@inkeep/open-knowledge 0.0.0-dev-20260424205527 → 0.0.0-dev-20260424220916

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/dist/constants-D89oLnWp.mjs +2 -0
  3. package/dist/index.mjs +1 -1
  4. package/dist/{init-DIbZ0Udv.mjs → init-BNgsPt1O.mjs} +3 -3
  5. package/dist/{init-i7vPAWv4.mjs → init-BRT4-mAi.mjs} +2 -2
  6. package/dist/init-CACF-cC-.mjs +1 -0
  7. package/dist/init-FeYpfkNJ.mjs +1 -0
  8. package/dist/loader-CHTgr19-.mjs +1 -0
  9. package/dist/{loader-CEfLKIxb.mjs → loader-D8Ft2dBj.mjs} +2 -2
  10. package/dist/paths-B_Ju9Fwm.mjs +1 -0
  11. package/dist/{paths-BN0gQKmX.mjs → paths-Dx9rYaqG.mjs} +2 -2
  12. package/dist/preview-BRnCHoKP.mjs +1 -0
  13. package/dist/{preview-BmSvc-WZ.mjs → preview-rzykMY4K.mjs} +2 -2
  14. package/dist/public/assets/ActivityModeContent-BNh4Pk40.js +2 -0
  15. package/dist/public/assets/ActivityPanelDiffView-DVyTW-J7.js +13 -0
  16. package/dist/public/assets/ActivityPanelDiffView-legcy4jI.css +1 -0
  17. package/dist/public/assets/DocumentContext-BKlAtvJh.js +5 -0
  18. package/dist/public/assets/GraphPanel-CBqnoz3m.js +46 -0
  19. package/dist/public/assets/McpConsentDialogBody-2PEhLTtI.js +1 -0
  20. package/dist/public/assets/{panel-jSlO39XJ.js → PageListContext-DdGQSVEJ.js} +76 -76
  21. package/dist/public/assets/SourceEditor-Bykgm2Df.js +3 -0
  22. package/dist/public/assets/agent-presence-BQu9C0ej.js +1 -0
  23. package/dist/public/assets/button-B1XQHQcX.js +1 -0
  24. package/dist/public/assets/clipboard-B7lAx5LI.js +32 -0
  25. package/dist/public/assets/compiler-runtime-Y11fyRVL.js +1 -0
  26. package/dist/public/assets/dialog-xzAlDsHy.js +45 -0
  27. package/dist/public/assets/{dist-Crc5NE1l.js → dist-BqO6NfD-.js} +1 -1
  28. package/dist/public/assets/{dist-DRn8lLJe.js → dist-CgLbXgrr.js} +1 -1
  29. package/dist/public/assets/{dist-BCB7v76S.js → dist-D2wwoXzm.js} +1 -1
  30. package/dist/public/assets/{dist-DF16X4DB.js → dist-DR1MrLJC.js} +1 -1
  31. package/dist/public/assets/{dist-Dx3W_u4i.js → dist-DeDgmJv2.js} +1 -1
  32. package/dist/public/assets/{dist-CjujjdB3.js → dist-DlS42TIP.js} +1 -1
  33. package/dist/public/assets/{dist-CDhLtkvx.js → dist-GlH2KPqY.js} +1 -1
  34. package/dist/public/assets/index-CQUn-INu.css +1 -0
  35. package/dist/public/assets/index-CfJ3Qwwv.js +27 -0
  36. package/dist/public/assets/panel-rtdrPcLu.js +1 -0
  37. package/dist/public/assets/{telemetry-impl-D_lLX0fS.js → telemetry-impl-BTqkcpTj.js} +2 -2
  38. package/dist/public/assets/toggle-group-B86VAmbm.js +1 -0
  39. package/dist/public/assets/tooltip-C2q723j6.js +1 -0
  40. package/dist/public/index.html +16 -11
  41. package/dist/{src-zcKwR9RH.mjs → src-BhGckK_W.mjs} +1 -1
  42. package/dist/{src-DBQiBMMB.mjs → src-C6N2KCTo.mjs} +22 -15
  43. package/dist/src-DdZqQcAX.mjs +1 -0
  44. package/dist/{start-J6AfuX7h.mjs → start-CnZPVF2R.mjs} +2 -2
  45. package/dist/start-DqIjcXQT.mjs +1 -0
  46. package/package.json +1 -1
  47. package/dist/constants-Dqmeg2oi.mjs +0 -2
  48. package/dist/init-3UxRGVAs.mjs +0 -1
  49. package/dist/init-AmgsVReV.mjs +0 -1
  50. package/dist/loader-CQUrJ6T-.mjs +0 -1
  51. package/dist/paths-HWNY8fZl.mjs +0 -1
  52. package/dist/preview-DzHGOZjd.mjs +0 -1
  53. package/dist/public/assets/GraphPanel-CMj_CKRD.js +0 -46
  54. package/dist/public/assets/McpConsentDialogBody-BpxsNx0A.js +0 -1
  55. package/dist/public/assets/SourceEditor-BSUZdSkZ.js +0 -3
  56. package/dist/public/assets/button-D7O9FEkM.js +0 -1
  57. package/dist/public/assets/clipboard-B0g7jEdf.js +0 -36
  58. package/dist/public/assets/dialog-DzmWgC4p.js +0 -45
  59. package/dist/public/assets/index-Bnp3jcJM.js +0 -27
  60. package/dist/public/assets/index-tR5M38z1.css +0 -1
  61. package/dist/public/assets/toggle-group-D0c1wSh_.js +0 -1
  62. package/dist/src-DjVVQCyp.mjs +0 -1
  63. package/dist/start-Dta5BSHL.mjs +0 -1
  64. /package/dist/public/assets/{__vite-browser-external-BFtnoaxY.js → __vite-browser-external-Dz2JgTKm.js} +0 -0
  65. /package/dist/public/assets/{go-BL7jA4zR.js → go-DatQmDtN.js} +0 -0
  66. /package/dist/public/assets/{shell-DKDblpGA.js → shell-7yok6dsz.js} +0 -0
  67. /package/dist/public/assets/{w3c-keyname-B56rf6AD.js → w3c-keyname-CSlwavrd.js} +0 -0
@@ -6,7 +6,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
6
6
  `}){let r=e.split(/\r?\n/);for(let e=1;e<r.length;e+=1)r[e]=t+r[e];return r.join(n)}})),require_parse_factory_options=__commonJSMin$1(((e,t)=>{t.exports=s;let{LEVEL_NAMES:n}=require_constants$5(),r=require_colors(),i=require_handle_custom_levels_opts(),a=require_handle_custom_levels_names_opts(),o=require_get_level_label_data();function s(e){let t=e.crlf?`\r
7
7
  `:`
8
8
  `,s=` `,{customPrettifiers:c,errorLikeObjectKeys:l,hideObject:u,levelFirst:d,levelKey:f,levelLabel:p,messageFormat:m,messageKey:h,minimumLevel:g,singleLine:_,timestampKey:v,translateTime:y}=e,b=e.errorProps.split(`,`),x=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,S=i(e.customLevels),C=a(e.customLevels),w=o(x,S,C),T;if(e.customColors)if(typeof e.customColors==`string`)T=e.customColors.split(`,`).reduce((t,r)=>{let[i,a]=r.split(`:`),o=(x?e.customLevels:C[i]!==void 0)?C[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else if(typeof e.customColors==`object`)T=Object.keys(e.customColors).reduce((t,r)=>{let[i,a]=[r,e.customColors[r]],o=(x?e.customLevels:C[i]!==void 0)?C[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let E={customLevels:S,customLevelNames:C};x===!0&&!e.customLevels&&(E.customLevels=void 0,E.customLevelNames=void 0);let D=e.include===void 0?void 0:new Set(e.include.split(`,`)),O=!D&&e.ignore?new Set(e.ignore.split(`,`)):void 0,k=r(e.colorize,T,x),A=e.colorizeObjects?k:r(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:k,customColors:T,customLevelNames:C,customLevels:S,customPrettifiers:c,customProperties:E,errorLikeObjectKeys:l,errorProps:b,getLevelLabelData:w,hideObject:u,ignoreKeys:O,includeKeys:D,levelFirst:d,levelKey:f,levelLabel:p,messageFormat:m,messageKey:h,minimumLevel:g,objectColorizer:A,singleLine:_,timestampKey:v,translateTime:y,useOnlyCustomProps:x}}})),require_fast_safe_stringify=__commonJSMin$1(((e,t)=>{t.exports=s,s.default=s,s.stable=d,s.stableStringify=d;var n=`[...]`,r=`[Circular]`,i=[],a=[];function o(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function s(e,t,n,r){r===void 0&&(r=o()),l(e,``,0,[],void 0,0,r);var s;try{s=a.length===0?JSON.stringify(e,t,n):JSON.stringify(e,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var c=i.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return s}function c(e,t,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get===void 0?(r[n]=e,i.push([r,n,t])):o.configurable?(Object.defineProperty(r,n,{value:e}),i.push([r,n,t,o])):a.push([t,n,e])}function l(e,t,i,a,o,s,u){s+=1;var d;if(typeof e==`object`&&e){for(d=0;d<a.length;d++)if(a[d]===e){c(r,e,t,o);return}if(u.depthLimit!==void 0&&s>u.depthLimit){c(n,e,t,o);return}if(u.edgesLimit!==void 0&&i+1>u.edgesLimit){c(n,e,t,o);return}if(a.push(e),Array.isArray(e))for(d=0;d<e.length;d++)l(e[d],d,d,a,e,s,u);else{var f=Object.keys(e);for(d=0;d<f.length;d++){var p=f[d];l(e[p],p,d,a,e,s,u)}}a.pop()}}function u(e,t){return e<t?-1:e>t?1:0}function d(e,t,n,r){r===void 0&&(r=o());var s=f(e,``,0,[],void 0,0,r)||e,c;try{c=a.length===0?JSON.stringify(s,t,n):JSON.stringify(s,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var l=i.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return c}function f(e,t,a,o,s,l,d){l+=1;var p;if(typeof e==`object`&&e){for(p=0;p<o.length;p++)if(o[p]===e){c(r,e,t,s);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(d.depthLimit!==void 0&&l>d.depthLimit){c(n,e,t,s);return}if(d.edgesLimit!==void 0&&a+1>d.edgesLimit){c(n,e,t,s);return}if(o.push(e),Array.isArray(e))for(p=0;p<e.length;p++)f(e[p],p,p,o,e,l,d);else{var m={},h=Object.keys(e).sort(u);for(p=0;p<h.length;p++){var g=h[p];f(e[g],g,p,o,e,l,d),m[g]=e[g]}if(s!==void 0)i.push([s,t,e]),s[t]=m;else return m}o.pop()}}function p(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(a.length>0)for(var r=0;r<a.length;r++){var i=a[r];if(i[1]===t&&i[0]===n){n=i[2],a.splice(r,1);break}}return e.call(this,t,n)}}})),require_prettify_error=__commonJSMin$1(((e,t)=>{t.exports=r;let n=require_join_lines_with_indentation();function r({keyName:e,lines:t,eol:r,ident:i}){let a=``,o=`${i}${e}: ${n({input:t,ident:i,eol:r})}${r}`.split(r);for(let e=0;e<o.length;e+=1){e!==0&&(a+=r);let t=o[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let n=/^\s*/.exec(t)[0].length+4,i=` `.repeat(n),o=e[2];a+=e[1]+r+i+JSON.parse(o).replace(/\n/g,r+i)}else a+=t}else a+=t}return a}})),require_prettify_object=__commonJSMin$1(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=require_constants$5(),r=require_fast_safe_stringify(),i=require_join_lines_with_indentation(),a=require_prettify_error();function o({log:e,excludeLoggerKeys:t=!0,skipKeys:o=[],context:s}){let{EOL:c,IDENT:l,customPrettifiers:u,errorLikeObjectKeys:d,objectColorizer:f,singleLine:p,colorizer:m}=s,h=[].concat(o);t===!0&&Array.prototype.push.apply(h,n);let g=``,{plain:_,errors:v}=Object.entries(e).reduce(({plain:t,errors:n},[r,i])=>{if(h.includes(r)===!1){let a=typeof u[r]==`function`?u[r](i,r,e,{colors:m.colors}):i;d.includes(r)?n[r]=a:t[r]=a}return{plain:t,errors:n}},{plain:{},errors:{}});return p?(Object.keys(_).length>0&&(g+=f.greyMessage(r(_))),g+=c,g=g.replace(/\\\\/gi,`\\`)):Object.entries(_).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);if(n===void 0)return;n=n.replace(/\\\\/gi,`\\`);let a=i({input:n,ident:l,eol:c});g+=`${l}${f.property(e)}:${a.startsWith(c)?``:` `}${a}${c}`}),Object.entries(v).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);n!==void 0&&(g+=a({keyName:e,lines:n,eol:c,ident:l}))}),g}})),require_prettify_error_log=__commonJSMin$1(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=require_constants$5(),r=require_is_object(),i=require_join_lines_with_indentation(),a=require_prettify_object();function o({log:e,context:t}){let{EOL:o,IDENT:s,errorProps:c,messageKey:l}=t,u=e.stack,d=`${s}${i({input:u,ident:s,eol:o})}${o}`;if(c.length>0){let i=n.concat(l,`type`,`stack`),u;u=c[0]===`*`?Object.keys(e).filter(e=>i.includes(e)===!1):c.filter(e=>i.includes(e)===!1);for(let n=0;n<u.length;n+=1){let i=u[n];if(i in e){if(r(e[i])){let n=a({log:e[i],excludeLoggerKeys:!1,context:{...t,IDENT:s+s}});d=`${d}${s}${i}: {${o}${n}${s}}${o}`;continue}d=`${d}${s}${i}: ${e[i]}${o}`}}}return d}})),require_prettify_level=__commonJSMin$1(((e,t)=>{t.exports=r;let n=require_get_property_value();function r({log:e,context:t}){let{colorizer:r,customLevels:i,customLevelNames:a,levelKey:o,getLevelLabelData:s}=t,c=t.customPrettifiers?.level,l=n(e,o);if(l===void 0)return;let u=r(l,{customLevels:i,customLevelNames:a});if(c){let[t]=s(l);return c(l,o,e,{label:t,labelColorized:u,colors:r.colors})}return u}})),require_prettify_message=__commonJSMin$1(((e,t)=>{t.exports=a;let{LEVELS:n}=require_constants$5(),r=require_get_property_value(),i=require_interpret_conditionals();function a({log:e,context:t}){let{colorizer:a,customLevels:o,levelKey:s,levelLabel:c,messageFormat:l,messageKey:u,useOnlyCustomProps:d}=t;if(l&&typeof l==`string`){let t=i(l,e),u=String(t).replace(/{([^{}]+)}/g,function(t,i){let a;if(i===c&&(a=r(e,s))!==void 0)return(d?o===void 0:o[a]===void 0)?n[a]:o[a];let l=r(e,i);return l===void 0?``:l});return a.message(u)}if(l&&typeof l==`function`){let t=l(e,u,c,{colors:a.colors});return a.message(t)}if(u in e&&!(typeof e[u]!=`string`&&typeof e[u]!=`number`&&typeof e[u]!=`boolean`))return a.message(e[u])}})),require_prettify_metadata=__commonJSMin$1(((e,t)=>{t.exports=n;function n({log:e,context:t}){let{customPrettifiers:n,colorizer:r}=t,i=``;if(e.name||e.pid||e.hostname){if(i+=`(`,e.name&&(i+=n.name?n.name(e.name,`name`,e,{colors:r.colors}):e.name),e.pid){let t=n.pid?n.pid(e.pid,`pid`,e,{colors:r.colors}):e.pid;e.name&&e.pid?i+=`/`+t:i+=t}if(e.hostname){let t=n.hostname?n.hostname(e.hostname,`hostname`,e,{colors:r.colors}):e.hostname;i+=`${i===`(`?`on`:` on`} ${t}`}i+=`)`}if(e.caller){let t=n.caller?n.caller(e.caller,`caller`,e,{colors:r.colors}):e.caller;i+=`${i===``?``:` `}<${t}>`}if(i!==``)return i}})),require_prettify_time=__commonJSMin$1(((e,t)=>{t.exports=r;let n=require_format_time();function r({log:e,context:t}){let{timestampKey:r,translateTime:i}=t,a=t.customPrettifiers?.time,o=null;if(r in e?o=e[r]:`timestamp`in e&&(o=e.timestamp),o===null)return;let s=i?n(o,i):o;return a?a(s):`[${s}]`}})),require_utils$15=__commonJSMin$1(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin$1(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),require_pretty=__commonJSMin$1(((e,t)=>{t.exports=h;let n=require_secure_json_parse(),r=require_is_object(),i=require_prettify_error_log(),a=require_prettify_level(),o=require_prettify_message(),s=require_prettify_metadata(),c=require_prettify_object(),l=require_prettify_time(),u=require_filter_log(),{LEVELS:d,LEVEL_KEY:f,LEVEL_NAMES:p}=require_constants$5(),m=e=>{try{return{value:n.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function h(e){let t;if(r(e))t=e;else{let n=m(e);if(n.err||!r(n.value))return e+this.EOL;t=n.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let n;if(n=e?this.customLevelNames[this.minimumLevel]:p[this.minimumLevel],n||=typeof this.minimumLevel==`string`?p[this.minimumLevel]:p[d[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?f:this.levelKey]<n)return}let n=o({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=u({log:t,context:this.context}));let h=a({log:t,context:{...this.context,...this.context.customProperties}}),g=s({log:t,context:this.context}),_=l({log:t,context:this.context}),v=``;if(this.levelFirst&&h&&(v=`${h}`),_&&v===``?v=`${_}`:_&&(v=`${v} ${_}`),!this.levelFirst&&h&&(v=v.length>0?`${v} ${h}`:h),g&&(v=v.length>0?`${v} ${g}:`:g),v.endsWith(`:`)===!1&&v!==``&&(v+=`:`),n!==void 0&&(v=v.length>0?`${v} ${n}`:n),v.length>0&&!this.singleLine&&(v+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=i({log:t,context:this.context});this.singleLine&&(v+=this.EOL),v+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),n=c({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(n)&&(v+=` `),v+=n}return v}})),require_pino_pretty=__commonJSMin$1(((e,t)=>{let{isColorSupported:n}=require_colorette(),r=require_pump(),{Transform:i}=__require$1(`node:stream`),a=require_pino_abstract_transport(),o=require_colors(),{ERROR_LIKE_KEYS:s,LEVEL_KEY:c,LEVEL_LABEL:l,MESSAGE_KEY:u,TIMESTAMP_KEY:d}=require_constants$5(),{buildSafeSonicBoom:f,parseFactoryOptions:p}=require_utils$15(),m=require_pretty(),h={colorize:n,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:s,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:c,levelLabel:l,messageFormat:null,messageKey:u,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:d,translateTime:!0,useOnlyCustomProps:!0};function g(e){let t=p(Object.assign({},h,e));return m.bind({...t,context:t})}function _(e={}){let t=g(e),n;return a(function(a){a.on(`message`,function n(r){!r||r.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:r.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||s,r.config.errorKey])),customLevels:r.config.levels.values}),t=g(e),a.off(`message`,n))});let o=new i({objectMode:!0,autoDestroy:!0,transform(e,n,r){r(null,t(e))}});return n=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:f({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),a.on(`unknown`,function(e){n.write(e+`
9
- `)}),r(a,o,n),o},{parse:`lines`,close(e,t){n.on(`close`,()=>{t(e)})}})}t.exports=_,t.exports.build=_,t.exports.PinoPretty=_,t.exports.prettyFactory=g,t.exports.colorizerFactory=o,t.exports.isColorSupported=n,t.exports.default=_}));init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1);function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let n;return n=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/;function validateAgentId(e){return typeof e!=`string`||e.length===0||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return`agent-${e}`}const counters={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0};function incrementReconcile(){counters.reconcileCount++}function incrementConflict(){counters.conflictCount++}function incrementBatch(){counters.batchCount++}function incrementUpstreamImport(){counters.upstreamImportCount++}function incrementRescueBuffer(){counters.rescueBufferCount++}function incrementBranchSwitch(){counters.branchSwitchCount++}function incrementPark(){counters.parkCount++}function incrementGitAutoSaveFailure(){counters.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters.serverObserverFiresA++:counters.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters.serverObserverErrorsA++:counters.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters.agentWriteCalls++}function incrementSummariesProvided(){counters.summariesProvided++}function incrementSummariesTruncated(){counters.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters.bridgeMergeCheckpointCreated++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters.collabSocketEpipeCount++:counters.collabSocketEconnresetCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters.cc1LastSeq[e]=t}function getMetrics(){return{...counters,cc1LastSeq:{...counters.cc1LastSeq}}}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const create$8=()=>new Map,copy=e=>{let t=create$8();return e.forEach((e,n)=>{t.set(n,e)}),t},setIfUndefined$1=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},any=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},create$7=()=>new Set,last=e=>e[e.length-1],appendTo=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},from$1=Array.from,some=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},isArray$1=Array.isArray;var ObservableV2=class{constructor(){this._observers=create$8()}on(e,t){return setIfUndefined$1(this._observers,e,create$7).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return from$1((this._observers.get(e)||create$8()).values()).forEach(e=>e(...t))}destroy(){this._observers=create$8()}};const floor$2=Math.floor,abs=Math.abs,min$2=(e,t)=>e<t?e:t,max$2=(e,t)=>e>t?e:t,isNaN$2=Number.isNaN,isNegativeZero=e=>e===0?1/e<0:e<0,BIT1=1,BIT2=2,BIT3=4,BIT4=8,BIT6=32,BIT7=64,BIT8$2=128,BIT18$2=1<<17,BIT19$2=1<<18,BIT20$2=1<<19,BIT21$2=1<<20,BIT22$2=1<<21,BIT23$2=1<<22,BIT24$2=1<<23,BIT25$2=1<<24,BIT26$2=1<<25,BIT27$2=1<<26,BIT28$2=1<<27,BIT29$2=1<<28,BIT30$2=1<<29,BIT31$2=1<<30,BITS5=31,BITS6=63,BITS7$2=127,BITS17=BIT18$2-1,BITS18=BIT19$2-1,BITS19=BIT20$2-1,BITS20=BIT21$2-1,BITS21=BIT22$2-1,BITS22=BIT23$2-1,BITS23=BIT24$2-1,BITS24=BIT25$2-1,BITS25=BIT26$2-1,BITS26=BIT27$2-1,BITS27=BIT28$2-1,BITS28=BIT29$2-1,BITS29=BIT30$2-1,BITS30=BIT31$2-1,BITS31=2147483647,BITS32=4294967295,MAX_SAFE_INTEGER$2=2**53-1,MIN_SAFE_INTEGER=-(2**53-1),HIGHEST_INT32=BITS31,HIGHEST_UINT32=BITS32,isInteger=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&floor$2(e)===e),isNaN$1=Number.isNaN,parseInt$1=Number.parseInt,fromCharCode$2=String.fromCharCode,fromCodePoint=String.fromCodePoint,MAX_UTF16_CHARACTER=fromCharCode$2(65535),toLowerCase=e=>e.toLowerCase(),trimLeftRegex=/^\s*/g,trimLeft=e=>e.replace(trimLeftRegex,``),fromCamelCaseRegex=/([A-Z])/g,fromCamelCase=(e,t)=>trimLeft(e.replace(fromCamelCaseRegex,e=>`${t}${toLowerCase(e)}`)),_encodeUtf8Polyfill$2=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder$2=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$2=e=>utf8TextEncoder$2.encode(e),encodeUtf8$2=utf8TextEncoder$2?_encodeUtf8Native$2:_encodeUtf8Polyfill$2;let utf8TextDecoder$2=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$2&&utf8TextDecoder$2.decode(new Uint8Array).length===1&&(utf8TextDecoder$2=null);var Encoder$1=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder$1=()=>new Encoder$1,encode=e=>{let t=createEncoder$1();return e(t),toUint8Array$1(t)},length$1=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},toUint8Array$1=e=>{let t=new Uint8Array(length$1(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},verifyLen=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(max$2(n,t)*2),e.cpos=0)},write$2=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeUint8=write$2,writeVarUint$2=(e,t)=>{for(;t>127;)write$2(e,128|127&t),t=floor$2(t/128);write$2(e,127&t)},writeVarInt=(e,t)=>{let n=isNegativeZero(t);for(n&&(t=-t),write$2(e,(t>63?128:0)|(n?64:0)|63&t),t=floor$2(t/64);t>0;)write$2(e,(t>127?128:0)|127&t),t=floor$2(t/128)},_strBuffer$2=new Uint8Array(3e4),_maxStrBSize$2=_strBuffer$2.length/3,_writeVarStringNative$2=(e,t)=>{if(t.length<_maxStrBSize$2){let n=utf8TextEncoder$2.encodeInto(t,_strBuffer$2).written||0;writeVarUint$2(e,n);for(let t=0;t<n;t++)write$2(e,_strBuffer$2[t])}else writeVarUint8Array$2(e,encodeUtf8$2(t))},_writeVarStringPolyfill$2=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint$2(e,r);for(let t=0;t<r;t++)write$2(e,n.codePointAt(t))},writeVarString$2=utf8TextEncoder$2&&utf8TextEncoder$2.encodeInto?_writeVarStringNative$2:_writeVarStringPolyfill$2,writeUint8Array$2=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min$2(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$2(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array$2=(e,t)=>{writeVarUint$2(e,t.byteLength),writeUint8Array$2(e,t)},writeOnDataView=(e,t)=>{verifyLen(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},writeFloat32=(e,t)=>writeOnDataView(e,4).setFloat32(0,t,!1),writeFloat64=(e,t)=>writeOnDataView(e,8).setFloat64(0,t,!1),writeBigInt64=(e,t)=>writeOnDataView(e,8).setBigInt64(0,t,!1),floatTestBed=new DataView(new ArrayBuffer(4)),isFloat32=e=>(floatTestBed.setFloat32(0,e),floatTestBed.getFloat32(0)===e),writeAny=(e,t)=>{switch(typeof t){case`string`:write$2(e,119),writeVarString$2(e,t);break;case`number`:isInteger(t)&&abs(t)<=2147483647?(write$2(e,125),writeVarInt(e,t)):isFloat32(t)?(write$2(e,124),writeFloat32(e,t)):(write$2(e,123),writeFloat64(e,t));break;case`bigint`:write$2(e,122),writeBigInt64(e,t);break;case`object`:if(t===null)write$2(e,126);else if(isArray$1(t)){write$2(e,117),writeVarUint$2(e,t.length);for(let n=0;n<t.length;n++)writeAny(e,t[n])}else if(t instanceof Uint8Array)write$2(e,116),writeVarUint8Array$2(e,t);else{write$2(e,118);let n=Object.keys(t);writeVarUint$2(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];writeVarString$2(e,i),writeAny(e,t[i])}}break;case`boolean`:write$2(e,t?120:121);break;default:write$2(e,127)}};var RleEncoder=class extends Encoder$1{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&writeVarUint$2(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const flushUintOptRleEncoder=e=>{e.count>0&&(writeVarInt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&writeVarUint$2(e.encoder,e.count-2))};var UintOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0}write(e){this.s===e?this.count++:(flushUintOptRleEncoder(this),this.count=1,this.s=e)}toUint8Array(){return flushUintOptRleEncoder(this),toUint8Array$1(this.encoder)}};const flushIntDiffOptRleEncoder=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);writeVarInt(e.encoder,t),e.count>1&&writeVarUint$2(e.encoder,e.count-2)}};var IntDiffOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(flushIntDiffOptRleEncoder(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return flushIntDiffOptRleEncoder(this),toUint8Array$1(this.encoder)}},StringEncoder=class{constructor(){this.sarr=[],this.s=``,this.lensE=new UintOptRleEncoder}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Encoder$1;return this.sarr.push(this.s),this.s=``,writeVarString$2(e,this.sarr.join(``)),writeUint8Array$2(e,this.lensE.toUint8Array()),toUint8Array$1(e)}};const create$6=e=>Error(e),methodUnimplemented=()=>{throw create$6(`Method unimplemented`)},unexpectedCase=()=>{throw create$6(`Unexpected case`)},errorUnexpectedEndOfArray$2=create$6(`Unexpected end of array`),errorIntegerOutOfRange$2=create$6(`Integer out of Range`);var Decoder$1=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder$1=e=>new Decoder$1(e),hasContent$1=e=>e.pos!==e.arr.length,readUint8Array$1=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},readVarUint8Array$1=e=>readUint8Array$1(e,readVarUint$1(e)),readUint8$1=e=>e.arr[e.pos++],readVarUint$1=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},readVarInt=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},_readVarStringPolyfill$1=e=>{let t=readVarUint$1(e);if(t===0)return``;{let n=String.fromCodePoint(readUint8$1(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(readUint8$1(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_readVarStringNative$1=e=>utf8TextDecoder$2.decode(readVarUint8Array$1(e)),readVarString$1=utf8TextDecoder$2?_readVarStringNative$1:_readVarStringPolyfill$1,readFromDataView=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},readFloat32=e=>readFromDataView(e,4).getFloat32(0,!1),readFloat64=e=>readFromDataView(e,8).getFloat64(0,!1),readBigInt64=e=>readFromDataView(e,8).getBigInt64(0,!1),readAnyLookupTable=[e=>void 0,e=>null,readVarInt,readFloat32,readFloat64,readBigInt64,e=>!1,e=>!0,readVarString$1,e=>{let t=readVarUint$1(e),n={};for(let r=0;r<t;r++){let t=readVarString$1(e);n[t]=readAny(e)}return n},e=>{let t=readVarUint$1(e),n=[];for(let r=0;r<t;r++)n.push(readAny(e));return n},readVarUint8Array$1],readAny=e=>readAnyLookupTable[127-readUint8$1(e)](e);var RleDecoder=class extends Decoder$1{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hasContent$1(this)?this.count=readVarUint$1(this)+1:this.count=-1),this.count--,this.s}},UintOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=readVarInt(this);let e=isNegativeZero(this.s);this.count=1,e&&(this.s=-this.s,this.count=readVarUint$1(this)+2)}return this.count--,this.s}},IntDiffOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=readVarInt(this),t=e&1;this.diff=floor$2(e/2),this.count=1,t&&(this.count=readVarUint$1(this)+2)}return this.s+=this.diff,this.count--,this.s}},StringDecoder=class{constructor(e){this.decoder=new UintOptRleDecoder(e),this.str=readVarString$1(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};const subtle=webcrypto.subtle,getRandomValues=webcrypto.getRandomValues.bind(webcrypto),uint32=()=>getRandomValues(new Uint32Array(1))[0],uuidv4Template=`10000000-1000-4000-8000-100000000000`,uuidv4=()=>uuidv4Template.replace(/[018]/g,e=>(e^uint32()&15>>e/4).toString(16)),getUnixTime$1=Date.now,create$5=e=>new Promise(e),all=Promise.all.bind(Promise),undefinedToNull=e=>e===void 0?null:e;var VarStoragePolyfill=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};let _localStorage=new VarStoragePolyfill,usePolyfill=!0;try{typeof localStorage<`u`&&localStorage&&(_localStorage=localStorage)}catch{}const varStorage=_localStorage,EqualityTraitSymbol$1=Symbol(`Equality`),equals=(e,t)=>e===t||!!e?.[EqualityTraitSymbol$1]?.(t)||!1,assign=Object.assign,keys$1=Object.keys,forEach=(e,t)=>{for(let n in e)t(e[n],n)},size$1=e=>keys$1(e).length,isEmpty=e=>{for(let t in e)return!1;return!0},every=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},hasProperty$1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalFlat=(e,t)=>e===t||size$1(e)===size$1(t)&&every(e,(e,n)=>(e!==void 0||hasProperty$1(t,n))&&equals(t[n],e)),freeze=Object.freeze,deepFreeze=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&deepFreeze(e[t])}return freeze(e)},callAll=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&callAll(e,t,n+1)}},id=e=>e,isOneOf=(e,t)=>t.includes(e),isArray=isArray$1,isNode=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,isBrowser=typeof window<`u`&&typeof document<`u`&&!isNode,isMac=typeof navigator<`u`?/Mac/.test(navigator.platform):!1;let params;const args=[],computeParams=()=>{if(params===void 0)if(isNode){params=create$8();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&params.set(t,``),t=r):t===null?args.push(r):(params.set(t,r),t=null)}t!==null&&params.set(t,``)}else typeof location==`object`?(params=create$8(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);params.set(`--${fromCamelCase(t,`-`)}`,n),params.set(`-${fromCamelCase(t,`-`)}`,n)}})):params=create$8();return params},hasParam=e=>computeParams().has(e),getVariable=e=>undefinedToNull(isNode?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:varStorage.getItem(e)),hasConf=e=>hasParam(`--`+e)||getVariable(e)!==null,production=hasConf(`production`),forceColor=isNode&&isOneOf(process.env.FORCE_COLOR,[`true`,`1`,`2`]),supportsColor=forceColor||!hasParam(`--no-colors`)&&!hasConf(`no-color`)&&(!isNode||process.stdout.isTTY)&&(!isNode||hasParam(`--color`)||getVariable(`COLORTERM`)!==null||(getVariable(`TERM`)||``).includes(`color`)),createUint8ArrayFromLen=e=>new Uint8Array(e),createUint8ArrayViewFromArrayBuffer=(e,t,n)=>new Uint8Array(e,t,n),toBase64Browser=e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=fromCharCode$2(e[n]);return btoa(t)},toBase64Node=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),fromBase64Browser=e=>{let t=atob(e),n=createUint8ArrayFromLen(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},fromBase64Node=e=>{let t=Buffer.from(e,`base64`);return createUint8ArrayViewFromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)},toBase64=isBrowser?toBase64Browser:toBase64Node,fromBase64=isBrowser?fromBase64Browser:fromBase64Node,copyUint8Array=e=>{let t=createUint8ArrayFromLen(e.byteLength);return t.set(e),t},encodeAny=e=>encode(t=>writeAny(t,e)),create$4=Symbol,BOLD=create$4(),UNBOLD=create$4(),BLUE=create$4(),GREY=create$4(),GREEN=create$4(),RED=create$4(),PURPLE=create$4(),ORANGE=create$4(),UNCOLOR=create$4(),computeNoColorLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};let lastLoggingTime=getUnixTime$1();const _nodeStyleMap={[BOLD]:`\x1B[1m`,[UNBOLD]:`\x1B[2m`,[BLUE]:`\x1B[34m`,[GREEN]:`\x1B[32m`,[GREY]:`\x1B[37m`,[RED]:`\x1B[31m`,[PURPLE]:`\x1B[35m`,[ORANGE]:`\x1B[38;5;208m`,[UNCOLOR]:`\x1B[0m`},computeNodeLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r],i=_nodeStyleMap[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n},computeLoggingArgs=supportsColor?computeNodeLoggingArgs:computeNoColorLoggingArgs,print=(...e)=>{console.log(...computeLoggingArgs(e))},warn=(...e)=>{console.warn(...computeLoggingArgs(e))},createIterator=e=>({[Symbol.iterator](){return this},next:e}),iteratorFilter=(e,t)=>createIterator(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),iteratorMap=(e,t)=>createIterator(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var DeleteItem=class{constructor(e,t){this.clock=e,this.len=t}},DeleteSet=class{constructor(){this.clients=new Map}};const iterateDeletedStructs=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])iterateStructs(e,i,o.clock,o.len,n)}}),findIndexDS=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=floor$2((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},isDeleted=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&findIndexDS(n,t.clock)!==null},sortAndMergeDeleteSet=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new DeleteItem(r.clock,max$2(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},mergeDeleteSets=e=>{let t=new DeleteSet;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)appendTo(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return sortAndMergeDeleteSet(t),t},addToDeleteSet=(e,t,n,r)=>{setIfUndefined$1(e.clients,t,()=>[]).push(new DeleteItem(n,r))},createDeleteSet=()=>new DeleteSet,createDeleteSetFromStructStore=e=>{let t=createDeleteSet();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new DeleteItem(i,a))}}r.length>0&&t.clients.set(n,r)}),t},writeDeleteSet=(e,t)=>{writeVarUint$2(e.restEncoder,t.clients.size),from$1(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),writeVarUint$2(e.restEncoder,t);let r=n.length;writeVarUint$2(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},readDeleteSet=e=>{let t=new DeleteSet,n=readVarUint$1(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=readVarUint$1(e.restDecoder),r=readVarUint$1(e.restDecoder);if(r>0){let i=setIfUndefined$1(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new DeleteItem(e.readDsClock(),e.readDsLen()))}}return t},readAndApplyDeleteSet=(e,t,n)=>{let r=new DeleteSet,i=readVarUint$1(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=readVarUint$1(e.restDecoder),a=readVarUint$1(e.restDecoder),o=n.clients.get(i)||[],s=getState(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&addToDeleteSet(r,i,s,a-s);let e=findIndexSS(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,splitItem(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,splitItem(t,c,a-c.id.clock)),c.delete(t))}else addToDeleteSet(r,i,n,a-n)}}if(r.clients.size>0){let e=new UpdateEncoderV2;return writeVarUint$2(e.restEncoder,0),writeDeleteSet(e,r),e.toUint8Array()}return null},equalDeleteSets=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},generateNewClientId=uint32;var Doc=class e extends ObservableV2{constructor({guid:e=uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=generateNewClientId(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new StructStore,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=create$5(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>create$5(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&transact(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(from$1(this.subdocs).map(e=>e.guid))}transact(e,t=null){return transact(this,e,t)}get(e,t=AbstractType){let n=setIfUndefined$1(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==AbstractType&&r!==t)if(r===AbstractType){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,YArray)}getText(e=``){return this.get(e,YText)}getMap(e=``){return this.get(e,YMap)}getXmlElement(e=``){return this.get(e,YXmlElement)}getXmlFragment(e=``){return this.get(e,YXmlFragment)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,from$1(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,transact(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},DSDecoderV1=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return readVarUint$1(this.restDecoder)}readDsLen(){return readVarUint$1(this.restDecoder)}},UpdateDecoderV1=class extends DSDecoderV1{readLeftID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readRightID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readClient(){return readVarUint$1(this.restDecoder)}readInfo(){return readUint8$1(this.restDecoder)}readString(){return readVarString$1(this.restDecoder)}readParentInfo(){return readVarUint$1(this.restDecoder)===1}readTypeRef(){return readVarUint$1(this.restDecoder)}readLen(){return readVarUint$1(this.restDecoder)}readAny(){return readAny(this.restDecoder)}readBuf(){return copyUint8Array(readVarUint8Array$1(this.restDecoder))}readJSON(){return JSON.parse(readVarString$1(this.restDecoder))}readKey(){return readVarString$1(this.restDecoder)}},DSDecoderV2=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=readVarUint$1(this.restDecoder),this.dsCurrVal}readDsLen(){let e=readVarUint$1(this.restDecoder)+1;return this.dsCurrVal+=e,e}},UpdateDecoderV2=class extends DSDecoderV2{constructor(e){super(e),this.keys=[],readVarUint$1(e),this.keyClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.clientDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.leftClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.rightClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.infoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.stringDecoder=new StringDecoder(readVarUint8Array$1(e)),this.parentInfoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.typeRefDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.lenDecoder=new UintOptRleDecoder(readVarUint8Array$1(e))}readLeftID(){return new ID(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ID(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return readAny(this.restDecoder)}readBuf(){return readVarUint8Array$1(this.restDecoder)}readJSON(){return readAny(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},DSEncoderV1=class{constructor(){this.restEncoder=createEncoder$1()}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){writeVarUint$2(this.restEncoder,e)}writeDsLen(e){writeVarUint$2(this.restEncoder,e)}},UpdateEncoderV1=class extends DSEncoderV1{writeLeftID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeRightID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeClient(e){writeVarUint$2(this.restEncoder,e)}writeInfo(e){writeUint8(this.restEncoder,e)}writeString(e){writeVarString$2(this.restEncoder,e)}writeParentInfo(e){writeVarUint$2(this.restEncoder,e?1:0)}writeTypeRef(e){writeVarUint$2(this.restEncoder,e)}writeLen(e){writeVarUint$2(this.restEncoder,e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeVarString$2(this.restEncoder,JSON.stringify(e))}writeKey(e){writeVarString$2(this.restEncoder,e)}},DSEncoderV2=class{constructor(){this.restEncoder=createEncoder$1(),this.dsCurrVal=0}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,writeVarUint$2(this.restEncoder,t)}writeDsLen(e){e===0&&unexpectedCase(),writeVarUint$2(this.restEncoder,e-1),this.dsCurrVal+=e}},UpdateEncoderV2=class extends DSEncoderV2{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new IntDiffOptRleEncoder,this.clientEncoder=new UintOptRleEncoder,this.leftClockEncoder=new IntDiffOptRleEncoder,this.rightClockEncoder=new IntDiffOptRleEncoder,this.infoEncoder=new RleEncoder(writeUint8),this.stringEncoder=new StringEncoder,this.parentInfoEncoder=new RleEncoder(writeUint8),this.typeRefEncoder=new UintOptRleEncoder,this.lenEncoder=new UintOptRleEncoder}toUint8Array(){let e=createEncoder$1();return writeVarUint$2(e,0),writeVarUint8Array$2(e,this.keyClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.clientEncoder.toUint8Array()),writeVarUint8Array$2(e,this.leftClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.rightClockEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.infoEncoder)),writeVarUint8Array$2(e,this.stringEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.parentInfoEncoder)),writeVarUint8Array$2(e,this.typeRefEncoder.toUint8Array()),writeVarUint8Array$2(e,this.lenEncoder.toUint8Array()),writeUint8Array$2(e,toUint8Array$1(this.restEncoder)),toUint8Array$1(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeAny(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const writeStructs=(e,t,n,r)=>{r=max$2(r,t[0].id.clock);let i=findIndexSS(t,r);writeVarUint$2(e.restEncoder,t.length-i),e.writeClient(n),writeVarUint$2(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},writeClientsStructs=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{getState(t,n)>e&&r.set(n,e)}),getStateVector(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),writeVarUint$2(e.restEncoder,r.size),from$1(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{writeStructs(e,t.clients.get(n),n,r)})},readClientsStructRefs=(e,t)=>{let n=create$8(),r=readVarUint$1(e.restDecoder);for(let i=0;i<r;i++){let r=readVarUint$1(e.restDecoder),i=Array(r),a=e.readClient(),o=readVarUint$1(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new GC(createID(a,o),t),o+=t;break}case 10:{let t=readVarUint$1(e.restDecoder);i[n]=new Skip(createID(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new Item(createID(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,readItemContent(e,r));i[n]=c,o+=c.length}}}}return n},integrateStructs=(e,t,n)=>{let r=[],i=from$1(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new StructStore,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Skip){let i=setIfUndefined$1(d,u.id.client,()=>getState(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,getState(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new UpdateEncoderV2;return writeClientsStructs(e,s,new Map),writeVarUint$2(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},writeStructsFromTransaction=(e,t)=>writeClientsStructs(e,t.doc.store,t.beforeState),readUpdateV2=(e,t,n,r=new UpdateDecoderV2(e))=>transact(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=integrateStructs(e,i,readClientsStructRefs(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<getState(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=mergeUpdatesV2([o.update,a.update])}}else i.pendingStructs=a;let s=readAndApplyDeleteSet(r,e,i);if(i.pendingDs){let t=new UpdateDecoderV2(createDecoder$1(i.pendingDs));readVarUint$1(t.restDecoder);let n=readAndApplyDeleteSet(t,e,i);s&&n?i.pendingDs=mergeUpdatesV2([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,applyUpdateV2(e.doc,t)}},n,!1),applyUpdateV2=(e,t,n,r=UpdateDecoderV2)=>{let i=createDecoder$1(t);readUpdateV2(i,e,n,new r(i))},applyUpdate=(e,t,n)=>applyUpdateV2(e,t,n,UpdateDecoderV1),writeStateAsUpdate=(e,t,n=new Map)=>{writeClientsStructs(e,t.store,n),writeDeleteSet(e,createDeleteSetFromStructStore(t.store))},encodeStateAsUpdateV2=(e,t=new Uint8Array([0]),n=new UpdateEncoderV2)=>{writeStateAsUpdate(n,e,decodeStateVector(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(diffUpdateV2(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===UpdateEncoderV1)return mergeUpdates(r.map((e,t)=>t===0?e:convertUpdateFormatV2ToV1(e)));if(n.constructor===UpdateEncoderV2)return mergeUpdatesV2(r)}return r[0]},encodeStateAsUpdate=(e,t)=>encodeStateAsUpdateV2(e,t,new UpdateEncoderV1),readStateVector=e=>{let t=new Map,n=readVarUint$1(e.restDecoder);for(let r=0;r<n;r++){let n=readVarUint$1(e.restDecoder),r=readVarUint$1(e.restDecoder);t.set(n,r)}return t},decodeStateVector=e=>readStateVector(new DSDecoderV1(createDecoder$1(e))),writeStateVector=(e,t)=>(writeVarUint$2(e.restEncoder,t.size),from$1(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{writeVarUint$2(e.restEncoder,t),writeVarUint$2(e.restEncoder,n)}),e),writeDocumentStateVector=(e,t)=>writeStateVector(e,getStateVector(t.store)),encodeStateVectorV2=(e,t=new DSEncoderV2)=>(e instanceof Map?writeStateVector(t,e):writeDocumentStateVector(t,e),t.toUint8Array()),encodeStateVector=e=>encodeStateVectorV2(e,new DSEncoderV1);var EventHandler=class{constructor(){this.l=[]}};const createEventHandler=()=>new EventHandler,addEventHandlerListener=(e,t)=>e.l.push(t),removeEventHandlerListener=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},callEventHandlerListeners=(e,t,n)=>callAll(e.l,[t,n]);var ID=class{constructor(e,t){this.client=e,this.clock=t}};const compareIDs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,createID=(e,t)=>new ID(e,t),findRootTypeKey=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw unexpectedCase()},isParentOf=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Snapshot=class{constructor(e,t){this.ds=e,this.sv=t}};const createSnapshot=(e,t)=>new Snapshot(e,t),emptySnapshot=createSnapshot(createDeleteSet(),new Map),snapshot=e=>createSnapshot(createDeleteSetFromStructStore(e.store),getStateVector(e.store)),isVisible$1=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!isDeleted(t.ds,e.id),splitSnapshotAffectedStructs=(e,t)=>{let n=setIfUndefined$1(e.meta,splitSnapshotAffectedStructs,create$7),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<getState(r,n)&&getItemCleanStart(e,createID(n,t))}),iterateDeletedStructs(e,t.ds,e=>{}),n.add(t))},snapshotContainsUpdateV2=(e,t,n=UpdateDecoderV2)=>{let r=new n(createDecoder$1(t)),i=new LazyStructReader(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=mergeDeleteSets([e.ds,readDeleteSet(r)]);return equalDeleteSets(e.ds,a)},snapshotContainsUpdate=(e,t)=>snapshotContainsUpdateV2(e,t,UpdateDecoderV1);var StructStore=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const getStateVector=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},getState=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},addStruct=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw unexpectedCase()}n.push(t)},findIndexSS=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=floor$2(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=floor$2((n+r)/2)}throw unexpectedCase()},find=(e,t)=>{let n=e.clients.get(t.client);return n[findIndexSS(n,t.clock)]},getItem=find,findIndexCleanStart=(e,t,n)=>{let r=findIndexSS(t,n),i=t[r];return i.id.clock<n&&i instanceof Item?(t.splice(r+1,0,splitItem(e,i,n-i.id.clock)),r+1):r},getItemCleanStart=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[findIndexCleanStart(e,n,t.clock)]},getItemCleanEnd=(e,t,n)=>{let r=t.clients.get(n.client),i=findIndexSS(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==GC&&r.splice(i+1,0,splitItem(e,a,n.clock-a.id.clock+1)),a},replaceStruct=(e,t,n)=>{let r=e.clients.get(t.id.client);r[findIndexSS(r,t.id.clock)]=n},iterateStructs=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=findIndexCleanStart(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&findIndexCleanStart(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Transaction=class{constructor(e,t,n){this.doc=e,this.deleteSet=new DeleteSet,this.beforeState=getStateVector(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const writeUpdateMessageFromTransaction=(e,t)=>t.deleteSet.clients.size===0&&!any(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(sortAndMergeDeleteSet(t.deleteSet),writeStructsFromTransaction(e,t),writeDeleteSet(e,t.deleteSet),!0),addChangedTypeToTransaction=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&setIfUndefined$1(e.changed,t,create$7).add(n)},tryToMergeWithLefts=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Item&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},tryGcDeleteSet=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=findIndexSS(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Item&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},tryMergeDeleteSet=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=min$2(r.length-1,1+findIndexSS(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+tryToMergeWithLefts(r,e)}})},cleanupTransactions=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{sortAndMergeDeleteSet(a),n.afterState=getStateVector(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{callEventHandlerListeners(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&cleanupYTextAfterTransaction(n)})}),callAll(e,[])}finally{r.gc&&tryGcDeleteSet(a,i,r.gcFilter),tryMergeDeleteSet(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=max$2(findIndexSS(e,r),1);for(let t=e.length-1;t>=n;)t-=1+tryToMergeWithLefts(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=findIndexSS(r,n);a+1<r.length&&tryToMergeWithLefts(r,a+1)>1||a>0&&tryToMergeWithLefts(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(print(ORANGE,BOLD,`[yjs] `,UNBOLD,RED,`Changed the client-id because another client seems to be using it.`),r.clientID=generateNewClientId()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new UpdateEncoderV1;writeUpdateMessageFromTransaction(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new UpdateEncoderV2;writeUpdateMessageFromTransaction(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):cleanupTransactions(e,t+1)}}},transact=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Transaction(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&cleanupTransactions(i,0)}}return o};var StackItem=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const clearUndoManagerStackItem=(e,t,n)=>{iterateDeletedStructs(e,n.deletions,n=>{n instanceof Item&&t.scope.some(t=>t===e.doc||isParentOf(t,n))&&keepItem(n,!1)})},popStackItem=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;transact(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;iterateDeletedStructs(n,o.insertions,e=>{if(e instanceof Item){if(e.redone!==null){let{item:t,diff:i}=followRedone(r,e.id);i>0&&(t=getItemCleanStart(n,createID(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||isParentOf(t,e))&&c.push(e)}}),iterateDeletedStructs(n,o.deletions,e=>{e instanceof Item&&a.some(t=>t===n.doc||isParentOf(t,e))&&!isDeleted(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=redoItem(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var UndoManager=class extends ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=isArray$1(e)?e[0].doc:e instanceof Doc?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new DeleteSet;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&addToDeleteSet(i,n,r,a)});let a=getUnixTime$1(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=mergeDeleteSets([t.deletions,e.deleteSet]),t.insertions=mergeDeleteSets([t.insertions,i])}else r.push(new StackItem(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),iterateDeletedStructs(e,e.deleteSet,t=>{t instanceof Item&&this.scope.some(n=>n===e.doc||isParentOf(n,t))&&keepItem(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=isArray$1(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof AbstractType?e.doc!==this.doc:e!==this.doc)&&warn(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>clearUndoManagerStackItem(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>clearUndoManagerStackItem(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=popStackItem(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=popStackItem(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*lazyStructReaderGenerator(e){let t=readVarUint$1(e.restDecoder);for(let n=0;n<t;n++){let t=readVarUint$1(e.restDecoder),n=e.readClient(),r=readVarUint$1(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=readVarUint$1(e.restDecoder);yield new Skip(createID(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new Item(createID(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,readItemContent(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new GC(createID(n,r),t),r+=t}}}}var LazyStructReader=class{constructor(e,t){this.gen=lazyStructReaderGenerator(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Skip);return this.curr}},LazyStructWriter=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const mergeUpdates=e=>mergeUpdatesV2(e,UpdateDecoderV1,UpdateEncoderV1),sliceStruct=(e,t)=>{if(e.constructor===GC){let{client:n,clock:r}=e.id;return new GC(createID(n,r+t),e.length-t)}else if(e.constructor===Skip){let{client:n,clock:r}=e.id;return new Skip(createID(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new Item(createID(r,i+t),null,createID(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},mergeUpdatesV2=(e,t=UpdateDecoderV2,n=UpdateEncoderV2)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(createDecoder$1(e))),i=r.map(e=>new LazyStructReader(e,!0)),a=null,o=new n,s=new LazyStructWriter(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Skip?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===Skip)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{writeStructToLazyStructWriter(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Skip(createID(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Skip?a.struct.length-=t:n=sliceStruct(n,t)),a.struct.mergeWith(n)||(writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Skip;n=e.next())writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(writeStructToLazyStructWriter(s,a.struct,a.offset),a=null),finishLazyStructWriting(s),writeDeleteSet(o,mergeDeleteSets(r.map(e=>readDeleteSet(e)))),o.toUint8Array()},diffUpdateV2=(e,t,n=UpdateDecoderV2,r=UpdateEncoderV2)=>{let i=decodeStateVector(t),a=new r,o=new LazyStructWriter(a),s=new n(createDecoder$1(e)),c=new LazyStructReader(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Skip){c.next();continue}if(e.id.clock+e.length>n)for(writeStructToLazyStructWriter(o,e,max$2(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)writeStructToLazyStructWriter(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return finishLazyStructWriting(o),writeDeleteSet(a,readDeleteSet(s)),a.toUint8Array()},flushLazyStructWriter=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:toUint8Array$1(e.encoder.restEncoder)}),e.encoder.restEncoder=createEncoder$1(),e.written=0)},writeStructToLazyStructWriter=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&flushLazyStructWriter(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),writeVarUint$2(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},finishLazyStructWriting=e=>{flushLazyStructWriter(e);let t=e.encoder.restEncoder;writeVarUint$2(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];writeVarUint$2(t,r.written),writeUint8Array$2(t,r.restEncoder)}},convertUpdateFormat=(e,t,n,r)=>{let i=new n(createDecoder$1(e)),a=new LazyStructReader(i,!1),o=new r,s=new LazyStructWriter(o);for(let e=a.curr;e!==null;e=a.next())writeStructToLazyStructWriter(s,t(e),0);return finishLazyStructWriting(s),writeDeleteSet(o,readDeleteSet(i)),o.toUint8Array()},convertUpdateFormatV2ToV1=e=>convertUpdateFormat(e,id,UpdateDecoderV2,UpdateEncoderV1),errorComputeChanges=`You must not compute changes after the event-handler fired.`;var YEvent=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=getPathTo(this.currentTarget,this.target)}deletes(e){return isDeleted(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=last(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=last(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=last(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let t=this.target,n=create$7(),r=create$7(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const getPathTo=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},warnPrematureAccess=()=>{warn(`Invalid access: Add Yjs type to a document before reading data.`)},maxSearchMarker=80;let globalSearchMarkerTimestamp=0;var ArraySearchMarker=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=globalSearchMarkerTimestamp++}};const refreshMarkerTimestamp=e=>{e.timestamp=globalSearchMarkerTimestamp++},overwriteMarker=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=globalSearchMarkerTimestamp++},markPosition=(e,t,n)=>{if(e.length>=maxSearchMarker){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return overwriteMarker(r,t,n),r}else{let r=new ArraySearchMarker(t,n);return e.push(r),r}},findMarker=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>abs(t-e.index)<abs(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,refreshMarkerTimestamp(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&abs(n.index-i)<r.parent.length/maxSearchMarker?(overwriteMarker(n,r,i),n):markPosition(e._searchMarker,r,i)},updateMarkerChanges=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=max$2(t,i.index+n))}},callTypeObservers=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;setIfUndefined$1(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;callEventHandlerListeners(r._eH,n,t)};var AbstractType=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=createEventHandler(),this._dEH=createEventHandler(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw methodUnimplemented()}clone(){throw methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){addEventHandlerListener(this._eH,e)}observeDeep(e){addEventHandlerListener(this._dEH,e)}unobserve(e){removeEventHandlerListener(this._eH,e)}unobserveDeep(e){removeEventHandlerListener(this._dEH,e)}toJSON(){}};const typeListSlice=(e,t,n)=>{e.doc??warnPrematureAccess(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},typeListToArray=e=>{e.doc??warnPrematureAccess();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},typeListToArraySnapshot=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&isVisible$1(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},typeListForEach=(e,t)=>{let n=0,r=e._start;for(e.doc??warnPrematureAccess();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},typeListMap=(e,t)=>{let n=[];return typeListForEach(e,(r,i)=>{n.push(t(r,i,e))}),n},typeListCreateIterator=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},typeListGet=(e,t)=>{e.doc??warnPrematureAccess();let n=findMarker(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},typeListInsertGenericsAfter=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentAny(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentBinary(new Uint8Array(n))),i.integrate(e,0);break;case Doc:i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentDoc(n)),i.integrate(e,0);break;default:if(n instanceof AbstractType)i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentType(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},lengthExceeded=()=>create$6(`Length exceeded!`),typeListInsertGenerics=(e,t,n,r)=>{if(n>t._length)throw lengthExceeded();if(n===0)return t._searchMarker&&updateMarkerChanges(t._searchMarker,n,r.length),typeListInsertGenericsAfter(e,t,null,r);let i=n,a=findMarker(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&getItemCleanStart(e,createID(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&updateMarkerChanges(t._searchMarker,i,r.length),typeListInsertGenericsAfter(e,t,o,r)},typeListPushGenerics=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return typeListInsertGenericsAfter(e,t,r,n)},typeListDelete=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=findMarker(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&getItemCleanStart(e,createID(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&getItemCleanStart(e,createID(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw lengthExceeded();t._searchMarker&&updateMarkerChanges(t._searchMarker,i,-a+r)},typeMapDelete=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},typeMapSet=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new ContentAny([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new ContentAny([r]);break;case Uint8Array:s=new ContentBinary(r);break;case Doc:s=new ContentDoc(r);break;default:if(r instanceof AbstractType)s=new ContentType(r);else throw Error(`Unexpected content type`)}new Item(createID(o,getState(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},typeMapGet=(e,t)=>{e.doc??warnPrematureAccess();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},typeMapGetAll=e=>{let t={};return e.doc??warnPrematureAccess(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},typeMapHas=(e,t)=>{e.doc??warnPrematureAccess();let n=e._map.get(t);return n!==void 0&&!n.deleted},typeMapGetAllSnapshot=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&isVisible$1(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},createMapIterator=e=>(e.doc??warnPrematureAccess(),iteratorFilter(e._map.entries(),e=>!e[1].deleted));var YArrayEvent=class extends YEvent{},YArray=class e extends AbstractType{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._length}_callObserver(e,t){super._callObserver(e,t),callTypeObservers(this,e,new YArrayEvent(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,n=>{typeListInsertGenerics(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):transact(this.doc,t=>{typeListPushGenerics(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,n=>{typeListDelete(n,this,e,t)})}get(e){return typeListGet(this,e)}toArray(){return typeListToArray(this)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}toJSON(){return this.map(e=>e instanceof AbstractType?e.toJSON():e)}map(e){return typeListMap(this,e)}forEach(e){typeListForEach(this,e)}[Symbol.iterator](){return typeListCreateIterator(this)}_write(e){e.writeTypeRef(YArrayRefID)}};const readYArray=e=>new YArray;var YMapEvent=class extends YEvent{constructor(e,t,n){super(e,t),this.keysChanged=n}},YMap=class e extends AbstractType{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof AbstractType?e.clone():e)}),t}_callObserver(e,t){callTypeObservers(this,e,new YMapEvent(this,e,t))}toJSON(){this.doc??warnPrematureAccess();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof AbstractType?r.toJSON():r}}),e}get size(){return[...createMapIterator(this)].length}keys(){return iteratorMap(createMapIterator(this),e=>e[0])}values(){return iteratorMap(createMapIterator(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return iteratorMap(createMapIterator(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??warnPrematureAccess(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):transact(this.doc,n=>{typeMapSet(n,this,e,t)}),t}get(e){return typeMapGet(this,e)}has(e){return typeMapHas(this,e)}clear(){this.doc===null?this._prelimContent.clear():transact(this.doc,e=>{this.forEach(function(t,n,r){typeMapDelete(e,r,n)})})}_write(e){e.writeTypeRef(YMapRefID)}};const readYMap=e=>new YMap,equalAttrs$1=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&equalFlat(e,t);var ItemTextListPosition=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&unexpectedCase(),this.right.content.constructor){case ContentFormat:this.right.deleted||updateCurrentAttributes(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const findNextPosition=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ContentFormat:t.right.deleted||updateCurrentAttributes(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},findPosition=(e,t,n,r)=>{let i=new Map,a=r?findMarker(t,n):null;return a?findNextPosition(e,new ItemTextListPosition(a.p.left,a.p,a.index,i),n-a.index):findNextPosition(e,new ItemTextListPosition(null,t._start,0,i),n)},insertNegatedAttributes=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ContentFormat&&equalAttrs$1(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Item(createID(a,getState(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new ContentFormat(o,r));l.integrate(e,0),n.right=l,n.forward()})},updateCurrentAttributes=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},minimizeAttributeChanges=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ContentFormat&&equalAttrs$1(t[e.right.content.key]??null,e.right.content.value));)e.forward()},insertAttributes=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!equalAttrs$1(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Item(createID(a,getState(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new ContentFormat(s,c)),n.right.integrate(e,0),n.forward()}}return o},insertText=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;minimizeAttributeChanges(n,i);let s=insertAttributes(e,t,n,i),c=r.constructor===String?new ContentString(r):r instanceof AbstractType?new ContentType(r):new ContentEmbed(r),{left:l,right:u,index:d}=n;t._searchMarker&&updateMarkerChanges(t._searchMarker,n.index,c.getLength()),u=new Item(createID(o,getState(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),insertNegatedAttributes(e,t,n,s)},formatText=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;minimizeAttributeChanges(n,i);let s=insertAttributes(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===ContentFormat));){if(!n.right.deleted)switch(n.right.content.constructor){case ContentFormat:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(equalAttrs$1(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&getItemCleanStart(e,createID(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
9
+ `)}),r(a,o,n),o},{parse:`lines`,close(e,t){n.on(`close`,()=>{t(e)})}})}t.exports=_,t.exports.build=_,t.exports.PinoPretty=_,t.exports.prettyFactory=g,t.exports.colorizerFactory=o,t.exports.isColorSupported=n,t.exports.default=_}));init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1);function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let n;return n=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/;function validateAgentId(e){return typeof e!=`string`||e.length===0||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}const counters={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0};function incrementReconcile(){counters.reconcileCount++}function incrementConflict(){counters.conflictCount++}function incrementBatch(){counters.batchCount++}function incrementUpstreamImport(){counters.upstreamImportCount++}function incrementRescueBuffer(){counters.rescueBufferCount++}function incrementBranchSwitch(){counters.branchSwitchCount++}function incrementPark(){counters.parkCount++}function incrementGitAutoSaveFailure(){counters.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters.serverObserverFiresA++:counters.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters.serverObserverErrorsA++:counters.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters.agentWriteCalls++}function incrementSummariesProvided(){counters.summariesProvided++}function incrementSummariesTruncated(){counters.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters.bridgeMergeCheckpointCreated++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters.collabSocketEpipeCount++:counters.collabSocketEconnresetCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters.cc1LastSeq[e]=t}function getMetrics(){return{...counters,cc1LastSeq:{...counters.cc1LastSeq}}}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const create$8=()=>new Map,copy=e=>{let t=create$8();return e.forEach((e,n)=>{t.set(n,e)}),t},setIfUndefined$1=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},any=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},create$7=()=>new Set,last=e=>e[e.length-1],appendTo=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},from$1=Array.from,some=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},isArray$1=Array.isArray;var ObservableV2=class{constructor(){this._observers=create$8()}on(e,t){return setIfUndefined$1(this._observers,e,create$7).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return from$1((this._observers.get(e)||create$8()).values()).forEach(e=>e(...t))}destroy(){this._observers=create$8()}};const floor$2=Math.floor,abs=Math.abs,min$2=(e,t)=>e<t?e:t,max$2=(e,t)=>e>t?e:t,isNaN$2=Number.isNaN,isNegativeZero=e=>e===0?1/e<0:e<0,BIT1=1,BIT2=2,BIT3=4,BIT4=8,BIT6=32,BIT7=64,BIT8$2=128,BIT18$2=1<<17,BIT19$2=1<<18,BIT20$2=1<<19,BIT21$2=1<<20,BIT22$2=1<<21,BIT23$2=1<<22,BIT24$2=1<<23,BIT25$2=1<<24,BIT26$2=1<<25,BIT27$2=1<<26,BIT28$2=1<<27,BIT29$2=1<<28,BIT30$2=1<<29,BIT31$2=1<<30,BITS5=31,BITS6=63,BITS7$2=127,BITS17=BIT18$2-1,BITS18=BIT19$2-1,BITS19=BIT20$2-1,BITS20=BIT21$2-1,BITS21=BIT22$2-1,BITS22=BIT23$2-1,BITS23=BIT24$2-1,BITS24=BIT25$2-1,BITS25=BIT26$2-1,BITS26=BIT27$2-1,BITS27=BIT28$2-1,BITS28=BIT29$2-1,BITS29=BIT30$2-1,BITS30=BIT31$2-1,BITS31=2147483647,BITS32=4294967295,MAX_SAFE_INTEGER$2=2**53-1,MIN_SAFE_INTEGER=-(2**53-1),HIGHEST_INT32=BITS31,HIGHEST_UINT32=BITS32,isInteger=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&floor$2(e)===e),isNaN$1=Number.isNaN,parseInt$1=Number.parseInt,fromCharCode$2=String.fromCharCode,fromCodePoint=String.fromCodePoint,MAX_UTF16_CHARACTER=fromCharCode$2(65535),toLowerCase=e=>e.toLowerCase(),trimLeftRegex=/^\s*/g,trimLeft=e=>e.replace(trimLeftRegex,``),fromCamelCaseRegex=/([A-Z])/g,fromCamelCase=(e,t)=>trimLeft(e.replace(fromCamelCaseRegex,e=>`${t}${toLowerCase(e)}`)),_encodeUtf8Polyfill$2=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder$2=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$2=e=>utf8TextEncoder$2.encode(e),encodeUtf8$2=utf8TextEncoder$2?_encodeUtf8Native$2:_encodeUtf8Polyfill$2;let utf8TextDecoder$2=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$2&&utf8TextDecoder$2.decode(new Uint8Array).length===1&&(utf8TextDecoder$2=null);var Encoder$1=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder$1=()=>new Encoder$1,encode=e=>{let t=createEncoder$1();return e(t),toUint8Array$1(t)},length$1=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},toUint8Array$1=e=>{let t=new Uint8Array(length$1(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},verifyLen=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(max$2(n,t)*2),e.cpos=0)},write$2=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeUint8=write$2,writeVarUint$2=(e,t)=>{for(;t>127;)write$2(e,128|127&t),t=floor$2(t/128);write$2(e,127&t)},writeVarInt=(e,t)=>{let n=isNegativeZero(t);for(n&&(t=-t),write$2(e,(t>63?128:0)|(n?64:0)|63&t),t=floor$2(t/64);t>0;)write$2(e,(t>127?128:0)|127&t),t=floor$2(t/128)},_strBuffer$2=new Uint8Array(3e4),_maxStrBSize$2=_strBuffer$2.length/3,_writeVarStringNative$2=(e,t)=>{if(t.length<_maxStrBSize$2){let n=utf8TextEncoder$2.encodeInto(t,_strBuffer$2).written||0;writeVarUint$2(e,n);for(let t=0;t<n;t++)write$2(e,_strBuffer$2[t])}else writeVarUint8Array$2(e,encodeUtf8$2(t))},_writeVarStringPolyfill$2=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint$2(e,r);for(let t=0;t<r;t++)write$2(e,n.codePointAt(t))},writeVarString$2=utf8TextEncoder$2&&utf8TextEncoder$2.encodeInto?_writeVarStringNative$2:_writeVarStringPolyfill$2,writeUint8Array$2=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min$2(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$2(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array$2=(e,t)=>{writeVarUint$2(e,t.byteLength),writeUint8Array$2(e,t)},writeOnDataView=(e,t)=>{verifyLen(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},writeFloat32=(e,t)=>writeOnDataView(e,4).setFloat32(0,t,!1),writeFloat64=(e,t)=>writeOnDataView(e,8).setFloat64(0,t,!1),writeBigInt64=(e,t)=>writeOnDataView(e,8).setBigInt64(0,t,!1),floatTestBed=new DataView(new ArrayBuffer(4)),isFloat32=e=>(floatTestBed.setFloat32(0,e),floatTestBed.getFloat32(0)===e),writeAny=(e,t)=>{switch(typeof t){case`string`:write$2(e,119),writeVarString$2(e,t);break;case`number`:isInteger(t)&&abs(t)<=2147483647?(write$2(e,125),writeVarInt(e,t)):isFloat32(t)?(write$2(e,124),writeFloat32(e,t)):(write$2(e,123),writeFloat64(e,t));break;case`bigint`:write$2(e,122),writeBigInt64(e,t);break;case`object`:if(t===null)write$2(e,126);else if(isArray$1(t)){write$2(e,117),writeVarUint$2(e,t.length);for(let n=0;n<t.length;n++)writeAny(e,t[n])}else if(t instanceof Uint8Array)write$2(e,116),writeVarUint8Array$2(e,t);else{write$2(e,118);let n=Object.keys(t);writeVarUint$2(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];writeVarString$2(e,i),writeAny(e,t[i])}}break;case`boolean`:write$2(e,t?120:121);break;default:write$2(e,127)}};var RleEncoder=class extends Encoder$1{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&writeVarUint$2(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const flushUintOptRleEncoder=e=>{e.count>0&&(writeVarInt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&writeVarUint$2(e.encoder,e.count-2))};var UintOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0}write(e){this.s===e?this.count++:(flushUintOptRleEncoder(this),this.count=1,this.s=e)}toUint8Array(){return flushUintOptRleEncoder(this),toUint8Array$1(this.encoder)}};const flushIntDiffOptRleEncoder=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);writeVarInt(e.encoder,t),e.count>1&&writeVarUint$2(e.encoder,e.count-2)}};var IntDiffOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(flushIntDiffOptRleEncoder(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return flushIntDiffOptRleEncoder(this),toUint8Array$1(this.encoder)}},StringEncoder=class{constructor(){this.sarr=[],this.s=``,this.lensE=new UintOptRleEncoder}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Encoder$1;return this.sarr.push(this.s),this.s=``,writeVarString$2(e,this.sarr.join(``)),writeUint8Array$2(e,this.lensE.toUint8Array()),toUint8Array$1(e)}};const create$6=e=>Error(e),methodUnimplemented=()=>{throw create$6(`Method unimplemented`)},unexpectedCase=()=>{throw create$6(`Unexpected case`)},errorUnexpectedEndOfArray$2=create$6(`Unexpected end of array`),errorIntegerOutOfRange$2=create$6(`Integer out of Range`);var Decoder$1=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder$1=e=>new Decoder$1(e),hasContent$1=e=>e.pos!==e.arr.length,readUint8Array$1=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},readVarUint8Array$1=e=>readUint8Array$1(e,readVarUint$1(e)),readUint8$1=e=>e.arr[e.pos++],readVarUint$1=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},readVarInt=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},_readVarStringPolyfill$1=e=>{let t=readVarUint$1(e);if(t===0)return``;{let n=String.fromCodePoint(readUint8$1(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(readUint8$1(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_readVarStringNative$1=e=>utf8TextDecoder$2.decode(readVarUint8Array$1(e)),readVarString$1=utf8TextDecoder$2?_readVarStringNative$1:_readVarStringPolyfill$1,readFromDataView=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},readFloat32=e=>readFromDataView(e,4).getFloat32(0,!1),readFloat64=e=>readFromDataView(e,8).getFloat64(0,!1),readBigInt64=e=>readFromDataView(e,8).getBigInt64(0,!1),readAnyLookupTable=[e=>void 0,e=>null,readVarInt,readFloat32,readFloat64,readBigInt64,e=>!1,e=>!0,readVarString$1,e=>{let t=readVarUint$1(e),n={};for(let r=0;r<t;r++){let t=readVarString$1(e);n[t]=readAny(e)}return n},e=>{let t=readVarUint$1(e),n=[];for(let r=0;r<t;r++)n.push(readAny(e));return n},readVarUint8Array$1],readAny=e=>readAnyLookupTable[127-readUint8$1(e)](e);var RleDecoder=class extends Decoder$1{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hasContent$1(this)?this.count=readVarUint$1(this)+1:this.count=-1),this.count--,this.s}},UintOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=readVarInt(this);let e=isNegativeZero(this.s);this.count=1,e&&(this.s=-this.s,this.count=readVarUint$1(this)+2)}return this.count--,this.s}},IntDiffOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=readVarInt(this),t=e&1;this.diff=floor$2(e/2),this.count=1,t&&(this.count=readVarUint$1(this)+2)}return this.s+=this.diff,this.count--,this.s}},StringDecoder=class{constructor(e){this.decoder=new UintOptRleDecoder(e),this.str=readVarString$1(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};const subtle=webcrypto.subtle,getRandomValues=webcrypto.getRandomValues.bind(webcrypto),uint32=()=>getRandomValues(new Uint32Array(1))[0],uuidv4Template=`10000000-1000-4000-8000-100000000000`,uuidv4=()=>uuidv4Template.replace(/[018]/g,e=>(e^uint32()&15>>e/4).toString(16)),getUnixTime$1=Date.now,create$5=e=>new Promise(e),all=Promise.all.bind(Promise),undefinedToNull=e=>e===void 0?null:e;var VarStoragePolyfill=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};let _localStorage=new VarStoragePolyfill,usePolyfill=!0;try{typeof localStorage<`u`&&localStorage&&(_localStorage=localStorage)}catch{}const varStorage=_localStorage,EqualityTraitSymbol$1=Symbol(`Equality`),equals=(e,t)=>e===t||!!e?.[EqualityTraitSymbol$1]?.(t)||!1,assign=Object.assign,keys$1=Object.keys,forEach=(e,t)=>{for(let n in e)t(e[n],n)},size$1=e=>keys$1(e).length,isEmpty=e=>{for(let t in e)return!1;return!0},every=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},hasProperty$1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalFlat=(e,t)=>e===t||size$1(e)===size$1(t)&&every(e,(e,n)=>(e!==void 0||hasProperty$1(t,n))&&equals(t[n],e)),freeze=Object.freeze,deepFreeze=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&deepFreeze(e[t])}return freeze(e)},callAll=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&callAll(e,t,n+1)}},id=e=>e,isOneOf=(e,t)=>t.includes(e),isArray=isArray$1,isNode=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,isBrowser=typeof window<`u`&&typeof document<`u`&&!isNode,isMac=typeof navigator<`u`?/Mac/.test(navigator.platform):!1;let params;const args=[],computeParams=()=>{if(params===void 0)if(isNode){params=create$8();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&params.set(t,``),t=r):t===null?args.push(r):(params.set(t,r),t=null)}t!==null&&params.set(t,``)}else typeof location==`object`?(params=create$8(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);params.set(`--${fromCamelCase(t,`-`)}`,n),params.set(`-${fromCamelCase(t,`-`)}`,n)}})):params=create$8();return params},hasParam=e=>computeParams().has(e),getVariable=e=>undefinedToNull(isNode?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:varStorage.getItem(e)),hasConf=e=>hasParam(`--`+e)||getVariable(e)!==null,production=hasConf(`production`),forceColor=isNode&&isOneOf(process.env.FORCE_COLOR,[`true`,`1`,`2`]),supportsColor=forceColor||!hasParam(`--no-colors`)&&!hasConf(`no-color`)&&(!isNode||process.stdout.isTTY)&&(!isNode||hasParam(`--color`)||getVariable(`COLORTERM`)!==null||(getVariable(`TERM`)||``).includes(`color`)),createUint8ArrayFromLen=e=>new Uint8Array(e),createUint8ArrayViewFromArrayBuffer=(e,t,n)=>new Uint8Array(e,t,n),toBase64Browser=e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=fromCharCode$2(e[n]);return btoa(t)},toBase64Node=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),fromBase64Browser=e=>{let t=atob(e),n=createUint8ArrayFromLen(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},fromBase64Node=e=>{let t=Buffer.from(e,`base64`);return createUint8ArrayViewFromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)},toBase64=isBrowser?toBase64Browser:toBase64Node,fromBase64=isBrowser?fromBase64Browser:fromBase64Node,copyUint8Array=e=>{let t=createUint8ArrayFromLen(e.byteLength);return t.set(e),t},encodeAny=e=>encode(t=>writeAny(t,e)),create$4=Symbol,BOLD=create$4(),UNBOLD=create$4(),BLUE=create$4(),GREY=create$4(),GREEN=create$4(),RED=create$4(),PURPLE=create$4(),ORANGE=create$4(),UNCOLOR=create$4(),computeNoColorLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};let lastLoggingTime=getUnixTime$1();const _nodeStyleMap={[BOLD]:`\x1B[1m`,[UNBOLD]:`\x1B[2m`,[BLUE]:`\x1B[34m`,[GREEN]:`\x1B[32m`,[GREY]:`\x1B[37m`,[RED]:`\x1B[31m`,[PURPLE]:`\x1B[35m`,[ORANGE]:`\x1B[38;5;208m`,[UNCOLOR]:`\x1B[0m`},computeNodeLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r],i=_nodeStyleMap[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n},computeLoggingArgs=supportsColor?computeNodeLoggingArgs:computeNoColorLoggingArgs,print=(...e)=>{console.log(...computeLoggingArgs(e))},warn=(...e)=>{console.warn(...computeLoggingArgs(e))},createIterator=e=>({[Symbol.iterator](){return this},next:e}),iteratorFilter=(e,t)=>createIterator(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),iteratorMap=(e,t)=>createIterator(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var DeleteItem=class{constructor(e,t){this.clock=e,this.len=t}},DeleteSet=class{constructor(){this.clients=new Map}};const iterateDeletedStructs=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])iterateStructs(e,i,o.clock,o.len,n)}}),findIndexDS=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=floor$2((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},isDeleted=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&findIndexDS(n,t.clock)!==null},sortAndMergeDeleteSet=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new DeleteItem(r.clock,max$2(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},mergeDeleteSets=e=>{let t=new DeleteSet;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)appendTo(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return sortAndMergeDeleteSet(t),t},addToDeleteSet=(e,t,n,r)=>{setIfUndefined$1(e.clients,t,()=>[]).push(new DeleteItem(n,r))},createDeleteSet=()=>new DeleteSet,createDeleteSetFromStructStore=e=>{let t=createDeleteSet();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new DeleteItem(i,a))}}r.length>0&&t.clients.set(n,r)}),t},writeDeleteSet=(e,t)=>{writeVarUint$2(e.restEncoder,t.clients.size),from$1(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),writeVarUint$2(e.restEncoder,t);let r=n.length;writeVarUint$2(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},readDeleteSet=e=>{let t=new DeleteSet,n=readVarUint$1(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=readVarUint$1(e.restDecoder),r=readVarUint$1(e.restDecoder);if(r>0){let i=setIfUndefined$1(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new DeleteItem(e.readDsClock(),e.readDsLen()))}}return t},readAndApplyDeleteSet=(e,t,n)=>{let r=new DeleteSet,i=readVarUint$1(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=readVarUint$1(e.restDecoder),a=readVarUint$1(e.restDecoder),o=n.clients.get(i)||[],s=getState(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&addToDeleteSet(r,i,s,a-s);let e=findIndexSS(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,splitItem(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,splitItem(t,c,a-c.id.clock)),c.delete(t))}else addToDeleteSet(r,i,n,a-n)}}if(r.clients.size>0){let e=new UpdateEncoderV2;return writeVarUint$2(e.restEncoder,0),writeDeleteSet(e,r),e.toUint8Array()}return null},equalDeleteSets=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},generateNewClientId=uint32;var Doc=class e extends ObservableV2{constructor({guid:e=uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=generateNewClientId(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new StructStore,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=create$5(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>create$5(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&transact(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(from$1(this.subdocs).map(e=>e.guid))}transact(e,t=null){return transact(this,e,t)}get(e,t=AbstractType){let n=setIfUndefined$1(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==AbstractType&&r!==t)if(r===AbstractType){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,YArray)}getText(e=``){return this.get(e,YText)}getMap(e=``){return this.get(e,YMap)}getXmlElement(e=``){return this.get(e,YXmlElement)}getXmlFragment(e=``){return this.get(e,YXmlFragment)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,from$1(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,transact(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},DSDecoderV1=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return readVarUint$1(this.restDecoder)}readDsLen(){return readVarUint$1(this.restDecoder)}},UpdateDecoderV1=class extends DSDecoderV1{readLeftID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readRightID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readClient(){return readVarUint$1(this.restDecoder)}readInfo(){return readUint8$1(this.restDecoder)}readString(){return readVarString$1(this.restDecoder)}readParentInfo(){return readVarUint$1(this.restDecoder)===1}readTypeRef(){return readVarUint$1(this.restDecoder)}readLen(){return readVarUint$1(this.restDecoder)}readAny(){return readAny(this.restDecoder)}readBuf(){return copyUint8Array(readVarUint8Array$1(this.restDecoder))}readJSON(){return JSON.parse(readVarString$1(this.restDecoder))}readKey(){return readVarString$1(this.restDecoder)}},DSDecoderV2=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=readVarUint$1(this.restDecoder),this.dsCurrVal}readDsLen(){let e=readVarUint$1(this.restDecoder)+1;return this.dsCurrVal+=e,e}},UpdateDecoderV2=class extends DSDecoderV2{constructor(e){super(e),this.keys=[],readVarUint$1(e),this.keyClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.clientDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.leftClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.rightClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.infoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.stringDecoder=new StringDecoder(readVarUint8Array$1(e)),this.parentInfoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.typeRefDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.lenDecoder=new UintOptRleDecoder(readVarUint8Array$1(e))}readLeftID(){return new ID(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ID(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return readAny(this.restDecoder)}readBuf(){return readVarUint8Array$1(this.restDecoder)}readJSON(){return readAny(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},DSEncoderV1=class{constructor(){this.restEncoder=createEncoder$1()}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){writeVarUint$2(this.restEncoder,e)}writeDsLen(e){writeVarUint$2(this.restEncoder,e)}},UpdateEncoderV1=class extends DSEncoderV1{writeLeftID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeRightID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeClient(e){writeVarUint$2(this.restEncoder,e)}writeInfo(e){writeUint8(this.restEncoder,e)}writeString(e){writeVarString$2(this.restEncoder,e)}writeParentInfo(e){writeVarUint$2(this.restEncoder,e?1:0)}writeTypeRef(e){writeVarUint$2(this.restEncoder,e)}writeLen(e){writeVarUint$2(this.restEncoder,e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeVarString$2(this.restEncoder,JSON.stringify(e))}writeKey(e){writeVarString$2(this.restEncoder,e)}},DSEncoderV2=class{constructor(){this.restEncoder=createEncoder$1(),this.dsCurrVal=0}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,writeVarUint$2(this.restEncoder,t)}writeDsLen(e){e===0&&unexpectedCase(),writeVarUint$2(this.restEncoder,e-1),this.dsCurrVal+=e}},UpdateEncoderV2=class extends DSEncoderV2{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new IntDiffOptRleEncoder,this.clientEncoder=new UintOptRleEncoder,this.leftClockEncoder=new IntDiffOptRleEncoder,this.rightClockEncoder=new IntDiffOptRleEncoder,this.infoEncoder=new RleEncoder(writeUint8),this.stringEncoder=new StringEncoder,this.parentInfoEncoder=new RleEncoder(writeUint8),this.typeRefEncoder=new UintOptRleEncoder,this.lenEncoder=new UintOptRleEncoder}toUint8Array(){let e=createEncoder$1();return writeVarUint$2(e,0),writeVarUint8Array$2(e,this.keyClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.clientEncoder.toUint8Array()),writeVarUint8Array$2(e,this.leftClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.rightClockEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.infoEncoder)),writeVarUint8Array$2(e,this.stringEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.parentInfoEncoder)),writeVarUint8Array$2(e,this.typeRefEncoder.toUint8Array()),writeVarUint8Array$2(e,this.lenEncoder.toUint8Array()),writeUint8Array$2(e,toUint8Array$1(this.restEncoder)),toUint8Array$1(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeAny(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const writeStructs=(e,t,n,r)=>{r=max$2(r,t[0].id.clock);let i=findIndexSS(t,r);writeVarUint$2(e.restEncoder,t.length-i),e.writeClient(n),writeVarUint$2(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},writeClientsStructs=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{getState(t,n)>e&&r.set(n,e)}),getStateVector(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),writeVarUint$2(e.restEncoder,r.size),from$1(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{writeStructs(e,t.clients.get(n),n,r)})},readClientsStructRefs=(e,t)=>{let n=create$8(),r=readVarUint$1(e.restDecoder);for(let i=0;i<r;i++){let r=readVarUint$1(e.restDecoder),i=Array(r),a=e.readClient(),o=readVarUint$1(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new GC(createID(a,o),t),o+=t;break}case 10:{let t=readVarUint$1(e.restDecoder);i[n]=new Skip(createID(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new Item(createID(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,readItemContent(e,r));i[n]=c,o+=c.length}}}}return n},integrateStructs=(e,t,n)=>{let r=[],i=from$1(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new StructStore,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Skip){let i=setIfUndefined$1(d,u.id.client,()=>getState(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,getState(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new UpdateEncoderV2;return writeClientsStructs(e,s,new Map),writeVarUint$2(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},writeStructsFromTransaction=(e,t)=>writeClientsStructs(e,t.doc.store,t.beforeState),readUpdateV2=(e,t,n,r=new UpdateDecoderV2(e))=>transact(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=integrateStructs(e,i,readClientsStructRefs(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<getState(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=mergeUpdatesV2([o.update,a.update])}}else i.pendingStructs=a;let s=readAndApplyDeleteSet(r,e,i);if(i.pendingDs){let t=new UpdateDecoderV2(createDecoder$1(i.pendingDs));readVarUint$1(t.restDecoder);let n=readAndApplyDeleteSet(t,e,i);s&&n?i.pendingDs=mergeUpdatesV2([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,applyUpdateV2(e.doc,t)}},n,!1),applyUpdateV2=(e,t,n,r=UpdateDecoderV2)=>{let i=createDecoder$1(t);readUpdateV2(i,e,n,new r(i))},applyUpdate=(e,t,n)=>applyUpdateV2(e,t,n,UpdateDecoderV1),writeStateAsUpdate=(e,t,n=new Map)=>{writeClientsStructs(e,t.store,n),writeDeleteSet(e,createDeleteSetFromStructStore(t.store))},encodeStateAsUpdateV2=(e,t=new Uint8Array([0]),n=new UpdateEncoderV2)=>{writeStateAsUpdate(n,e,decodeStateVector(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(diffUpdateV2(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===UpdateEncoderV1)return mergeUpdates(r.map((e,t)=>t===0?e:convertUpdateFormatV2ToV1(e)));if(n.constructor===UpdateEncoderV2)return mergeUpdatesV2(r)}return r[0]},encodeStateAsUpdate=(e,t)=>encodeStateAsUpdateV2(e,t,new UpdateEncoderV1),readStateVector=e=>{let t=new Map,n=readVarUint$1(e.restDecoder);for(let r=0;r<n;r++){let n=readVarUint$1(e.restDecoder),r=readVarUint$1(e.restDecoder);t.set(n,r)}return t},decodeStateVector=e=>readStateVector(new DSDecoderV1(createDecoder$1(e))),writeStateVector=(e,t)=>(writeVarUint$2(e.restEncoder,t.size),from$1(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{writeVarUint$2(e.restEncoder,t),writeVarUint$2(e.restEncoder,n)}),e),writeDocumentStateVector=(e,t)=>writeStateVector(e,getStateVector(t.store)),encodeStateVectorV2=(e,t=new DSEncoderV2)=>(e instanceof Map?writeStateVector(t,e):writeDocumentStateVector(t,e),t.toUint8Array()),encodeStateVector=e=>encodeStateVectorV2(e,new DSEncoderV1);var EventHandler=class{constructor(){this.l=[]}};const createEventHandler=()=>new EventHandler,addEventHandlerListener=(e,t)=>e.l.push(t),removeEventHandlerListener=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},callEventHandlerListeners=(e,t,n)=>callAll(e.l,[t,n]);var ID=class{constructor(e,t){this.client=e,this.clock=t}};const compareIDs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,createID=(e,t)=>new ID(e,t),findRootTypeKey=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw unexpectedCase()},isParentOf=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Snapshot=class{constructor(e,t){this.ds=e,this.sv=t}};const createSnapshot=(e,t)=>new Snapshot(e,t),emptySnapshot=createSnapshot(createDeleteSet(),new Map),snapshot=e=>createSnapshot(createDeleteSetFromStructStore(e.store),getStateVector(e.store)),isVisible$1=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!isDeleted(t.ds,e.id),splitSnapshotAffectedStructs=(e,t)=>{let n=setIfUndefined$1(e.meta,splitSnapshotAffectedStructs,create$7),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<getState(r,n)&&getItemCleanStart(e,createID(n,t))}),iterateDeletedStructs(e,t.ds,e=>{}),n.add(t))},snapshotContainsUpdateV2=(e,t,n=UpdateDecoderV2)=>{let r=new n(createDecoder$1(t)),i=new LazyStructReader(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=mergeDeleteSets([e.ds,readDeleteSet(r)]);return equalDeleteSets(e.ds,a)},snapshotContainsUpdate=(e,t)=>snapshotContainsUpdateV2(e,t,UpdateDecoderV1);var StructStore=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const getStateVector=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},getState=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},addStruct=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw unexpectedCase()}n.push(t)},findIndexSS=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=floor$2(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=floor$2((n+r)/2)}throw unexpectedCase()},find=(e,t)=>{let n=e.clients.get(t.client);return n[findIndexSS(n,t.clock)]},getItem=find,findIndexCleanStart=(e,t,n)=>{let r=findIndexSS(t,n),i=t[r];return i.id.clock<n&&i instanceof Item?(t.splice(r+1,0,splitItem(e,i,n-i.id.clock)),r+1):r},getItemCleanStart=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[findIndexCleanStart(e,n,t.clock)]},getItemCleanEnd=(e,t,n)=>{let r=t.clients.get(n.client),i=findIndexSS(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==GC&&r.splice(i+1,0,splitItem(e,a,n.clock-a.id.clock+1)),a},replaceStruct=(e,t,n)=>{let r=e.clients.get(t.id.client);r[findIndexSS(r,t.id.clock)]=n},iterateStructs=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=findIndexCleanStart(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&findIndexCleanStart(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Transaction=class{constructor(e,t,n){this.doc=e,this.deleteSet=new DeleteSet,this.beforeState=getStateVector(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const writeUpdateMessageFromTransaction=(e,t)=>t.deleteSet.clients.size===0&&!any(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(sortAndMergeDeleteSet(t.deleteSet),writeStructsFromTransaction(e,t),writeDeleteSet(e,t.deleteSet),!0),addChangedTypeToTransaction=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&setIfUndefined$1(e.changed,t,create$7).add(n)},tryToMergeWithLefts=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Item&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},tryGcDeleteSet=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=findIndexSS(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Item&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},tryMergeDeleteSet=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=min$2(r.length-1,1+findIndexSS(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+tryToMergeWithLefts(r,e)}})},cleanupTransactions=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{sortAndMergeDeleteSet(a),n.afterState=getStateVector(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{callEventHandlerListeners(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&cleanupYTextAfterTransaction(n)})}),callAll(e,[])}finally{r.gc&&tryGcDeleteSet(a,i,r.gcFilter),tryMergeDeleteSet(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=max$2(findIndexSS(e,r),1);for(let t=e.length-1;t>=n;)t-=1+tryToMergeWithLefts(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=findIndexSS(r,n);a+1<r.length&&tryToMergeWithLefts(r,a+1)>1||a>0&&tryToMergeWithLefts(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(print(ORANGE,BOLD,`[yjs] `,UNBOLD,RED,`Changed the client-id because another client seems to be using it.`),r.clientID=generateNewClientId()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new UpdateEncoderV1;writeUpdateMessageFromTransaction(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new UpdateEncoderV2;writeUpdateMessageFromTransaction(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):cleanupTransactions(e,t+1)}}},transact=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Transaction(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&cleanupTransactions(i,0)}}return o};var StackItem=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const clearUndoManagerStackItem=(e,t,n)=>{iterateDeletedStructs(e,n.deletions,n=>{n instanceof Item&&t.scope.some(t=>t===e.doc||isParentOf(t,n))&&keepItem(n,!1)})},popStackItem=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;transact(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;iterateDeletedStructs(n,o.insertions,e=>{if(e instanceof Item){if(e.redone!==null){let{item:t,diff:i}=followRedone(r,e.id);i>0&&(t=getItemCleanStart(n,createID(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||isParentOf(t,e))&&c.push(e)}}),iterateDeletedStructs(n,o.deletions,e=>{e instanceof Item&&a.some(t=>t===n.doc||isParentOf(t,e))&&!isDeleted(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=redoItem(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var UndoManager=class extends ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=isArray$1(e)?e[0].doc:e instanceof Doc?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new DeleteSet;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&addToDeleteSet(i,n,r,a)});let a=getUnixTime$1(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=mergeDeleteSets([t.deletions,e.deleteSet]),t.insertions=mergeDeleteSets([t.insertions,i])}else r.push(new StackItem(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),iterateDeletedStructs(e,e.deleteSet,t=>{t instanceof Item&&this.scope.some(n=>n===e.doc||isParentOf(n,t))&&keepItem(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=isArray$1(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof AbstractType?e.doc!==this.doc:e!==this.doc)&&warn(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>clearUndoManagerStackItem(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>clearUndoManagerStackItem(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=popStackItem(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=popStackItem(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*lazyStructReaderGenerator(e){let t=readVarUint$1(e.restDecoder);for(let n=0;n<t;n++){let t=readVarUint$1(e.restDecoder),n=e.readClient(),r=readVarUint$1(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=readVarUint$1(e.restDecoder);yield new Skip(createID(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new Item(createID(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,readItemContent(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new GC(createID(n,r),t),r+=t}}}}var LazyStructReader=class{constructor(e,t){this.gen=lazyStructReaderGenerator(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Skip);return this.curr}},LazyStructWriter=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const mergeUpdates=e=>mergeUpdatesV2(e,UpdateDecoderV1,UpdateEncoderV1),sliceStruct=(e,t)=>{if(e.constructor===GC){let{client:n,clock:r}=e.id;return new GC(createID(n,r+t),e.length-t)}else if(e.constructor===Skip){let{client:n,clock:r}=e.id;return new Skip(createID(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new Item(createID(r,i+t),null,createID(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},mergeUpdatesV2=(e,t=UpdateDecoderV2,n=UpdateEncoderV2)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(createDecoder$1(e))),i=r.map(e=>new LazyStructReader(e,!0)),a=null,o=new n,s=new LazyStructWriter(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Skip?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===Skip)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{writeStructToLazyStructWriter(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Skip(createID(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Skip?a.struct.length-=t:n=sliceStruct(n,t)),a.struct.mergeWith(n)||(writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Skip;n=e.next())writeStructToLazyStructWriter(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(writeStructToLazyStructWriter(s,a.struct,a.offset),a=null),finishLazyStructWriting(s),writeDeleteSet(o,mergeDeleteSets(r.map(e=>readDeleteSet(e)))),o.toUint8Array()},diffUpdateV2=(e,t,n=UpdateDecoderV2,r=UpdateEncoderV2)=>{let i=decodeStateVector(t),a=new r,o=new LazyStructWriter(a),s=new n(createDecoder$1(e)),c=new LazyStructReader(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Skip){c.next();continue}if(e.id.clock+e.length>n)for(writeStructToLazyStructWriter(o,e,max$2(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)writeStructToLazyStructWriter(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return finishLazyStructWriting(o),writeDeleteSet(a,readDeleteSet(s)),a.toUint8Array()},flushLazyStructWriter=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:toUint8Array$1(e.encoder.restEncoder)}),e.encoder.restEncoder=createEncoder$1(),e.written=0)},writeStructToLazyStructWriter=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&flushLazyStructWriter(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),writeVarUint$2(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},finishLazyStructWriting=e=>{flushLazyStructWriter(e);let t=e.encoder.restEncoder;writeVarUint$2(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];writeVarUint$2(t,r.written),writeUint8Array$2(t,r.restEncoder)}},convertUpdateFormat=(e,t,n,r)=>{let i=new n(createDecoder$1(e)),a=new LazyStructReader(i,!1),o=new r,s=new LazyStructWriter(o);for(let e=a.curr;e!==null;e=a.next())writeStructToLazyStructWriter(s,t(e),0);return finishLazyStructWriting(s),writeDeleteSet(o,readDeleteSet(i)),o.toUint8Array()},convertUpdateFormatV2ToV1=e=>convertUpdateFormat(e,id,UpdateDecoderV2,UpdateEncoderV1),errorComputeChanges=`You must not compute changes after the event-handler fired.`;var YEvent=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=getPathTo(this.currentTarget,this.target)}deletes(e){return isDeleted(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=last(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=last(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=last(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let t=this.target,n=create$7(),r=create$7(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const getPathTo=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},warnPrematureAccess=()=>{warn(`Invalid access: Add Yjs type to a document before reading data.`)},maxSearchMarker=80;let globalSearchMarkerTimestamp=0;var ArraySearchMarker=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=globalSearchMarkerTimestamp++}};const refreshMarkerTimestamp=e=>{e.timestamp=globalSearchMarkerTimestamp++},overwriteMarker=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=globalSearchMarkerTimestamp++},markPosition=(e,t,n)=>{if(e.length>=maxSearchMarker){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return overwriteMarker(r,t,n),r}else{let r=new ArraySearchMarker(t,n);return e.push(r),r}},findMarker=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>abs(t-e.index)<abs(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,refreshMarkerTimestamp(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&abs(n.index-i)<r.parent.length/maxSearchMarker?(overwriteMarker(n,r,i),n):markPosition(e._searchMarker,r,i)},updateMarkerChanges=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=max$2(t,i.index+n))}},callTypeObservers=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;setIfUndefined$1(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;callEventHandlerListeners(r._eH,n,t)};var AbstractType=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=createEventHandler(),this._dEH=createEventHandler(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw methodUnimplemented()}clone(){throw methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){addEventHandlerListener(this._eH,e)}observeDeep(e){addEventHandlerListener(this._dEH,e)}unobserve(e){removeEventHandlerListener(this._eH,e)}unobserveDeep(e){removeEventHandlerListener(this._dEH,e)}toJSON(){}};const typeListSlice=(e,t,n)=>{e.doc??warnPrematureAccess(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},typeListToArray=e=>{e.doc??warnPrematureAccess();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},typeListToArraySnapshot=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&isVisible$1(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},typeListForEach=(e,t)=>{let n=0,r=e._start;for(e.doc??warnPrematureAccess();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},typeListMap=(e,t)=>{let n=[];return typeListForEach(e,(r,i)=>{n.push(t(r,i,e))}),n},typeListCreateIterator=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},typeListGet=(e,t)=>{e.doc??warnPrematureAccess();let n=findMarker(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},typeListInsertGenericsAfter=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentAny(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentBinary(new Uint8Array(n))),i.integrate(e,0);break;case Doc:i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentDoc(n)),i.integrate(e,0);break;default:if(n instanceof AbstractType)i=new Item(createID(o,getState(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ContentType(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},lengthExceeded=()=>create$6(`Length exceeded!`),typeListInsertGenerics=(e,t,n,r)=>{if(n>t._length)throw lengthExceeded();if(n===0)return t._searchMarker&&updateMarkerChanges(t._searchMarker,n,r.length),typeListInsertGenericsAfter(e,t,null,r);let i=n,a=findMarker(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&getItemCleanStart(e,createID(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&updateMarkerChanges(t._searchMarker,i,r.length),typeListInsertGenericsAfter(e,t,o,r)},typeListPushGenerics=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return typeListInsertGenericsAfter(e,t,r,n)},typeListDelete=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=findMarker(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&getItemCleanStart(e,createID(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&getItemCleanStart(e,createID(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw lengthExceeded();t._searchMarker&&updateMarkerChanges(t._searchMarker,i,-a+r)},typeMapDelete=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},typeMapSet=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new ContentAny([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new ContentAny([r]);break;case Uint8Array:s=new ContentBinary(r);break;case Doc:s=new ContentDoc(r);break;default:if(r instanceof AbstractType)s=new ContentType(r);else throw Error(`Unexpected content type`)}new Item(createID(o,getState(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},typeMapGet=(e,t)=>{e.doc??warnPrematureAccess();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},typeMapGetAll=e=>{let t={};return e.doc??warnPrematureAccess(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},typeMapHas=(e,t)=>{e.doc??warnPrematureAccess();let n=e._map.get(t);return n!==void 0&&!n.deleted},typeMapGetAllSnapshot=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&isVisible$1(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},createMapIterator=e=>(e.doc??warnPrematureAccess(),iteratorFilter(e._map.entries(),e=>!e[1].deleted));var YArrayEvent=class extends YEvent{},YArray=class e extends AbstractType{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._length}_callObserver(e,t){super._callObserver(e,t),callTypeObservers(this,e,new YArrayEvent(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,n=>{typeListInsertGenerics(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):transact(this.doc,t=>{typeListPushGenerics(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,n=>{typeListDelete(n,this,e,t)})}get(e){return typeListGet(this,e)}toArray(){return typeListToArray(this)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}toJSON(){return this.map(e=>e instanceof AbstractType?e.toJSON():e)}map(e){return typeListMap(this,e)}forEach(e){typeListForEach(this,e)}[Symbol.iterator](){return typeListCreateIterator(this)}_write(e){e.writeTypeRef(YArrayRefID)}};const readYArray=e=>new YArray;var YMapEvent=class extends YEvent{constructor(e,t,n){super(e,t),this.keysChanged=n}},YMap=class e extends AbstractType{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof AbstractType?e.clone():e)}),t}_callObserver(e,t){callTypeObservers(this,e,new YMapEvent(this,e,t))}toJSON(){this.doc??warnPrematureAccess();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof AbstractType?r.toJSON():r}}),e}get size(){return[...createMapIterator(this)].length}keys(){return iteratorMap(createMapIterator(this),e=>e[0])}values(){return iteratorMap(createMapIterator(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return iteratorMap(createMapIterator(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??warnPrematureAccess(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):transact(this.doc,n=>{typeMapSet(n,this,e,t)}),t}get(e){return typeMapGet(this,e)}has(e){return typeMapHas(this,e)}clear(){this.doc===null?this._prelimContent.clear():transact(this.doc,e=>{this.forEach(function(t,n,r){typeMapDelete(e,r,n)})})}_write(e){e.writeTypeRef(YMapRefID)}};const readYMap=e=>new YMap,equalAttrs$1=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&equalFlat(e,t);var ItemTextListPosition=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&unexpectedCase(),this.right.content.constructor){case ContentFormat:this.right.deleted||updateCurrentAttributes(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const findNextPosition=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ContentFormat:t.right.deleted||updateCurrentAttributes(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},findPosition=(e,t,n,r)=>{let i=new Map,a=r?findMarker(t,n):null;return a?findNextPosition(e,new ItemTextListPosition(a.p.left,a.p,a.index,i),n-a.index):findNextPosition(e,new ItemTextListPosition(null,t._start,0,i),n)},insertNegatedAttributes=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ContentFormat&&equalAttrs$1(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Item(createID(a,getState(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new ContentFormat(o,r));l.integrate(e,0),n.right=l,n.forward()})},updateCurrentAttributes=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},minimizeAttributeChanges=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ContentFormat&&equalAttrs$1(t[e.right.content.key]??null,e.right.content.value));)e.forward()},insertAttributes=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!equalAttrs$1(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Item(createID(a,getState(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new ContentFormat(s,c)),n.right.integrate(e,0),n.forward()}}return o},insertText=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;minimizeAttributeChanges(n,i);let s=insertAttributes(e,t,n,i),c=r.constructor===String?new ContentString(r):r instanceof AbstractType?new ContentType(r):new ContentEmbed(r),{left:l,right:u,index:d}=n;t._searchMarker&&updateMarkerChanges(t._searchMarker,n.index,c.getLength()),u=new Item(createID(o,getState(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),insertNegatedAttributes(e,t,n,s)},formatText=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;minimizeAttributeChanges(n,i);let s=insertAttributes(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===ContentFormat));){if(!n.right.deleted)switch(n.right.content.constructor){case ContentFormat:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(equalAttrs$1(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&getItemCleanStart(e,createID(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
10
10
  `;n.right=new Item(createID(o,getState(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ContentString(i)),n.right.integrate(e,0),n.forward()}insertNegatedAttributes(e,t,n,s)},cleanupFormattingGap=(e,t,n,r,i)=>{let a=t,o=create$8();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===ContentFormat){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case ContentFormat:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&updateCurrentAttributes(i,n);break}}}t=t.right}return s},cleanupContextlessFormattingGap=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ContentFormat){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},cleanupYTextFormatting=e=>{let t=0;return transact(e.doc,n=>{let r=e._start,i=e._start,a=create$8(),o=copy(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case ContentFormat:updateCurrentAttributes(o,i.content);break;default:t+=cleanupFormattingGap(n,r,i,a,o),a=copy(o),r=i;break}i=i.right}}),t},cleanupYTextAfterTransaction=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&iterateStructs(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===ContentFormat&&e.constructor!==GC&&t.add(e.parent)})}transact(n,n=>{iterateDeletedStructs(e,e.deleteSet,e=>{if(e instanceof GC||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===ContentFormat?t.add(r):cleanupContextlessFormattingGap(n,e)});for(let e of t)cleanupYTextFormatting(e)})},deleteText=(e,t,n)=>{let r=n,i=copy(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case ContentType:case ContentEmbed:case ContentString:n<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&cleanupFormattingGap(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&updateMarkerChanges(o._searchMarker,t.index,-r+n),t};var YTextEvent=class extends YEvent{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){return this._changes===null&&(this._changes={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set}),this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];transact(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},isEmpty(o)||(e.attributes=assign({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case ContentType:case ContentEmbed:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case ContentString:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case ContentFormat:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(equalAttrs$1(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),equalAttrs$1(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;equalAttrs$1(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(equalAttrs$1(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),updateCurrentAttributes(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},YText=class e extends AbstractType{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??warnPrematureAccess(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new YTextEvent(this,e,t);callTypeObservers(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??warnPrematureAccess();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===ContentString&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):transact(this.doc,n=>{let r=new ItemTextListPosition(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
11
11
  `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&insertText(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&deleteText(n,r,a.delete):formatText(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??warnPrematureAccess();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(isVisible$1(s,e)||t!==void 0&&isVisible$1(s,t))switch(s.content.constructor){case ContentString:{let r=i.get(`ychange`);e!==void 0&&!isVisible$1(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!isVisible$1(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case ContentType:case ContentEmbed:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case ContentFormat:isVisible$1(s,e)&&(c(),updateCurrentAttributes(i,s.content));break}s=s.right}c()};return e||t?transact(a,n=>{e&&splitSnapshotAffectedStructs(n,e),t&&splitSnapshotAffectedStructs(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):transact(r,r=>{let i=findPosition(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),insertText(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):transact(r,r=>{let i=findPosition(r,this,e,!n);insertText(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):transact(n,n=>{deleteText(n,findPosition(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):transact(r,r=>{let i=findPosition(r,this,e,!1);i.right!==null&&formatText(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):transact(this.doc,t=>{typeMapDelete(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):transact(this.doc,n=>{typeMapSet(n,this,e,t)})}getAttribute(e){return typeMapGet(this,e)}getAttributes(){return typeMapGetAll(this)}_write(e){e.writeTypeRef(YTextRefID)}};const readYText=e=>new YText;var YXmlTreeWalker=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??warnPrematureAccess()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===YXmlElement||t.constructor===YXmlFragment)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},YXmlFragment=class e extends AbstractType{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new YXmlTreeWalker(this,e)}querySelector(e){e=e.toUpperCase();let t=new YXmlTreeWalker(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),from$1(new YXmlTreeWalker(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){callTypeObservers(this,e,new YXmlEvent(this,t,e))}toString(){return typeListMap(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),typeListForEach(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,n=>{typeListInsertGenerics(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)transact(this.doc,n=>{let r=e&&e instanceof AbstractType?e._item:e;typeListInsertGenericsAfter(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw create$6(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,n=>{typeListDelete(n,this,e,t)})}toArray(){return typeListToArray(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return typeListGet(this,e)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}forEach(e){typeListForEach(this,e)}_write(e){e.writeTypeRef(YXmlFragmentRefID)}};const readYXmlFragment=e=>new YXmlFragment;var YXmlElement=class e extends YXmlFragment{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return forEach(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):transact(this.doc,n=>{typeMapSet(n,this,e,t)})}getAttribute(e){return typeMapGet(this,e)}hasAttribute(e){return typeMapHas(this,e)}getAttributes(e){return e?typeMapGetAllSnapshot(this,e):typeMapGetAll(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return typeListForEach(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(YXmlElementRefID),e.writeKey(this.nodeName)}};const readYXmlElement=e=>new YXmlElement(e.readKey());var YXmlEvent=class extends YEvent{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},YXmlHook=class e extends YMap{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(YXmlHookRefID),e.writeKey(this.hookName)}};const readYXmlHook=e=>new YXmlHook(e.readKey());var YXmlText=class e extends YText{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(YXmlTextRefID)}};const readYXmlText=e=>new YXmlText;var AbstractStruct=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw methodUnimplemented()}mergeWith(e){return!1}write(e,t,n){throw methodUnimplemented()}integrate(e,t){throw methodUnimplemented()}};const structGCRefNumber=0;var GC=class extends AbstractStruct{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),addStruct(e.doc.store,this)}write(e,t){e.writeInfo(structGCRefNumber),e.writeLen(this.length-t)}getMissing(e,t){return null}},ContentBinary=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const readContentBinary=e=>new ContentBinary(e.readBuf());var ContentDeleted=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){addToDeleteSet(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const readContentDeleted=e=>new ContentDeleted(e.readLen()),createDocFromOpts=(e,t)=>new Doc({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var ContentDoc=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(createDocFromOpts(this.doc.guid,this.opts))}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const readContentDoc=e=>new ContentDoc(createDocFromOpts(e.readString(),e.readAny()));var ContentEmbed=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const readContentEmbed=e=>new ContentEmbed(e.readJSON());var ContentFormat=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const readContentFormat=e=>new ContentFormat(e.readKey(),e.readJSON());var ContentJSON=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const readContentJSON=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new ContentJSON(n)},isDevMode=getVariable(`node_env`)===`development`;var ContentAny=class e{constructor(e){this.arr=e,isDevMode&&deepFreeze(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const readContentAny=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ContentAny(n)};var ContentString=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const readContentString=e=>new ContentString(e.readString()),typeRefs=[readYArray,readYMap,readYText,readYXmlElement,readYXmlFragment,readYXmlHook,readYXmlText],YArrayRefID=0,YMapRefID=1,YTextRefID=2,YXmlElementRefID=3,YXmlFragmentRefID=4,YXmlHookRefID=5,YXmlTextRefID=6;var ContentType=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const readContentType=e=>new ContentType(typeRefs[e.readTypeRef()](e)),followRedone=(e,t)=>{let n=t,r=0,i;do r>0&&(n=createID(n.client,n.clock+r)),i=getItem(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Item);return{item:i,diff:r}},keepItem=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},splitItem=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Item(createID(r,i+n),t,createID(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=createID(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},isDeletedByUndoStack=(e,t)=>some(e,e=>isDeleted(e.deletions,t)),redoItem=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return getItemCleanStart(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||redoItem(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=getItemCleanStart(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:getItemCleanStart(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:getItemCleanStart(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||isDeleted(r,d.right.id)||isDeletedByUndoStack(a.undoStack,d.right.id)||isDeletedByUndoStack(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=getItemCleanStart(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=createID(c,getState(s,c)),h=new Item(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,keepItem(h,!0),h.integrate(e,0),h};var Item=class e extends AbstractStruct{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=getState(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=getState(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ID&&this.id.client!==this.parent.client&&this.parent.clock>=getState(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=getItemCleanEnd(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=getItemCleanStart(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===GC||this.right&&this.right.constructor===GC)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ID){let e=getItem(n,this.parent);e.constructor===GC?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=getItemCleanEnd(e,e.doc.store,createID(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),compareIDs(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(compareIDs(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(getItem(e.doc.store,n.origin)))r.has(getItem(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null)this.right=this.left.right,this.left.right=this;else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),addStruct(e.doc.store,this),this.content.integrate(e,this),addChangedTypeToTransaction(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new GC(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:createID(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&compareIDs(e.origin,this.lastId)&&this.right===e&&compareIDs(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),addToDeleteSet(e.deleteSet,this.id.client,this.id.clock,this.length),addChangedTypeToTransaction(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw unexpectedCase();this.content.gc(e),t?replaceStruct(e,this,new GC(this.id,this.length)):this.content=new ContentDeleted(this.length)}write(e,t){let n=t>0?createID(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=findRootTypeKey(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===ID?(e.writeParentInfo(!1),e.writeLeftID(t)):unexpectedCase();i!==null&&e.writeString(i)}this.content.write(e,t)}};const readItemContent=(e,t)=>contentRefs[t&31](e),contentRefs=[()=>{unexpectedCase()},readContentDeleted,readContentJSON,readContentBinary,readContentString,readContentEmbed,readContentFormat,readContentType,readContentAny,readContentDoc,()=>{unexpectedCase()}],structSkipRefNumber=10;var Skip=class extends AbstractStruct{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){unexpectedCase()}write(e,t){e.writeInfo(structSkipRefNumber),writeVarUint$2(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const glo=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},importIdentifier=`__ $YJS$ __`;glo[importIdentifier]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),glo[importIdentifier]=!0;const highSurrogateRegex=/[\uD800-\uDBFF]/,lowSurrogateRegex=/[\uDC00-\uDFFF]/,simpleDiffString=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&highSurrogateRegex.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&lowSurrogateRegex.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},simpleDiff=simpleDiffString,digest=e=>{let t=createHash(`sha256`);return t.update(e),t.digest()},ySyncPluginKey=new PluginKey(`y-sync`),yUndoPluginKey=new PluginKey(`y-undo`),yCursorPluginKey=new PluginKey(`yjs-cursor`),_convolute=e=>{let t=6;for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},hashOfJSON=e=>toBase64(_convolute(digest(encodeAny(e)))),createEmptyMeta=()=>({mapping:new Map,isOMark:new Map}),isVisible=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!isDeleted(t.ds,e.id),createNodeIfNotExists=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof YXmlElement)return createNodeFromYElement(e,t,n,r,i,a);throw methodUnimplemented()}return o},createNodeFromYElement=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof YXmlElement){let s=createNodeIfNotExists(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof YText&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=createTextNodesFromYText(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):typeListToArraySnapshot(e,new Snapshot(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(isVisible(e._item,r)?isVisible(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=t.node(e.nodeName,s,o);return n.mapping.set(e,c),c}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},createTextNodesFromYText=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,attributesToMarks(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},createTypeFromTextNodes=(e,t)=>{let n=new YXmlText,r=e.map(e=>({insert:e.text,attributes:marksToAttributes(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},createTypeFromElementNode=(e,t)=>{let n=new YXmlElement(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}return n.insert(0,normalizePNodeContent(e).map(e=>createTypeFromTextOrElementNode(e,t))),t.mapping.set(n,e),n},createTypeFromTextOrElementNode=(e,t)=>e instanceof Array?createTypeFromTextNodes(e,t):createTypeFromElementNode(e,t),isObject=e=>typeof e==`object`&&!!e,equalAttrs=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||isObject(o)&&isObject(s)&&equalAttrs(o,s)}return r},normalizePNodeContent=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},equalYTextPText=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&keys$1(e.attributes||{}).length===t[n].marks.length&&every(e.attributes,(e,r)=>{let i=yattr2markname(r),a=t[n].marks;return a.find(e=>e.type.name===i)?equalAttrs(e,a.find(e=>e.type.name===i)?.attrs):!1}))},equalYTypePNode=(e,t)=>{if(e instanceof YXmlElement&&!(t instanceof Array)&&matchNodeName(e,t)){let n=normalizePNodeContent(t);return e._length===n.length&&equalAttrs(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>equalYTypePNode(e,n[t]))}return e instanceof YXmlText&&t instanceof Array&&equalYTextPText(e,t)},mappedIdentity=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),computeChildEqualityFactor=(e,t,n)=>{let r=e.toArray(),i=normalizePNodeContent(t),a=i.length,o=r.length,s=min$2(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(mappedIdentity(n.mapping.get(e),t))u=!0;else if(!equalYTypePNode(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(mappedIdentity(n.mapping.get(e),t))u=!0;else if(!equalYTypePNode(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},ytextTrans=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof ContentString?t+=n.content.str:n.content instanceof ContentFormat&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},updateYText=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=ytextTrans(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,marksToAttributes(e.marks,n))})),{insert:o,remove:s,index:c}=simpleDiff(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},hashedMarkNameRegex=/(.*)(--[a-zA-Z0-9+/=]{8})$/,yattr2markname=e=>hashedMarkNameRegex.exec(e)?.[1]??e,attributesToMarks=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(yattr2markname(r),e[r]));return n},marksToAttributes=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=setIfUndefined$1(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${hashOfJSON(e.toJSON())}`:e.type.name]=e.attrs}}),n},updateYFragment=(e,t,n,r)=>{if(t instanceof YXmlElement&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof YXmlElement){let e=t.getAttributes(),r=n.attrs;for(let n in r)r[n]===null?t.removeAttribute(n):e[n]!==r[n]&&n!==`ychange`&&t.setAttribute(n,r[n]);for(let n in e)r[n]===void 0&&t.removeAttribute(n)}let i=normalizePNodeContent(n),a=i.length,o=t.toArray(),s=o.length,c=min$2(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!mappedIdentity(r.mapping.get(e),t))if(equalYTypePNode(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!mappedIdentity(r.mapping.get(e),t))if(equalYTypePNode(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof YXmlText&&c instanceof Array)equalYTextPText(n,c)||updateYText(n,c,r),l+=1;else{let i=n instanceof YXmlElement&&matchNodeName(n,c),a=d instanceof YXmlElement&&matchNodeName(d,f);if(i&&a){let e=computeChildEqualityFactor(n,c,r),t=computeChildEqualityFactor(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(updateYFragment(e,n,c,r),l+=1):a?(updateYFragment(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[createTypeFromTextOrElementNode(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof YXmlText?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(createTypeFromTextOrElementNode(i[t],r));t.insert(l,e)}},ySyncPluginKey)},matchNodeName=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,yXmlFragmentToProseMirrorFragment=(e,t)=>{let n=e.toArray().map(e=>createNodeFromYElement(e,t,createEmptyMeta())).filter(e=>e!==null);return Fragment.fromArray(n)},yXmlFragmentToProseMirrorRootNode=(e,t)=>t.topNodeType.create(null,yXmlFragmentToProseMirrorFragment(e,t)),DEBOUNCE_MS=100;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let r={v:1,ch:e,seq:n};t.broadcastStateless(JSON.stringify(r)),incrementCC1Broadcast(),setCC1LastSeq(e,n),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions);var require_AbstractAsyncHooksContextManager=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AbstractAsyncHooksContextManager=void 0;let t=__require$1(`events`),n=[`addListener`,`on`,`once`,`prependListener`,`prependOnceListener`];e.AbstractAsyncHooksContextManager=class{bind(e,n){return n instanceof t.EventEmitter?this._bindEventEmitter(e,n):typeof n==`function`?this._bindFunction(e,n):n}_bindFunction(e,t){let n=this,r=function(...r){return n.with(e,()=>t.apply(this,r))};return Object.defineProperty(r,`length`,{enumerable:!1,configurable:!0,writable:!1,value:t.length}),r}_bindEventEmitter(e,t){return this._getPatchMap(t)===void 0?(this._createPatchMap(t),n.forEach(n=>{t[n]!==void 0&&(t[n]=this._patchAddListener(t,t[n],e))}),typeof t.removeListener==`function`&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off==`function`&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners==`function`&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners)),t):t}_patchRemoveListener(e,t){let n=this;return function(r,i){let a=n._getPatchMap(e)?.[r];if(a===void 0)return t.call(this,r,i);let o=a.get(i);return t.call(this,r,o||i)}}_patchRemoveAllListeners(e,t){let n=this;return function(r){let i=n._getPatchMap(e);return i!==void 0&&(arguments.length===0?n._createPatchMap(e):i[r]!==void 0&&delete i[r]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let r=this;return function(i,a){if(r._wrapped)return t.call(this,i,a);let o=r._getPatchMap(e);o===void 0&&(o=r._createPatchMap(e));let s=o[i];s===void 0&&(s=new WeakMap,o[i]=s);let c=r.bind(n,a);s.set(a,c),r._wrapped=!0;try{return t.call(this,i,c)}finally{r._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol(`OtListeners`);_wrapped=!1}})),require_AsyncHooksContextManager=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AsyncHooksContextManager=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=__require$1(`async_hooks`),r=require_AbstractAsyncHooksContextManager();e.AsyncHooksContextManager=class extends r.AbstractAsyncHooksContextManager{_asyncHook;_contexts=new Map;_stack=[];constructor(){super(),this._asyncHook=n.createHook({init:this._init.bind(this),before:this._before.bind(this),after:this._after.bind(this),destroy:this._destroy.bind(this),promiseResolve:this._destroy.bind(this)})}active(){return this._stack[this._stack.length-1]??t.ROOT_CONTEXT}with(e,t,n,...r){this._enterContext(e);try{return t.call(n,...r)}finally{this._exitContext()}}enable(){return this._asyncHook.enable(),this}disable(){return this._asyncHook.disable(),this._contexts.clear(),this._stack=[],this}_init(e,t){if(t===`TIMERWRAP`)return;let n=this._stack[this._stack.length-1];n!==void 0&&this._contexts.set(e,n)}_destroy(e){this._contexts.delete(e)}_before(e){let t=this._contexts.get(e);t!==void 0&&this._enterContext(t)}_after(){this._exitContext()}_enterContext(e){this._stack.push(e)}_exitContext(){this._stack.pop()}}})),require_AsyncLocalStorageContextManager=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AsyncLocalStorageContextManager=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=__require$1(`async_hooks`),r=require_AbstractAsyncHooksContextManager();e.AsyncLocalStorageContextManager=class extends r.AbstractAsyncHooksContextManager{_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new n.AsyncLocalStorage}active(){return this._asyncLocalStorage.getStore()??t.ROOT_CONTEXT}with(e,t,n,...r){let i=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,i,...r)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}}})),require_src$15=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AsyncLocalStorageContextManager=e.AsyncHooksContextManager=void 0;var t=require_AsyncHooksContextManager();Object.defineProperty(e,`AsyncHooksContextManager`,{enumerable:!0,get:function(){return t.AsyncHooksContextManager}});var n=require_AsyncLocalStorageContextManager();Object.defineProperty(e,`AsyncLocalStorageContextManager`,{enumerable:!0,get:function(){return n.AsyncLocalStorageContextManager}})})),require_suppress_tracing$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function n(e){return e.setValue(t,!0)}e.suppressTracing=n;function r(e){return e.deleteValue(t)}e.unsuppressTracing=r;function i(e){return e.getValue(t)===!0}e.isTracingSuppressed=i})),require_constants$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$14=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_constants$4();function r(e){return e.reduce((e,t)=>{let r=`${e}${e===``?``:n.BAGGAGE_ITEMS_SEPARATOR}${t}`;return r.length>n.BAGGAGE_MAX_TOTAL_LENGTH?e:r},``)}e.serializeKeyPairs=r;function i(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(r+=n.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}e.getKeyPairs=i;function a(e){if(!e)return;let r=e.indexOf(n.BAGGAGE_PROPERTIES_SEPARATOR),i=r===-1?e:e.substring(0,r),a=i.indexOf(n.BAGGAGE_KEY_PAIR_SEPARATOR);if(a<=0)return;let o=i.substring(0,a).trim(),s=i.substring(a+1).trim();if(!o||!s)return;let c,l;try{c=decodeURIComponent(o),l=decodeURIComponent(s)}catch{return}let u;if(r!==-1&&r<e.length-1){let n=e.substring(r+1);u=(0,t.baggageEntryMetadataFromString)(n)}return{key:c,value:l,metadata:u}}e.parsePairKeyValue=a;function o(e){let t={};return typeof e==`string`&&e.length>0&&e.split(n.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let n=a(e);n!==void 0&&n.value.length>0&&(t[n.key]=n.value)}),t}e.parseKeyPairsIntoRecord=o})),require_W3CBaggagePropagator$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$3(),r=require_constants$4(),i=require_utils$14();e.W3CBaggagePropagator=class{inject(e,a,o){let s=t.propagation.getBaggage(e);if(!s||(0,n.isTracingSuppressed)(e))return;let c=(0,i.getKeyPairs)(s).filter(e=>e.length<=r.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,r.BAGGAGE_MAX_NAME_VALUE_PAIRS),l=(0,i.serializeKeyPairs)(c);l.length>0&&o.set(a,r.BAGGAGE_HEADER,l)}extract(e,n,a){let o=a.get(n,r.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(r.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let c={};return s.length===0||(s.split(r.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,i.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),c[t.key]=e}}),Object.entries(c).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(c))}fields(){return[r.BAGGAGE_HEADER]}}})),require_anchored_clock$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function n(e){let n={};if(typeof e!=`object`||!e)return n;for(let a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;if(!r(a)){t.diag.warn(`Invalid attribute key: ${a}`);continue}let o=e[a];if(!i(o)){t.diag.warn(`Invalid attribute value set for key: ${a}`);continue}Array.isArray(o)?n[a]=o.slice():n[a]=o}return n}e.sanitizeAttributes=n;function r(e){return typeof e==`string`&&e!==``}e.isAttributeKey=r;function i(e){return e==null?!0:Array.isArray(e)?a(e):o(typeof e)}e.isAttributeValue=i;function a(e){let t;for(let n of e){if(n==null)continue;let e=typeof n;if(e!==t){if(!t){if(o(e)){t=e;continue}return!1}return!1}}return!0}function o(e){switch(e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function n(){return e=>{t.diag.error(r(e))}}e.loggingErrorHandler=n;function r(e){return typeof e==`string`?e:JSON.stringify(i(e))}function i(e){let t={},n=e;for(;n!==null;)Object.getOwnPropertyNames(n).forEach(e=>{if(t[e])return;let r=n[e];r&&(t[e]=String(r))}),n=Object.getPrototypeOf(n);return t}})),require_global_error_handler$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$3().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),require_environment$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=__require$1(`util`);function r(e){let r=process.env[e];if(r==null||r.trim()===``)return;let i=Number(r);if(isNaN(i)){t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected a number, using defaults`);return}return i}e.getNumberFromEnv=r;function i(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=i;function a(e){let r=process.env[e]?.trim().toLowerCase();return r==null||r===``?!1:r===`true`?!0:(r===`false`||t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=a;function o(e){return i(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=o})),require_globalThis$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=globalThis})),require_version$6=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`}));function createConstMap(e){let t={},n=e.length;for(let r=0;r<n;r++){let n=e[r];n&&(t[String(n).toUpperCase().replace(/[-.]/g,`_`)]=n)}return t}var init_utils=__esmMin((()=>{})),TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME,SEMATTRS_DB_STATEMENT,SEMATTRS_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT,SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE,SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE,SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME,SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_LINENO,SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_URL,SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM,SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes,TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_DB2,DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_EDB,DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_H2,DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB,DbSystemValues,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ALL,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO,DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_ANY,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues,TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER,FaasTriggerValues,TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues,TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS,FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP,FaasInvokedProviderValues,TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_IP,NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER,NetTransportValues,TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_LTE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_GSM,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NR,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues,TMP_HTTPFLAVORVALUES_HTTP_1_0,TMP_HTTPFLAVORVALUES_HTTP_1_1,TMP_HTTPFLAVORVALUES_HTTP_2_0,TMP_HTTPFLAVORVALUES_SPDY,TMP_HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_HTTP_1_0,HTTPFLAVORVALUES_HTTP_1_1,HTTPFLAVORVALUES_HTTP_2_0,HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC,HttpFlavorValues,TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues,TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues,TMP_RPCGRPCSTATUSCODEVALUES_OK,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RPCGRPCSTATUSCODEVALUES_OK,RPCGRPCSTATUSCODEVALUES_CANCELLED,RPCGRPCSTATUSCODEVALUES_UNKNOWN,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,RPCGRPCSTATUSCODEVALUES_NOT_FOUND,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,RPCGRPCSTATUSCODEVALUES_ABORTED,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,RPCGRPCSTATUSCODEVALUES_INTERNAL,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,RPCGRPCSTATUSCODEVALUES_DATA_LOSS,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RpcGrpcStatusCodeValues,TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED,MessageTypeValues,init_SemanticAttributes=__esmMin((()=>{init_utils(),TMP_AWS_LAMBDA_INVOKED_ARN=`aws.lambda.invoked_arn`,TMP_DB_SYSTEM=`db.system`,TMP_DB_CONNECTION_STRING=`db.connection_string`,TMP_DB_USER=`db.user`,TMP_DB_JDBC_DRIVER_CLASSNAME=`db.jdbc.driver_classname`,TMP_DB_NAME=`db.name`,TMP_DB_STATEMENT=`db.statement`,TMP_DB_OPERATION=`db.operation`,TMP_DB_MSSQL_INSTANCE_NAME=`db.mssql.instance_name`,TMP_DB_CASSANDRA_KEYSPACE=`db.cassandra.keyspace`,TMP_DB_CASSANDRA_PAGE_SIZE=`db.cassandra.page_size`,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL=`db.cassandra.consistency_level`,TMP_DB_CASSANDRA_TABLE=`db.cassandra.table`,TMP_DB_CASSANDRA_IDEMPOTENCE=`db.cassandra.idempotence`,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=`db.cassandra.speculative_execution_count`,TMP_DB_CASSANDRA_COORDINATOR_ID=`db.cassandra.coordinator.id`,TMP_DB_CASSANDRA_COORDINATOR_DC=`db.cassandra.coordinator.dc`,TMP_DB_HBASE_NAMESPACE=`db.hbase.namespace`,TMP_DB_REDIS_DATABASE_INDEX=`db.redis.database_index`,TMP_DB_MONGODB_COLLECTION=`db.mongodb.collection`,TMP_DB_SQL_TABLE=`db.sql.table`,TMP_EXCEPTION_TYPE=`exception.type`,TMP_EXCEPTION_MESSAGE=`exception.message`,TMP_EXCEPTION_STACKTRACE=`exception.stacktrace`,TMP_EXCEPTION_ESCAPED=`exception.escaped`,TMP_FAAS_TRIGGER=`faas.trigger`,TMP_FAAS_EXECUTION=`faas.execution`,TMP_FAAS_DOCUMENT_COLLECTION=`faas.document.collection`,TMP_FAAS_DOCUMENT_OPERATION=`faas.document.operation`,TMP_FAAS_DOCUMENT_TIME=`faas.document.time`,TMP_FAAS_DOCUMENT_NAME=`faas.document.name`,TMP_FAAS_TIME=`faas.time`,TMP_FAAS_CRON=`faas.cron`,TMP_FAAS_COLDSTART=`faas.coldstart`,TMP_FAAS_INVOKED_NAME=`faas.invoked_name`,TMP_FAAS_INVOKED_PROVIDER=`faas.invoked_provider`,TMP_FAAS_INVOKED_REGION=`faas.invoked_region`,TMP_NET_TRANSPORT=`net.transport`,TMP_NET_PEER_IP=`net.peer.ip`,TMP_NET_PEER_PORT=`net.peer.port`,TMP_NET_PEER_NAME=`net.peer.name`,TMP_NET_HOST_IP=`net.host.ip`,TMP_NET_HOST_PORT=`net.host.port`,TMP_NET_HOST_NAME=`net.host.name`,TMP_NET_HOST_CONNECTION_TYPE=`net.host.connection.type`,TMP_NET_HOST_CONNECTION_SUBTYPE=`net.host.connection.subtype`,TMP_NET_HOST_CARRIER_NAME=`net.host.carrier.name`,TMP_NET_HOST_CARRIER_MCC=`net.host.carrier.mcc`,TMP_NET_HOST_CARRIER_MNC=`net.host.carrier.mnc`,TMP_NET_HOST_CARRIER_ICC=`net.host.carrier.icc`,TMP_PEER_SERVICE=`peer.service`,TMP_ENDUSER_ID=`enduser.id`,TMP_ENDUSER_ROLE=`enduser.role`,TMP_ENDUSER_SCOPE=`enduser.scope`,TMP_THREAD_ID=`thread.id`,TMP_THREAD_NAME=`thread.name`,TMP_CODE_FUNCTION=`code.function`,TMP_CODE_NAMESPACE=`code.namespace`,TMP_CODE_FILEPATH=`code.filepath`,TMP_CODE_LINENO=`code.lineno`,TMP_HTTP_METHOD=`http.method`,TMP_HTTP_URL=`http.url`,TMP_HTTP_TARGET=`http.target`,TMP_HTTP_HOST=`http.host`,TMP_HTTP_SCHEME=`http.scheme`,TMP_HTTP_STATUS_CODE=`http.status_code`,TMP_HTTP_FLAVOR=`http.flavor`,TMP_HTTP_USER_AGENT=`http.user_agent`,TMP_HTTP_REQUEST_CONTENT_LENGTH=`http.request_content_length`,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=`http.request_content_length_uncompressed`,TMP_HTTP_RESPONSE_CONTENT_LENGTH=`http.response_content_length`,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=`http.response_content_length_uncompressed`,TMP_HTTP_SERVER_NAME=`http.server_name`,TMP_HTTP_ROUTE=`http.route`,TMP_HTTP_CLIENT_IP=`http.client_ip`,TMP_AWS_DYNAMODB_TABLE_NAMES=`aws.dynamodb.table_names`,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY=`aws.dynamodb.consumed_capacity`,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=`aws.dynamodb.item_collection_metrics`,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=`aws.dynamodb.provisioned_read_capacity`,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=`aws.dynamodb.provisioned_write_capacity`,TMP_AWS_DYNAMODB_CONSISTENT_READ=`aws.dynamodb.consistent_read`,TMP_AWS_DYNAMODB_PROJECTION=`aws.dynamodb.projection`,TMP_AWS_DYNAMODB_LIMIT=`aws.dynamodb.limit`,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET=`aws.dynamodb.attributes_to_get`,TMP_AWS_DYNAMODB_INDEX_NAME=`aws.dynamodb.index_name`,TMP_AWS_DYNAMODB_SELECT=`aws.dynamodb.select`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=`aws.dynamodb.global_secondary_indexes`,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=`aws.dynamodb.local_secondary_indexes`,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=`aws.dynamodb.exclusive_start_table`,TMP_AWS_DYNAMODB_TABLE_COUNT=`aws.dynamodb.table_count`,TMP_AWS_DYNAMODB_SCAN_FORWARD=`aws.dynamodb.scan_forward`,TMP_AWS_DYNAMODB_SEGMENT=`aws.dynamodb.segment`,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS=`aws.dynamodb.total_segments`,TMP_AWS_DYNAMODB_COUNT=`aws.dynamodb.count`,TMP_AWS_DYNAMODB_SCANNED_COUNT=`aws.dynamodb.scanned_count`,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=`aws.dynamodb.attribute_definitions`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=`aws.dynamodb.global_secondary_index_updates`,TMP_MESSAGING_SYSTEM=`messaging.system`,TMP_MESSAGING_DESTINATION=`messaging.destination`,TMP_MESSAGING_DESTINATION_KIND=`messaging.destination_kind`,TMP_MESSAGING_TEMP_DESTINATION=`messaging.temp_destination`,TMP_MESSAGING_PROTOCOL=`messaging.protocol`,TMP_MESSAGING_PROTOCOL_VERSION=`messaging.protocol_version`,TMP_MESSAGING_URL=`messaging.url`,TMP_MESSAGING_MESSAGE_ID=`messaging.message_id`,TMP_MESSAGING_CONVERSATION_ID=`messaging.conversation_id`,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=`messaging.message_payload_size_bytes`,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=`messaging.message_payload_compressed_size_bytes`,TMP_MESSAGING_OPERATION=`messaging.operation`,TMP_MESSAGING_CONSUMER_ID=`messaging.consumer_id`,TMP_MESSAGING_RABBITMQ_ROUTING_KEY=`messaging.rabbitmq.routing_key`,TMP_MESSAGING_KAFKA_MESSAGE_KEY=`messaging.kafka.message_key`,TMP_MESSAGING_KAFKA_CONSUMER_GROUP=`messaging.kafka.consumer_group`,TMP_MESSAGING_KAFKA_CLIENT_ID=`messaging.kafka.client_id`,TMP_MESSAGING_KAFKA_PARTITION=`messaging.kafka.partition`,TMP_MESSAGING_KAFKA_TOMBSTONE=`messaging.kafka.tombstone`,TMP_RPC_SYSTEM=`rpc.system`,TMP_RPC_SERVICE=`rpc.service`,TMP_RPC_METHOD=`rpc.method`,TMP_RPC_GRPC_STATUS_CODE=`rpc.grpc.status_code`,TMP_RPC_JSONRPC_VERSION=`rpc.jsonrpc.version`,TMP_RPC_JSONRPC_REQUEST_ID=`rpc.jsonrpc.request_id`,TMP_RPC_JSONRPC_ERROR_CODE=`rpc.jsonrpc.error_code`,TMP_RPC_JSONRPC_ERROR_MESSAGE=`rpc.jsonrpc.error_message`,TMP_MESSAGE_TYPE=`message.type`,TMP_MESSAGE_ID=`message.id`,TMP_MESSAGE_COMPRESSED_SIZE=`message.compressed_size`,TMP_MESSAGE_UNCOMPRESSED_SIZE=`message.uncompressed_size`,SEMATTRS_AWS_LAMBDA_INVOKED_ARN=TMP_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM=TMP_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING=TMP_DB_CONNECTION_STRING,SEMATTRS_DB_USER=TMP_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME=TMP_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME=TMP_DB_NAME,SEMATTRS_DB_STATEMENT=TMP_DB_STATEMENT,SEMATTRS_DB_OPERATION=TMP_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME=TMP_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE=TMP_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE=TMP_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL=TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE=TMP_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE=TMP_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID=TMP_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC=TMP_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE=TMP_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX=TMP_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION=TMP_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE=TMP_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE=TMP_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE=TMP_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE=TMP_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED=TMP_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER=TMP_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION=TMP_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION=TMP_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION=TMP_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME=TMP_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME=TMP_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME=TMP_FAAS_TIME,SEMATTRS_FAAS_CRON=TMP_FAAS_CRON,SEMATTRS_FAAS_COLDSTART=TMP_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME=TMP_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER=TMP_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION=TMP_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT=TMP_NET_TRANSPORT,SEMATTRS_NET_PEER_IP=TMP_NET_PEER_IP,SEMATTRS_NET_PEER_PORT=TMP_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME=TMP_NET_PEER_NAME,SEMATTRS_NET_HOST_IP=TMP_NET_HOST_IP,SEMATTRS_NET_HOST_PORT=TMP_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME=TMP_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE=TMP_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE=TMP_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME=TMP_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC=TMP_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC=TMP_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC=TMP_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE=TMP_PEER_SERVICE,SEMATTRS_ENDUSER_ID=TMP_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE=TMP_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE=TMP_ENDUSER_SCOPE,SEMATTRS_THREAD_ID=TMP_THREAD_ID,SEMATTRS_THREAD_NAME=TMP_THREAD_NAME,SEMATTRS_CODE_FUNCTION=TMP_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE=TMP_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH=TMP_CODE_FILEPATH,SEMATTRS_CODE_LINENO=TMP_CODE_LINENO,SEMATTRS_HTTP_METHOD=TMP_HTTP_METHOD,SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_TARGET=TMP_HTTP_TARGET,SEMATTRS_HTTP_HOST=TMP_HTTP_HOST,SEMATTRS_HTTP_SCHEME=TMP_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE=TMP_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR=TMP_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH=TMP_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH=TMP_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME=TMP_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE=TMP_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP=TMP_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES=TMP_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY=TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ=TMP_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION=TMP_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT=TMP_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET=TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME=TMP_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT=TMP_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT=TMP_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD=TMP_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT=TMP_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS=TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT=TMP_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT=TMP_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM=TMP_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION=TMP_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND=TMP_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION=TMP_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL=TMP_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION=TMP_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL=TMP_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID=TMP_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID=TMP_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION=TMP_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID=TMP_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY=TMP_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY=TMP_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP=TMP_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID=TMP_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION=TMP_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE=TMP_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM=TMP_RPC_SYSTEM,SEMATTRS_RPC_SERVICE=TMP_RPC_SERVICE,SEMATTRS_RPC_METHOD=TMP_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE=TMP_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION=TMP_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID=TMP_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE=TMP_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE=TMP_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE=TMP_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID=TMP_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE=TMP_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE=TMP_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes=createConstMap([TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE]),TMP_DBSYSTEMVALUES_OTHER_SQL=`other_sql`,TMP_DBSYSTEMVALUES_MSSQL=`mssql`,TMP_DBSYSTEMVALUES_MYSQL=`mysql`,TMP_DBSYSTEMVALUES_ORACLE=`oracle`,TMP_DBSYSTEMVALUES_DB2=`db2`,TMP_DBSYSTEMVALUES_POSTGRESQL=`postgresql`,TMP_DBSYSTEMVALUES_REDSHIFT=`redshift`,TMP_DBSYSTEMVALUES_HIVE=`hive`,TMP_DBSYSTEMVALUES_CLOUDSCAPE=`cloudscape`,TMP_DBSYSTEMVALUES_HSQLDB=`hsqldb`,TMP_DBSYSTEMVALUES_PROGRESS=`progress`,TMP_DBSYSTEMVALUES_MAXDB=`maxdb`,TMP_DBSYSTEMVALUES_HANADB=`hanadb`,TMP_DBSYSTEMVALUES_INGRES=`ingres`,TMP_DBSYSTEMVALUES_FIRSTSQL=`firstsql`,TMP_DBSYSTEMVALUES_EDB=`edb`,TMP_DBSYSTEMVALUES_CACHE=`cache`,TMP_DBSYSTEMVALUES_ADABAS=`adabas`,TMP_DBSYSTEMVALUES_FIREBIRD=`firebird`,TMP_DBSYSTEMVALUES_DERBY=`derby`,TMP_DBSYSTEMVALUES_FILEMAKER=`filemaker`,TMP_DBSYSTEMVALUES_INFORMIX=`informix`,TMP_DBSYSTEMVALUES_INSTANTDB=`instantdb`,TMP_DBSYSTEMVALUES_INTERBASE=`interbase`,TMP_DBSYSTEMVALUES_MARIADB=`mariadb`,TMP_DBSYSTEMVALUES_NETEZZA=`netezza`,TMP_DBSYSTEMVALUES_PERVASIVE=`pervasive`,TMP_DBSYSTEMVALUES_POINTBASE=`pointbase`,TMP_DBSYSTEMVALUES_SQLITE=`sqlite`,TMP_DBSYSTEMVALUES_SYBASE=`sybase`,TMP_DBSYSTEMVALUES_TERADATA=`teradata`,TMP_DBSYSTEMVALUES_VERTICA=`vertica`,TMP_DBSYSTEMVALUES_H2=`h2`,TMP_DBSYSTEMVALUES_COLDFUSION=`coldfusion`,TMP_DBSYSTEMVALUES_CASSANDRA=`cassandra`,TMP_DBSYSTEMVALUES_HBASE=`hbase`,TMP_DBSYSTEMVALUES_MONGODB=`mongodb`,TMP_DBSYSTEMVALUES_REDIS=`redis`,TMP_DBSYSTEMVALUES_COUCHBASE=`couchbase`,TMP_DBSYSTEMVALUES_COUCHDB=`couchdb`,TMP_DBSYSTEMVALUES_COSMOSDB=`cosmosdb`,TMP_DBSYSTEMVALUES_DYNAMODB=`dynamodb`,TMP_DBSYSTEMVALUES_NEO4J=`neo4j`,TMP_DBSYSTEMVALUES_GEODE=`geode`,TMP_DBSYSTEMVALUES_ELASTICSEARCH=`elasticsearch`,TMP_DBSYSTEMVALUES_MEMCACHED=`memcached`,TMP_DBSYSTEMVALUES_COCKROACHDB=`cockroachdb`,DBSYSTEMVALUES_OTHER_SQL=TMP_DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL=TMP_DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL=TMP_DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE=TMP_DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_POSTGRESQL=TMP_DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT=TMP_DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE=TMP_DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE=TMP_DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB=TMP_DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS=TMP_DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB=TMP_DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB=TMP_DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES=TMP_DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL=TMP_DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_CACHE=TMP_DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS=TMP_DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD=TMP_DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY=TMP_DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER=TMP_DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX=TMP_DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB=TMP_DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE=TMP_DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB=TMP_DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA=TMP_DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE=TMP_DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE=TMP_DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE=TMP_DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE=TMP_DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA=TMP_DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA=TMP_DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_COLDFUSION=TMP_DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA=TMP_DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE=TMP_DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB=TMP_DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS=TMP_DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE=TMP_DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB=TMP_DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB=TMP_DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB=TMP_DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J=TMP_DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE=TMP_DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH=TMP_DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED=TMP_DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB=TMP_DBSYSTEMVALUES_COCKROACHDB,DbSystemValues=createConstMap([TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB]),TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL=`all`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=`each_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=`quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=`local_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE=`one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO=`two`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE=`three`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=`local_one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY=`any`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=`serial`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=`local_serial`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_THREE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues=createConstMap([TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL]),TMP_FAASTRIGGERVALUES_DATASOURCE=`datasource`,TMP_FAASTRIGGERVALUES_HTTP=`http`,TMP_FAASTRIGGERVALUES_PUBSUB=`pubsub`,TMP_FAASTRIGGERVALUES_TIMER=`timer`,TMP_FAASTRIGGERVALUES_OTHER=`other`,FAASTRIGGERVALUES_DATASOURCE=TMP_FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP=TMP_FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB=TMP_FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER=TMP_FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER=TMP_FAASTRIGGERVALUES_OTHER,FaasTriggerValues=createConstMap([TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER]),TMP_FAASDOCUMENTOPERATIONVALUES_INSERT=`insert`,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT=`edit`,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE=`delete`,FAASDOCUMENTOPERATIONVALUES_INSERT=TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT=TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE=TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues=createConstMap([TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE]),TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_FAASINVOKEDPROVIDERVALUES_AWS=`aws`,TMP_FAASINVOKEDPROVIDERVALUES_AZURE=`azure`,TMP_FAASINVOKEDPROVIDERVALUES_GCP=`gcp`,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AZURE=TMP_FAASINVOKEDPROVIDERVALUES_AZURE,FaasInvokedProviderValues=createConstMap([TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP]),TMP_NETTRANSPORTVALUES_IP_TCP=`ip_tcp`,TMP_NETTRANSPORTVALUES_IP_UDP=`ip_udp`,TMP_NETTRANSPORTVALUES_IP=`ip`,TMP_NETTRANSPORTVALUES_UNIX=`unix`,TMP_NETTRANSPORTVALUES_PIPE=`pipe`,TMP_NETTRANSPORTVALUES_INPROC=`inproc`,TMP_NETTRANSPORTVALUES_OTHER=`other`,NETTRANSPORTVALUES_IP_TCP=TMP_NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP=TMP_NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_UNIX=TMP_NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE=TMP_NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC=TMP_NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER=TMP_NETTRANSPORTVALUES_OTHER,NetTransportValues=createConstMap([TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER]),TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI=`wifi`,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED=`wired`,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL=`cell`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=`unavailable`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=`unknown`,NETHOSTCONNECTIONTYPEVALUES_WIFI=TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED=TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL=TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues=createConstMap([TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN]),TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=`gprs`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=`edge`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=`umts`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=`cdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=`evdo_0`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=`evdo_a`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=`cdma2000_1xrtt`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=`hsdpa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=`hsupa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=`hspa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=`iden`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=`evdo_b`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE=`lte`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=`ehrpd`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=`hspap`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM=`gsm`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=`td_scdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=`iwlan`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR=`nr`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=`nrnsa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=`lte_ca`,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues=createConstMap([TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA]),TMP_HTTPFLAVORVALUES_HTTP_1_0=`1.0`,TMP_HTTPFLAVORVALUES_HTTP_1_1=`1.1`,TMP_HTTPFLAVORVALUES_HTTP_2_0=`2.0`,TMP_HTTPFLAVORVALUES_SPDY=`SPDY`,TMP_HTTPFLAVORVALUES_QUIC=`QUIC`,HTTPFLAVORVALUES_SPDY=TMP_HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC=TMP_HTTPFLAVORVALUES_QUIC,HttpFlavorValues={HTTP_1_0:TMP_HTTPFLAVORVALUES_HTTP_1_0,HTTP_1_1:TMP_HTTPFLAVORVALUES_HTTP_1_1,HTTP_2_0:TMP_HTTPFLAVORVALUES_HTTP_2_0,SPDY:TMP_HTTPFLAVORVALUES_SPDY,QUIC:TMP_HTTPFLAVORVALUES_QUIC},TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE=`queue`,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC=`topic`,MESSAGINGDESTINATIONKINDVALUES_QUEUE=TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC=TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues=createConstMap([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]),TMP_MESSAGINGOPERATIONVALUES_RECEIVE=`receive`,TMP_MESSAGINGOPERATIONVALUES_PROCESS=`process`,MESSAGINGOPERATIONVALUES_RECEIVE=TMP_MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS=TMP_MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues=createConstMap([TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS]),TMP_RPCGRPCSTATUSCODEVALUES_OK=0,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED=1,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN=2,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT=3,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED=4,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND=5,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS=6,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED=7,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED=8,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION=9,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED=10,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE=11,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED=12,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL=13,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE=14,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS=15,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED=16,RpcGrpcStatusCodeValues={OK:TMP_RPCGRPCSTATUSCODEVALUES_OK,CANCELLED:TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,UNKNOWN:TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,INVALID_ARGUMENT:TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,DEADLINE_EXCEEDED:TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,NOT_FOUND:TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,ALREADY_EXISTS:TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,PERMISSION_DENIED:TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RESOURCE_EXHAUSTED:TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,FAILED_PRECONDITION:TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,ABORTED:TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,OUT_OF_RANGE:TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,UNIMPLEMENTED:TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,INTERNAL:TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,UNAVAILABLE:TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,DATA_LOSS:TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,UNAUTHENTICATED:TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED},TMP_MESSAGETYPEVALUES_SENT=`SENT`,TMP_MESSAGETYPEVALUES_RECEIVED=`RECEIVED`,MESSAGETYPEVALUES_SENT=TMP_MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED=TMP_MESSAGETYPEVALUES_RECEIVED,MessageTypeValues=createConstMap([TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED])})),init_trace=__esmMin((()=>{init_SemanticAttributes()})),TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION,SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE,SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION,SemanticResourceAttributes,TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP,CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS,CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP,CloudProviderValues,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues,TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AWSECSLAUNCHTYPEVALUES_EC2,AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues,TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86,HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86,HostArchValues,TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS,OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX,OSTYPEVALUES_AIX,OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS,OsTypeValues,TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRYSDKLANGUAGEVALUES_CPP,TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO,TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP,TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues,init_SemanticResourceAttributes=__esmMin((()=>{init_utils(),TMP_CLOUD_PROVIDER=`cloud.provider`,TMP_CLOUD_ACCOUNT_ID=`cloud.account.id`,TMP_CLOUD_REGION=`cloud.region`,TMP_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,TMP_CLOUD_PLATFORM=`cloud.platform`,TMP_AWS_ECS_CONTAINER_ARN=`aws.ecs.container.arn`,TMP_AWS_ECS_CLUSTER_ARN=`aws.ecs.cluster.arn`,TMP_AWS_ECS_LAUNCHTYPE=`aws.ecs.launchtype`,TMP_AWS_ECS_TASK_ARN=`aws.ecs.task.arn`,TMP_AWS_ECS_TASK_FAMILY=`aws.ecs.task.family`,TMP_AWS_ECS_TASK_REVISION=`aws.ecs.task.revision`,TMP_AWS_EKS_CLUSTER_ARN=`aws.eks.cluster.arn`,TMP_AWS_LOG_GROUP_NAMES=`aws.log.group.names`,TMP_AWS_LOG_GROUP_ARNS=`aws.log.group.arns`,TMP_AWS_LOG_STREAM_NAMES=`aws.log.stream.names`,TMP_AWS_LOG_STREAM_ARNS=`aws.log.stream.arns`,TMP_CONTAINER_NAME=`container.name`,TMP_CONTAINER_ID=`container.id`,TMP_CONTAINER_RUNTIME=`container.runtime`,TMP_CONTAINER_IMAGE_NAME=`container.image.name`,TMP_CONTAINER_IMAGE_TAG=`container.image.tag`,TMP_DEPLOYMENT_ENVIRONMENT=`deployment.environment`,TMP_DEVICE_ID=`device.id`,TMP_DEVICE_MODEL_IDENTIFIER=`device.model.identifier`,TMP_DEVICE_MODEL_NAME=`device.model.name`,TMP_FAAS_NAME=`faas.name`,TMP_FAAS_ID=`faas.id`,TMP_FAAS_VERSION=`faas.version`,TMP_FAAS_INSTANCE=`faas.instance`,TMP_FAAS_MAX_MEMORY=`faas.max_memory`,TMP_HOST_ID=`host.id`,TMP_HOST_NAME=`host.name`,TMP_HOST_TYPE=`host.type`,TMP_HOST_ARCH=`host.arch`,TMP_HOST_IMAGE_NAME=`host.image.name`,TMP_HOST_IMAGE_ID=`host.image.id`,TMP_HOST_IMAGE_VERSION=`host.image.version`,TMP_K8S_CLUSTER_NAME=`k8s.cluster.name`,TMP_K8S_NODE_NAME=`k8s.node.name`,TMP_K8S_NODE_UID=`k8s.node.uid`,TMP_K8S_NAMESPACE_NAME=`k8s.namespace.name`,TMP_K8S_POD_UID=`k8s.pod.uid`,TMP_K8S_POD_NAME=`k8s.pod.name`,TMP_K8S_CONTAINER_NAME=`k8s.container.name`,TMP_K8S_REPLICASET_UID=`k8s.replicaset.uid`,TMP_K8S_REPLICASET_NAME=`k8s.replicaset.name`,TMP_K8S_DEPLOYMENT_UID=`k8s.deployment.uid`,TMP_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,TMP_K8S_STATEFULSET_UID=`k8s.statefulset.uid`,TMP_K8S_STATEFULSET_NAME=`k8s.statefulset.name`,TMP_K8S_DAEMONSET_UID=`k8s.daemonset.uid`,TMP_K8S_DAEMONSET_NAME=`k8s.daemonset.name`,TMP_K8S_JOB_UID=`k8s.job.uid`,TMP_K8S_JOB_NAME=`k8s.job.name`,TMP_K8S_CRONJOB_UID=`k8s.cronjob.uid`,TMP_K8S_CRONJOB_NAME=`k8s.cronjob.name`,TMP_OS_TYPE=`os.type`,TMP_OS_DESCRIPTION=`os.description`,TMP_OS_NAME=`os.name`,TMP_OS_VERSION=`os.version`,TMP_PROCESS_PID=`process.pid`,TMP_PROCESS_EXECUTABLE_NAME=`process.executable.name`,TMP_PROCESS_EXECUTABLE_PATH=`process.executable.path`,TMP_PROCESS_COMMAND=`process.command`,TMP_PROCESS_COMMAND_LINE=`process.command_line`,TMP_PROCESS_COMMAND_ARGS=`process.command_args`,TMP_PROCESS_OWNER=`process.owner`,TMP_PROCESS_RUNTIME_NAME=`process.runtime.name`,TMP_PROCESS_RUNTIME_VERSION=`process.runtime.version`,TMP_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,TMP_SERVICE_NAME=`service.name`,TMP_SERVICE_NAMESPACE=`service.namespace`,TMP_SERVICE_INSTANCE_ID=`service.instance.id`,TMP_SERVICE_VERSION=`service.version`,TMP_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,TMP_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TMP_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,TMP_TELEMETRY_AUTO_VERSION=`telemetry.auto.version`,TMP_WEBENGINE_NAME=`webengine.name`,TMP_WEBENGINE_VERSION=`webengine.version`,TMP_WEBENGINE_DESCRIPTION=`webengine.description`,SEMRESATTRS_CLOUD_PROVIDER=TMP_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID=TMP_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION=TMP_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE=TMP_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM=TMP_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN=TMP_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN=TMP_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE=TMP_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN=TMP_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY=TMP_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION=TMP_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN=TMP_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES=TMP_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS=TMP_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES=TMP_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS=TMP_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME=TMP_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID=TMP_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME=TMP_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME=TMP_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG=TMP_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT=TMP_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID=TMP_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER=TMP_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME=TMP_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME=TMP_FAAS_NAME,SEMRESATTRS_FAAS_ID=TMP_FAAS_ID,SEMRESATTRS_FAAS_VERSION=TMP_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE=TMP_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY=TMP_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID=TMP_HOST_ID,SEMRESATTRS_HOST_NAME=TMP_HOST_NAME,SEMRESATTRS_HOST_TYPE=TMP_HOST_TYPE,SEMRESATTRS_HOST_ARCH=TMP_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME=TMP_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID=TMP_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION=TMP_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME=TMP_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME=TMP_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID=TMP_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME=TMP_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID=TMP_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME=TMP_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME=TMP_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID=TMP_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME=TMP_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID=TMP_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME=TMP_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID=TMP_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME=TMP_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID=TMP_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME=TMP_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID=TMP_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME=TMP_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID=TMP_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME=TMP_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE=TMP_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION=TMP_OS_DESCRIPTION,SEMRESATTRS_OS_NAME=TMP_OS_NAME,SEMRESATTRS_OS_VERSION=TMP_OS_VERSION,SEMRESATTRS_PROCESS_PID=TMP_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME=TMP_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH=TMP_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND=TMP_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE=TMP_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS=TMP_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER=TMP_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION=TMP_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION=TMP_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME=TMP_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE=TMP_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID=TMP_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION=TMP_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION=TMP_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME=TMP_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION=TMP_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION=TMP_WEBENGINE_DESCRIPTION,SemanticResourceAttributes=createConstMap([TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION]),TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_CLOUDPROVIDERVALUES_AWS=`aws`,TMP_CLOUDPROVIDERVALUES_AZURE=`azure`,TMP_CLOUDPROVIDERVALUES_GCP=`gcp`,CLOUDPROVIDERVALUES_ALIBABA_CLOUD=TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AZURE=TMP_CLOUDPROVIDERVALUES_AZURE,CloudProviderValues=createConstMap([TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP]),TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=`alibaba_cloud_ecs`,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=`alibaba_cloud_fc`,TMP_CLOUDPLATFORMVALUES_AWS_EC2=`aws_ec2`,TMP_CLOUDPLATFORMVALUES_AWS_ECS=`aws_ecs`,TMP_CLOUDPLATFORMVALUES_AWS_EKS=`aws_eks`,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA=`aws_lambda`,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=`aws_elastic_beanstalk`,TMP_CLOUDPLATFORMVALUES_AZURE_VM=`azure_vm`,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=`azure_container_instances`,TMP_CLOUDPLATFORMVALUES_AZURE_AKS=`azure_aks`,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=`azure_functions`,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=`azure_app_service`,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=`gcp_compute_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=`gcp_cloud_run`,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=`gcp_kubernetes_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=`gcp_cloud_functions`,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE=`gcp_app_engine`,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2=TMP_CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS=TMP_CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS=TMP_CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA=TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM=TMP_CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS=TMP_CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues=createConstMap([TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE]),TMP_AWSECSLAUNCHTYPEVALUES_EC2=`ec2`,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE=`fargate`,AWSECSLAUNCHTYPEVALUES_FARGATE=TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues=createConstMap([TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]),TMP_HOSTARCHVALUES_AMD64=`amd64`,TMP_HOSTARCHVALUES_ARM32=`arm32`,TMP_HOSTARCHVALUES_ARM64=`arm64`,TMP_HOSTARCHVALUES_IA64=`ia64`,TMP_HOSTARCHVALUES_PPC32=`ppc32`,TMP_HOSTARCHVALUES_PPC64=`ppc64`,TMP_HOSTARCHVALUES_X86=`x86`,HOSTARCHVALUES_AMD64=TMP_HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32=TMP_HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64=TMP_HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64=TMP_HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32=TMP_HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64=TMP_HOSTARCHVALUES_PPC64,HostArchValues=createConstMap([TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86]),TMP_OSTYPEVALUES_WINDOWS=`windows`,TMP_OSTYPEVALUES_LINUX=`linux`,TMP_OSTYPEVALUES_DARWIN=`darwin`,TMP_OSTYPEVALUES_FREEBSD=`freebsd`,TMP_OSTYPEVALUES_NETBSD=`netbsd`,TMP_OSTYPEVALUES_OPENBSD=`openbsd`,TMP_OSTYPEVALUES_DRAGONFLYBSD=`dragonflybsd`,TMP_OSTYPEVALUES_HPUX=`hpux`,TMP_OSTYPEVALUES_AIX=`aix`,TMP_OSTYPEVALUES_SOLARIS=`solaris`,TMP_OSTYPEVALUES_Z_OS=`z_os`,OSTYPEVALUES_WINDOWS=TMP_OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX=TMP_OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN=TMP_OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD=TMP_OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD=TMP_OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD=TMP_OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD=TMP_OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX=TMP_OSTYPEVALUES_HPUX,OSTYPEVALUES_SOLARIS=TMP_OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS=TMP_OSTYPEVALUES_Z_OS,OsTypeValues=createConstMap([TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS]),TMP_TELEMETRYSDKLANGUAGEVALUES_CPP=`cpp`,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET=`dotnet`,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG=`erlang`,TMP_TELEMETRYSDKLANGUAGEVALUES_GO=`go`,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA=`java`,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS=`nodejs`,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP=`php`,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON=`python`,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY=`ruby`,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS=`webjs`,TELEMETRYSDKLANGUAGEVALUES_DOTNET=TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG=TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_JAVA=TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS=TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PYTHON=TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY=TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues=createConstMap([TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS])})),init_resource=__esmMin((()=>{init_SemanticResourceAttributes()})),ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME,DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL,ATTR_DOTNET_GC_HEAP_GENERATION,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH,DOTNET_GC_HEAP_GENERATION_VALUE_POH,ATTR_ERROR_TYPE,ERROR_TYPE_VALUE_OTHER,ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD,HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET,HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT,HTTP_REQUEST_METHOD_VALUE_TRACE,ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE,JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP,ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE,JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW,JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING,ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT,NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP,NETWORK_TRANSPORT_VALUE_UDP,NETWORK_TRANSPORT_VALUE_UNIX,ATTR_NETWORK_TYPE,NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6,ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE,OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK,ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,ATTR_SIGNALR_TRANSPORT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,ATTR_TELEMETRY_SDK_LANGUAGE,TELEMETRY_SDK_LANGUAGE_VALUE_CPP,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT,ATTR_URL_FULL,ATTR_URL_PATH,ATTR_URL_QUERY,ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL,init_stable_attributes=__esmMin((()=>{ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT=`aspnetcore.diagnostics.exception.result`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED=`aborted`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED=`handled`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED=`skipped`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED=`unhandled`,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE=`aspnetcore.diagnostics.handler.type`,ATTR_ASPNETCORE_RATE_LIMITING_POLICY=`aspnetcore.rate_limiting.policy`,ATTR_ASPNETCORE_RATE_LIMITING_RESULT=`aspnetcore.rate_limiting.result`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED=`acquired`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER=`endpoint_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER=`global_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED=`request_canceled`,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED=`aspnetcore.request.is_unhandled`,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK=`aspnetcore.routing.is_fallback`,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS=`aspnetcore.routing.match_status`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE=`failure`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS=`success`,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED=`aspnetcore.user.is_authenticated`,ATTR_CLIENT_ADDRESS=`client.address`,ATTR_CLIENT_PORT=`client.port`,ATTR_CODE_COLUMN_NUMBER=`code.column.number`,ATTR_CODE_FILE_PATH=`code.file.path`,ATTR_CODE_FUNCTION_NAME=`code.function.name`,ATTR_CODE_LINE_NUMBER=`code.line.number`,ATTR_CODE_STACKTRACE=`code.stacktrace`,ATTR_DB_COLLECTION_NAME=`db.collection.name`,ATTR_DB_NAMESPACE=`db.namespace`,ATTR_DB_OPERATION_BATCH_SIZE=`db.operation.batch.size`,ATTR_DB_OPERATION_NAME=`db.operation.name`,ATTR_DB_QUERY_SUMMARY=`db.query.summary`,ATTR_DB_QUERY_TEXT=`db.query.text`,ATTR_DB_RESPONSE_STATUS_CODE=`db.response.status_code`,ATTR_DB_STORED_PROCEDURE_NAME=`db.stored_procedure.name`,ATTR_DB_SYSTEM_NAME=`db.system.name`,DB_SYSTEM_NAME_VALUE_MARIADB=`mariadb`,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER=`microsoft.sql_server`,DB_SYSTEM_NAME_VALUE_MYSQL=`mysql`,DB_SYSTEM_NAME_VALUE_POSTGRESQL=`postgresql`,ATTR_DOTNET_GC_HEAP_GENERATION=`dotnet.gc.heap.generation`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0=`gen0`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1=`gen1`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2=`gen2`,ATTR_ERROR_TYPE=`error.type`,ERROR_TYPE_VALUE_OTHER=`_OTHER`,ATTR_EXCEPTION_ESCAPED=`exception.escaped`,ATTR_EXCEPTION_MESSAGE=`exception.message`,ATTR_EXCEPTION_STACKTRACE=`exception.stacktrace`,ATTR_EXCEPTION_TYPE=`exception.type`,ATTR_HTTP_REQUEST_HEADER=e=>`http.request.header.${e}`,ATTR_HTTP_REQUEST_METHOD=`http.request.method`,HTTP_REQUEST_METHOD_VALUE_OTHER=`_OTHER`,HTTP_REQUEST_METHOD_VALUE_CONNECT=`CONNECT`,HTTP_REQUEST_METHOD_VALUE_DELETE=`DELETE`,HTTP_REQUEST_METHOD_VALUE_HEAD=`HEAD`,HTTP_REQUEST_METHOD_VALUE_OPTIONS=`OPTIONS`,HTTP_REQUEST_METHOD_VALUE_PATCH=`PATCH`,HTTP_REQUEST_METHOD_VALUE_POST=`POST`,HTTP_REQUEST_METHOD_VALUE_TRACE=`TRACE`,ATTR_HTTP_REQUEST_METHOD_ORIGINAL=`http.request.method_original`,ATTR_HTTP_REQUEST_RESEND_COUNT=`http.request.resend_count`,ATTR_HTTP_RESPONSE_HEADER=e=>`http.response.header.${e}`,ATTR_HTTP_RESPONSE_STATUS_CODE=`http.response.status_code`,ATTR_HTTP_ROUTE=`http.route`,ATTR_JVM_GC_ACTION=`jvm.gc.action`,ATTR_JVM_GC_NAME=`jvm.gc.name`,ATTR_JVM_MEMORY_POOL_NAME=`jvm.memory.pool.name`,ATTR_JVM_MEMORY_TYPE=`jvm.memory.type`,JVM_MEMORY_TYPE_VALUE_HEAP=`heap`,JVM_MEMORY_TYPE_VALUE_NON_HEAP=`non_heap`,ATTR_JVM_THREAD_DAEMON=`jvm.thread.daemon`,ATTR_JVM_THREAD_STATE=`jvm.thread.state`,JVM_THREAD_STATE_VALUE_BLOCKED=`blocked`,JVM_THREAD_STATE_VALUE_RUNNABLE=`runnable`,JVM_THREAD_STATE_VALUE_TERMINATED=`terminated`,JVM_THREAD_STATE_VALUE_TIMED_WAITING=`timed_waiting`,JVM_THREAD_STATE_VALUE_WAITING=`waiting`,ATTR_NETWORK_LOCAL_ADDRESS=`network.local.address`,ATTR_NETWORK_LOCAL_PORT=`network.local.port`,ATTR_NETWORK_PEER_ADDRESS=`network.peer.address`,ATTR_NETWORK_PEER_PORT=`network.peer.port`,ATTR_NETWORK_PROTOCOL_NAME=`network.protocol.name`,ATTR_NETWORK_PROTOCOL_VERSION=`network.protocol.version`,ATTR_NETWORK_TRANSPORT=`network.transport`,NETWORK_TRANSPORT_VALUE_PIPE=`pipe`,NETWORK_TRANSPORT_VALUE_QUIC=`quic`,NETWORK_TRANSPORT_VALUE_UNIX=`unix`,ATTR_NETWORK_TYPE=`network.type`,NETWORK_TYPE_VALUE_IPV4=`ipv4`,NETWORK_TYPE_VALUE_IPV6=`ipv6`,ATTR_OTEL_SCOPE_NAME=`otel.scope.name`,ATTR_OTEL_SCOPE_VERSION=`otel.scope.version`,ATTR_OTEL_STATUS_CODE=`otel.status_code`,OTEL_STATUS_CODE_VALUE_ERROR=`ERROR`,ATTR_OTEL_STATUS_DESCRIPTION=`otel.status_description`,ATTR_SERVER_ADDRESS=`server.address`,ATTR_SERVER_PORT=`server.port`,ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,ATTR_SERVICE_NAME=`service.name`,ATTR_SERVICE_NAMESPACE=`service.namespace`,ATTR_SERVICE_VERSION=`service.version`,ATTR_SIGNALR_CONNECTION_STATUS=`signalr.connection.status`,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN=`app_shutdown`,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE=`normal_closure`,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT=`timeout`,ATTR_SIGNALR_TRANSPORT=`signalr.transport`,SIGNALR_TRANSPORT_VALUE_LONG_POLLING=`long_polling`,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS=`server_sent_events`,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS=`web_sockets`,ATTR_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET=`dotnet`,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG=`erlang`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA=`java`,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS=`nodejs`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON=`python`,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY=`ruby`,TELEMETRY_SDK_LANGUAGE_VALUE_RUST=`rust`,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT=`swift`,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS=`webjs`,ATTR_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,ATTR_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,ATTR_URL_FRAGMENT=`url.fragment`,ATTR_URL_FULL=`url.full`,ATTR_URL_PATH=`url.path`,ATTR_URL_QUERY=`url.query`,ATTR_URL_SCHEME=`url.scheme`,ATTR_USER_AGENT_ORIGINAL=`user_agent.original`})),METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION,init_stable_metrics=__esmMin((()=>{METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS=`aspnetcore.diagnostics.exceptions`,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES=`aspnetcore.rate_limiting.active_request_leases`,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS=`aspnetcore.rate_limiting.queued_requests`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE=`aspnetcore.rate_limiting.request.time_in_queue`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION=`aspnetcore.rate_limiting.request_lease.duration`,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS=`aspnetcore.rate_limiting.requests`,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS=`aspnetcore.routing.match_attempts`,METRIC_DB_CLIENT_OPERATION_DURATION=`db.client.operation.duration`,METRIC_DOTNET_ASSEMBLY_COUNT=`dotnet.assembly.count`,METRIC_DOTNET_EXCEPTIONS=`dotnet.exceptions`,METRIC_DOTNET_GC_COLLECTIONS=`dotnet.gc.collections`,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED=`dotnet.gc.heap.total_allocated`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE=`dotnet.gc.last_collection.heap.fragmentation.size`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE=`dotnet.gc.last_collection.heap.size`,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE=`dotnet.gc.last_collection.memory.committed_size`,METRIC_DOTNET_GC_PAUSE_TIME=`dotnet.gc.pause.time`,METRIC_DOTNET_JIT_COMPILATION_TIME=`dotnet.jit.compilation.time`,METRIC_DOTNET_JIT_COMPILED_IL_SIZE=`dotnet.jit.compiled_il.size`,METRIC_DOTNET_JIT_COMPILED_METHODS=`dotnet.jit.compiled_methods`,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS=`dotnet.monitor.lock_contentions`,METRIC_DOTNET_PROCESS_CPU_COUNT=`dotnet.process.cpu.count`,METRIC_DOTNET_PROCESS_CPU_TIME=`dotnet.process.cpu.time`,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET=`dotnet.process.memory.working_set`,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH=`dotnet.thread_pool.queue.length`,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT=`dotnet.thread_pool.thread.count`,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT=`dotnet.thread_pool.work_item.count`,METRIC_DOTNET_TIMER_COUNT=`dotnet.timer.count`,METRIC_HTTP_CLIENT_REQUEST_DURATION=`http.client.request.duration`,METRIC_HTTP_SERVER_REQUEST_DURATION=`http.server.request.duration`,METRIC_JVM_CLASS_COUNT=`jvm.class.count`,METRIC_JVM_CLASS_LOADED=`jvm.class.loaded`,METRIC_JVM_CLASS_UNLOADED=`jvm.class.unloaded`,METRIC_JVM_CPU_COUNT=`jvm.cpu.count`,METRIC_JVM_CPU_RECENT_UTILIZATION=`jvm.cpu.recent_utilization`,METRIC_JVM_CPU_TIME=`jvm.cpu.time`,METRIC_JVM_GC_DURATION=`jvm.gc.duration`,METRIC_JVM_MEMORY_COMMITTED=`jvm.memory.committed`,METRIC_JVM_MEMORY_LIMIT=`jvm.memory.limit`,METRIC_JVM_MEMORY_USED=`jvm.memory.used`,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC=`jvm.memory.used_after_last_gc`,METRIC_JVM_THREAD_COUNT=`jvm.thread.count`,METRIC_KESTREL_ACTIVE_CONNECTIONS=`kestrel.active_connections`,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES=`kestrel.active_tls_handshakes`,METRIC_KESTREL_CONNECTION_DURATION=`kestrel.connection.duration`,METRIC_KESTREL_QUEUED_CONNECTIONS=`kestrel.queued_connections`,METRIC_KESTREL_QUEUED_REQUESTS=`kestrel.queued_requests`,METRIC_KESTREL_REJECTED_CONNECTIONS=`kestrel.rejected_connections`,METRIC_KESTREL_TLS_HANDSHAKE_DURATION=`kestrel.tls_handshake.duration`,METRIC_KESTREL_UPGRADED_CONNECTIONS=`kestrel.upgraded_connections`,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS=`signalr.server.active_connections`,METRIC_SIGNALR_SERVER_CONNECTION_DURATION=`signalr.server.connection.duration`})),EVENT_EXCEPTION,init_stable_events=__esmMin((()=>{EVENT_EXCEPTION=`exception`})),esm_exports$1=__exportAll({ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED:()=>ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS:()=>ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT:()=>ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER:()=>ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH:()=>ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME:()=>ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER:()=>ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE:()=>ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME:()=>ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE:()=>ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE:()=>ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME:()=>ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY:()=>ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT:()=>ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE:()=>ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME:()=>ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME:()=>ATTR_DB_SYSTEM_NAME,ATTR_DOTNET_GC_HEAP_GENERATION:()=>ATTR_DOTNET_GC_HEAP_GENERATION,ATTR_ERROR_TYPE:()=>ATTR_ERROR_TYPE,ATTR_EXCEPTION_ESCAPED:()=>ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE:()=>ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE:()=>ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE:()=>ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER:()=>ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD:()=>ATTR_HTTP_REQUEST_METHOD,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER:()=>ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE:()=>ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION:()=>ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME:()=>ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME:()=>ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE:()=>ATTR_JVM_MEMORY_TYPE,ATTR_JVM_THREAD_DAEMON:()=>ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE:()=>ATTR_JVM_THREAD_STATE,ATTR_NETWORK_LOCAL_ADDRESS:()=>ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT:()=>ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS:()=>ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT:()=>ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME:()=>ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION:()=>ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT:()=>ATTR_NETWORK_TRANSPORT,ATTR_NETWORK_TYPE:()=>ATTR_NETWORK_TYPE,ATTR_OTEL_SCOPE_NAME:()=>ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION:()=>ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE:()=>ATTR_OTEL_STATUS_CODE,ATTR_OTEL_STATUS_DESCRIPTION:()=>ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS:()=>ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT:()=>ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID:()=>ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME:()=>ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE:()=>ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION:()=>ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS:()=>ATTR_SIGNALR_CONNECTION_STATUS,ATTR_SIGNALR_TRANSPORT:()=>ATTR_SIGNALR_TRANSPORT,ATTR_TELEMETRY_SDK_LANGUAGE:()=>ATTR_TELEMETRY_SDK_LANGUAGE,ATTR_TELEMETRY_SDK_NAME:()=>ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION:()=>ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT:()=>ATTR_URL_FRAGMENT,ATTR_URL_FULL:()=>ATTR_URL_FULL,ATTR_URL_PATH:()=>ATTR_URL_PATH,ATTR_URL_QUERY:()=>ATTR_URL_QUERY,ATTR_URL_SCHEME:()=>ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL:()=>ATTR_USER_AGENT_ORIGINAL,AWSECSLAUNCHTYPEVALUES_EC2:()=>`ec2`,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues:()=>AwsEcsLaunchtypeValues,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2:()=>CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS:()=>CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS:()=>CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AZURE_AKS:()=>CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_VM:()=>CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS:()=>`aws`,CLOUDPROVIDERVALUES_AZURE:()=>CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP:()=>`gcp`,CloudPlatformValues:()=>CloudPlatformValues,CloudProviderValues:()=>CloudProviderValues,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>`all`,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>`any`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>`one`,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>`two`,DBSYSTEMVALUES_ADABAS:()=>DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_CACHE:()=>DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_CASSANDRA:()=>DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_CLOUDSCAPE:()=>DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_COCKROACHDB:()=>DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_COLDFUSION:()=>DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_COSMOSDB:()=>DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_COUCHBASE:()=>DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB:()=>DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_DB2:()=>`db2`,DBSYSTEMVALUES_DERBY:()=>DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_DYNAMODB:()=>DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_EDB:()=>`edb`,DBSYSTEMVALUES_ELASTICSEARCH:()=>DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_FILEMAKER:()=>DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_FIREBIRD:()=>DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_FIRSTSQL:()=>DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_GEODE:()=>DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_H2:()=>`h2`,DBSYSTEMVALUES_HANADB:()=>DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_HBASE:()=>DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_HIVE:()=>DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_HSQLDB:()=>DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_INFORMIX:()=>DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INGRES:()=>DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_INSTANTDB:()=>DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE:()=>DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB:()=>DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_MAXDB:()=>DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_MEMCACHED:()=>DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_MONGODB:()=>DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_MSSQL:()=>DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL:()=>DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_NEO4J:()=>DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_NETEZZA:()=>DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_ORACLE:()=>DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_OTHER_SQL:()=>DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_PERVASIVE:()=>DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE:()=>DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_POSTGRESQL:()=>DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_PROGRESS:()=>DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_REDIS:()=>DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_REDSHIFT:()=>DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_SQLITE:()=>DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE:()=>DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA:()=>DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA:()=>DBSYSTEMVALUES_VERTICA,DB_SYSTEM_NAME_VALUE_MARIADB:()=>DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER:()=>DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL:()=>DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL:()=>DB_SYSTEM_NAME_VALUE_POSTGRESQL,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH:()=>`loh`,DOTNET_GC_HEAP_GENERATION_VALUE_POH:()=>`poh`,DbCassandraConsistencyLevelValues:()=>DbCassandraConsistencyLevelValues,DbSystemValues:()=>DbSystemValues,ERROR_TYPE_VALUE_OTHER:()=>ERROR_TYPE_VALUE_OTHER,EVENT_EXCEPTION:()=>EVENT_EXCEPTION,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>FAASDOCUMENTOPERATIONVALUES_INSERT,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS:()=>`aws`,FAASINVOKEDPROVIDERVALUES_AZURE:()=>FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP:()=>`gcp`,FAASTRIGGERVALUES_DATASOURCE:()=>FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP:()=>FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_OTHER:()=>FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_PUBSUB:()=>FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER:()=>FAASTRIGGERVALUES_TIMER,FaasDocumentOperationValues:()=>FaasDocumentOperationValues,FaasInvokedProviderValues:()=>FaasInvokedProviderValues,FaasTriggerValues:()=>FaasTriggerValues,HOSTARCHVALUES_AMD64:()=>HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32:()=>HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64:()=>HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64:()=>HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32:()=>HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64:()=>HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86:()=>`x86`,HTTPFLAVORVALUES_HTTP_1_0:()=>`1.0`,HTTPFLAVORVALUES_HTTP_1_1:()=>`1.1`,HTTPFLAVORVALUES_HTTP_2_0:()=>`2.0`,HTTPFLAVORVALUES_QUIC:()=>HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_SPDY:()=>HTTPFLAVORVALUES_SPDY,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET:()=>`GET`,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST:()=>HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT:()=>`PUT`,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>HTTP_REQUEST_METHOD_VALUE_TRACE,HostArchValues:()=>HostArchValues,HttpFlavorValues:()=>HttpFlavorValues,JVM_MEMORY_TYPE_VALUE_HEAP:()=>JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>JVM_MEMORY_TYPE_VALUE_NON_HEAP,JVM_THREAD_STATE_VALUE_BLOCKED:()=>JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW:()=>`new`,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED:()=>JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING:()=>JVM_THREAD_STATE_VALUE_WAITING,MESSAGETYPEVALUES_RECEIVED:()=>MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT:()=>MESSAGETYPEVALUES_SENT,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGOPERATIONVALUES_PROCESS:()=>MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE:()=>MESSAGINGOPERATIONVALUES_RECEIVE,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION:()=>METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT:()=>METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS:()=>METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS:()=>METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED:()=>METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME:()=>METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME:()=>METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE:()=>METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS:()=>METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS:()=>METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT:()=>METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME:()=>METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET:()=>METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH:()=>METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT:()=>METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT:()=>METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT:()=>METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT:()=>METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED:()=>METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED:()=>METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT:()=>METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME:()=>METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION:()=>METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED:()=>METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT:()=>METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED:()=>METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT:()=>METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION:()=>METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS:()=>METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>METRIC_SIGNALR_SERVER_CONNECTION_DURATION,MessageTypeValues:()=>MessageTypeValues,MessagingDestinationKindValues:()=>MessagingDestinationKindValues,MessagingOperationValues:()=>MessagingOperationValues,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>`gsm`,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>`lte`,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>`nr`,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>NETHOSTCONNECTIONTYPEVALUES_WIRED,NETTRANSPORTVALUES_INPROC:()=>NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_IP:()=>`ip`,NETTRANSPORTVALUES_IP_TCP:()=>NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP:()=>NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_OTHER:()=>NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_PIPE:()=>NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_UNIX:()=>NETTRANSPORTVALUES_UNIX,NETWORK_TRANSPORT_VALUE_PIPE:()=>NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC:()=>NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP:()=>`tcp`,NETWORK_TRANSPORT_VALUE_UDP:()=>`udp`,NETWORK_TRANSPORT_VALUE_UNIX:()=>NETWORK_TRANSPORT_VALUE_UNIX,NETWORK_TYPE_VALUE_IPV4:()=>NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6:()=>NETWORK_TYPE_VALUE_IPV6,NetHostConnectionSubtypeValues:()=>NetHostConnectionSubtypeValues,NetHostConnectionTypeValues:()=>NetHostConnectionTypeValues,NetTransportValues:()=>NetTransportValues,OSTYPEVALUES_AIX:()=>`aix`,OSTYPEVALUES_DARWIN:()=>OSTYPEVALUES_DARWIN,OSTYPEVALUES_DRAGONFLYBSD:()=>OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_FREEBSD:()=>OSTYPEVALUES_FREEBSD,OSTYPEVALUES_HPUX:()=>OSTYPEVALUES_HPUX,OSTYPEVALUES_LINUX:()=>OSTYPEVALUES_LINUX,OSTYPEVALUES_NETBSD:()=>OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD:()=>OSTYPEVALUES_OPENBSD,OSTYPEVALUES_SOLARIS:()=>OSTYPEVALUES_SOLARIS,OSTYPEVALUES_WINDOWS:()=>OSTYPEVALUES_WINDOWS,OSTYPEVALUES_Z_OS:()=>OSTYPEVALUES_Z_OS,OTEL_STATUS_CODE_VALUE_ERROR:()=>OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK:()=>`OK`,OsTypeValues:()=>OsTypeValues,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>10,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>6,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>1,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>15,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>4,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>9,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>13,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>3,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>5,RPCGRPCSTATUSCODEVALUES_OK:()=>0,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>11,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>7,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>8,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>16,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>14,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>12,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>2,RpcGrpcStatusCodeValues:()=>RpcGrpcStatusCodeValues,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_COUNT:()=>SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_SELECT:()=>SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_CODE_FILEPATH:()=>SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_FUNCTION:()=>SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_LINENO:()=>SEMATTRS_CODE_LINENO,SEMATTRS_CODE_NAMESPACE:()=>SEMATTRS_CODE_NAMESPACE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_TABLE:()=>SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CONNECTION_STRING:()=>SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_HBASE_NAMESPACE:()=>SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_MONGODB_COLLECTION:()=>SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_NAME:()=>SEMATTRS_DB_NAME,SEMATTRS_DB_OPERATION:()=>SEMATTRS_DB_OPERATION,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_SQL_TABLE:()=>SEMATTRS_DB_SQL_TABLE,SEMATTRS_DB_STATEMENT:()=>SEMATTRS_DB_STATEMENT,SEMATTRS_DB_SYSTEM:()=>SEMATTRS_DB_SYSTEM,SEMATTRS_DB_USER:()=>SEMATTRS_DB_USER,SEMATTRS_ENDUSER_ID:()=>SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE:()=>SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE:()=>SEMATTRS_ENDUSER_SCOPE,SEMATTRS_EXCEPTION_ESCAPED:()=>SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_EXCEPTION_MESSAGE:()=>SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE:()=>SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_TYPE:()=>SEMATTRS_EXCEPTION_TYPE,SEMATTRS_FAAS_COLDSTART:()=>SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_CRON:()=>SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_NAME:()=>SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME:()=>SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_EXECUTION:()=>SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_INVOKED_NAME:()=>SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION:()=>SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_FAAS_TIME:()=>SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_TRIGGER:()=>SEMATTRS_FAAS_TRIGGER,SEMATTRS_HTTP_CLIENT_IP:()=>SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_HTTP_FLAVOR:()=>SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_HOST:()=>SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_METHOD:()=>SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_ROUTE:()=>SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_SCHEME:()=>SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_SERVER_NAME:()=>SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_STATUS_CODE:()=>SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_TARGET:()=>SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_URL:()=>SEMATTRS_HTTP_URL,SEMATTRS_HTTP_USER_AGENT:()=>SEMATTRS_HTTP_USER_AGENT,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_ID:()=>SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_TYPE:()=>SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_MESSAGING_CONSUMER_ID:()=>SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_DESTINATION:()=>SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_MESSAGING_MESSAGE_ID:()=>SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION:()=>SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_PROTOCOL:()=>SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_SYSTEM:()=>SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_URL:()=>SEMATTRS_MESSAGING_URL,SEMATTRS_NET_HOST_CARRIER_ICC:()=>SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_NET_HOST_CARRIER_MCC:()=>SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC:()=>SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_NAME:()=>SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_IP:()=>SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_NAME:()=>SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_PORT:()=>SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_PEER_IP:()=>SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_NAME:()=>SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_PEER_PORT:()=>SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_TRANSPORT:()=>SEMATTRS_NET_TRANSPORT,SEMATTRS_PEER_SERVICE:()=>SEMATTRS_PEER_SERVICE,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_VERSION:()=>SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_METHOD:()=>SEMATTRS_RPC_METHOD,SEMATTRS_RPC_SERVICE:()=>SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_SYSTEM:()=>SEMATTRS_RPC_SYSTEM,SEMATTRS_THREAD_ID:()=>SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME:()=>SEMATTRS_THREAD_NAME,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM:()=>SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_CLOUD_PROVIDER:()=>SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_REGION:()=>SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CONTAINER_ID:()=>SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_CONTAINER_NAME:()=>SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_RUNTIME:()=>SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID:()=>SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME:()=>SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_ID:()=>SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_INSTANCE:()=>SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY:()=>SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_FAAS_NAME:()=>SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_VERSION:()=>SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_HOST_ARCH:()=>SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_ID:()=>SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_IMAGE_ID:()=>SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_NAME:()=>SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_VERSION:()=>SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_HOST_NAME:()=>SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE:()=>SEMRESATTRS_HOST_TYPE,SEMRESATTRS_K8S_CLUSTER_NAME:()=>SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_CONTAINER_NAME:()=>SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_CRONJOB_NAME:()=>SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID:()=>SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID:()=>SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_JOB_NAME:()=>SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_JOB_UID:()=>SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_NODE_NAME:()=>SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID:()=>SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_POD_NAME:()=>SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_POD_UID:()=>SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_REPLICASET_NAME:()=>SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_REPLICASET_UID:()=>SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_STATEFULSET_UID:()=>SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_OS_DESCRIPTION:()=>SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME:()=>SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_TYPE:()=>SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_VERSION:()=>SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_COMMAND:()=>SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_OWNER:()=>SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_PID:()=>SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_NAME:()=>SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE:()=>SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_VERSION:()=>SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>SEMRESATTRS_WEBENGINE_DESCRIPTION,SEMRESATTRS_WEBENGINE_NAME:()=>SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION:()=>SEMRESATTRS_WEBENGINE_VERSION,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,SemanticAttributes:()=>SemanticAttributes,SemanticResourceAttributes:()=>SemanticResourceAttributes,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>`cpp`,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO:()=>`go`,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>`php`,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>`cpp`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>`go`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>`php`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,TelemetrySdkLanguageValues:()=>TelemetrySdkLanguageValues}),init_esm$1=__esmMin((()=>{init_trace(),init_resource(),init_stable_attributes(),init_stable_metrics(),init_stable_events()})),require_semconv$7=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$6(),n=(init_esm$1(),__toCommonJS(esm_exports$1)),r=require_semconv$7();e.SDK_INFO={[n.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[r.ATTR_PROCESS_RUNTIME_NAME]:`node`,[n.ATTR_TELEMETRY_SDK_LANGUAGE]:n.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[n.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_node$12=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=e.SDK_INFO=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$3();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var n=require_globalThis$3();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=require_sdk_info$3();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return r.SDK_INFO}}),e.otperformance=performance})),require_platform$11=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$12();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$11(),n=9,r=10**6,i=10**9;function a(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*r)]}e.millisToHrTime=a;function o(){return t.otperformance.timeOrigin}e.getTimeOrigin=o;function s(e){return g(a(t.otperformance.timeOrigin),a(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=s;function c(e){if(m(e))return e;if(typeof e==`number`)return e<t.otperformance.timeOrigin?s(e):a(e);if(e instanceof Date)return a(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=c;function l(e,t){let n=t[0]-e[0],r=t[1]-e[1];return r<0&&(--n,r+=i),[n,r]}e.hrTimeDuration=l;function u(e){let t=9,n=`${`0`.repeat(9)}${e[1]}Z`,r=n.substring(n.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,r)}e.hrTimeToTimeStamp=u;function d(e){return e[0]*i+e[1]}e.hrTimeToNanoseconds=d;function f(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=f;function p(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=p;function m(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=m;function h(e){return m(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=h;function g(e,t){let n=[e[0]+t[0],e[1]+t[1]];return n[1]>=i&&(n[1]-=i,n[0]+=1),n}e.addHrTimes=g})),require_timer_util$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){typeof e!=`number`&&e.unref()}e.unrefTimer=t})),require_ExportResult$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,n,r){for(let i of this._propagators)try{i.inject(e,n,r)}catch(e){t.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${e.message}`)}}extract(e,n,r){return this._propagators.reduce((e,i)=>{try{return i.extract(e,n,r)}catch(e){t.diag.warn(`Failed to extract with ${i.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,n=`[a-z]${t}{0,255}`,r=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,i=RegExp(`^(?:${n}|${r})$`),a=/^[ -~]{0,255}[!-~]$/,o=/,|=/;function s(e){return i.test(e)}e.validateKey=s;function c(e){return a.test(e)&&!o.test(e)}e.validateValue=c})),require_TraceState$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$3(),n=32,r=512,i=`,`,a=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,n)=>{let r=n.trim(),i=r.indexOf(`=`);if(i!==-1){let a=r.slice(0,i),o=r.slice(i+1,n.length);(0,t.validateKey)(a)&&(0,t.validateValue)(o)&&e.set(a,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$3(),r=require_TraceState$3();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let i=`00`,a=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function o(e){let t=a.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=o,e.W3CTraceContextPropagator=class{inject(r,i,a){let o=t.trace.getSpanContext(r);if(!o||(0,n.isTracingSuppressed)(r)||!(0,t.isSpanContextValid)(o))return;let s=`00-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||t.TraceFlags.NONE).toString(16)}`;a.set(i,e.TRACE_PARENT_HEADER,s),o.traceState&&a.set(i,e.TRACE_STATE_HEADER,o.traceState.serialize())}extract(n,i,a){let s=a.get(i,e.TRACE_PARENT_HEADER);if(!s)return n;let c=Array.isArray(s)?s[0]:s;if(typeof c!=`string`)return n;let l=o(c);if(!l)return n;l.isRemote=!0;let u=a.get(i,e.TRACE_STATE_HEADER);if(u){let e=Array.isArray(u)?u.join(`,`):u;l.traceState=new r.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(n,l)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function n(e,n){return e.setValue(t,n)}e.setRPCMetadata=n;function r(e){return e.deleteValue(t)}e.deleteRPCMetadata=r;function i(e){return e.getValue(t)}e.getRPCMetadata=i})),require_lodash_merge$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,n=`[object Null]`,r=`[object Undefined]`,i=Function.prototype.toString,a=i.call(Object),o=Object.getPrototypeOf,s=Object.prototype,c=s.hasOwnProperty,l=Symbol?Symbol.toStringTag:void 0,u=s.toString;function d(e){if(!f(e)||p(e)!==`[object Object]`)return!1;let t=o(e);if(t===null)return!0;let n=c.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&i.call(n)===a}e.isPlainObject=d;function f(e){return typeof e==`object`&&!!e}function p(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:l&&l in Object(e)?m(e):h(e)}function m(e){let t=c.call(e,l),n=e[l],r=!1;try{e[l]=void 0,r=!0}catch{}let i=u.call(e);return r&&(t?e[l]=n:delete e[l]),i}function h(e){return u.call(e)}})),require_merge$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$3(),n=20;function r(...e){let t=e.shift(),n=new WeakMap;for(;e.length>0;)t=a(t,e.shift(),0,n);return t}e.merge=r;function i(e){return s(e)?e.slice():e}function a(e,t,n=0,r){let f;if(!(n>20)){if(n++,u(e)||u(t)||c(t))f=i(t);else if(s(e)){if(f=e.slice(),s(t))for(let e=0,n=t.length;e<n;e++)f.push(i(t[e]));else if(l(t)){let e=Object.keys(t);for(let n=0,r=e.length;n<r;n++){let r=e[n];r===`__proto__`||r===`constructor`||r===`prototype`||(f[r]=i(t[r]))}}}else if(l(e))if(l(t)){if(!d(e,t))return t;f=Object.assign({},e);let i=Object.keys(t);for(let s=0,c=i.length;s<c;s++){let c=i[s];if(c===`__proto__`||c===`constructor`||c===`prototype`)continue;let d=t[c];if(u(d))d===void 0?delete f[c]:f[c]=d;else{let i=f[c],s=d;if(o(e,c,r)||o(t,c,r))delete f[c];else{if(l(i)&&l(s)){let n=r.get(i)||[],a=r.get(s)||[];n.push({obj:e,key:c}),a.push({obj:t,key:c}),r.set(i,n),r.set(s,a)}f[c]=a(f[c],d,n,r)}}}}else f=t;return f}}function o(e,t,n){let r=n.get(e[t])||[];for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i.key===t&&i.obj===e)return!0}return!1}function s(e){return Array.isArray(e)}function c(e){return typeof e==`function`}function l(e){return!u(e)&&!s(e)&&!c(e)&&typeof e==`object`}function u(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function d(e,n){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(n))}})),require_timeout$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function n(e,n){let r,i=new Promise(function(e,i){r=setTimeout(function(){i(new t(`Operation timed out.`))},n)});return Promise.race([e,i]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}e.callWithTimeout=n})),require_url$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function n(e,n){if(!n)return!1;for(let r of n)if(t(e,r))return!0;return!1}e.isUrlIgnored=n})),require_promise$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$3();e.BindOnceFuture=class{_isCalled=!1;_deferred=new t.Deferred;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function r(e){return e==null?void 0:n[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(n)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=r})),require_exporter$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$3();function r(e,r){return new Promise(i=>{t.context.with((0,n.suppressTracing)(t.context.active()),()=>{e.export(r,i)})})}e._export=r})),require_src$14=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.unrefTimer=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$3();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=require_anchored_clock$3();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=require_attributes$3();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=require_global_error_handler$3();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=require_logging_error_handler$3();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=require_time$3();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return o.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return o.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return o.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return o.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return o.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return o.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return o.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return o.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return o.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return o.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return o.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return o.timeInputToHrTime}});var s=require_timer_util$3();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return s.unrefTimer}});var c=require_ExportResult$3();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return c.ExportResultCode}});var l=require_utils$14();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return l.parseKeyPairsIntoRecord}});var u=require_platform$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return u.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return u._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return u.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return u.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return u.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return u.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return u.otperformance}});var d=require_composite$3();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return d.CompositePropagator}});var f=require_W3CTraceContextPropagator$3();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return f.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return f.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return f.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return f.parseTraceParent}});var p=require_rpc_metadata$3();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return p.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return p.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return p.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return p.setRPCMetadata}});var m=require_suppress_tracing$3();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return m.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return m.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return m.unsuppressTracing}});var h=require_TraceState$3();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return h.TraceState}});var g=require_merge$3();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return g.merge}});var _=require_timeout$3();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return _.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return _.callWithTimeout}});var v=require_url$3();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return v.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return v.urlMatches}});var y=require_callback$3();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return y.BindOnceFuture}});var b=require_configuration$3();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return b.diagLogLevelFromString}}),e.internal={_export:require_exporter$3()._export}})),require_suppress_tracing$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function n(e){return e.setValue(t,!0)}e.suppressTracing=n;function r(e){return e.deleteValue(t)}e.unsuppressTracing=r;function i(e){return e.getValue(t)===!0}e.isTracingSuppressed=i})),require_constants$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$13=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_constants$3();function r(e){return e.reduce((e,t)=>{let r=`${e}${e===``?``:n.BAGGAGE_ITEMS_SEPARATOR}${t}`;return r.length>n.BAGGAGE_MAX_TOTAL_LENGTH?e:r},``)}e.serializeKeyPairs=r;function i(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(r+=n.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}e.getKeyPairs=i;function a(e){let r=e.split(n.BAGGAGE_PROPERTIES_SEPARATOR);if(r.length<=0)return;let i=r.shift();if(!i)return;let a=i.indexOf(n.BAGGAGE_KEY_PAIR_SEPARATOR);if(a<=0)return;let o=decodeURIComponent(i.substring(0,a).trim()),s=decodeURIComponent(i.substring(a+1).trim()),c;return r.length>0&&(c=(0,t.baggageEntryMetadataFromString)(r.join(n.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:c}}e.parsePairKeyValue=a;function o(e){let t={};return typeof e==`string`&&e.length>0&&e.split(n.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let n=a(e);n!==void 0&&n.value.length>0&&(t[n.key]=n.value)}),t}e.parseKeyPairsIntoRecord=o})),require_W3CBaggagePropagator$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$2(),r=require_constants$3(),i=require_utils$13();e.W3CBaggagePropagator=class{inject(e,a,o){let s=t.propagation.getBaggage(e);if(!s||(0,n.isTracingSuppressed)(e))return;let c=(0,i.getKeyPairs)(s).filter(e=>e.length<=r.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,r.BAGGAGE_MAX_NAME_VALUE_PAIRS),l=(0,i.serializeKeyPairs)(c);l.length>0&&o.set(a,r.BAGGAGE_HEADER,l)}extract(e,n,a){let o=a.get(n,r.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(r.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let c={};return s.length===0||(s.split(r.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,i.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),c[t.key]=e}}),Object.entries(c).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(c))}fields(){return[r.BAGGAGE_HEADER]}}})),require_anchored_clock$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function n(e){let n={};if(typeof e!=`object`||!e)return n;for(let[a,o]of Object.entries(e)){if(!r(a)){t.diag.warn(`Invalid attribute key: ${a}`);continue}if(!i(o)){t.diag.warn(`Invalid attribute value set for key: ${a}`);continue}Array.isArray(o)?n[a]=o.slice():n[a]=o}return n}e.sanitizeAttributes=n;function r(e){return typeof e==`string`&&e.length>0}e.isAttributeKey=r;function i(e){return e==null?!0:Array.isArray(e)?a(e):o(e)}e.isAttributeValue=i;function a(e){let t;for(let n of e)if(n!=null){if(!t){if(o(n)){t=typeof n;continue}return!1}if(typeof n!==t)return!1}return!0}function o(e){switch(typeof e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function n(){return e=>{t.diag.error(r(e))}}e.loggingErrorHandler=n;function r(e){return typeof e==`string`?e:JSON.stringify(i(e))}function i(e){let t={},n=e;for(;n!==null;)Object.getOwnPropertyNames(n).forEach(e=>{if(t[e])return;let r=n[e];r&&(t[e]=String(r))}),n=Object.getPrototypeOf(n);return t}})),require_global_error_handler$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$2().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),require_environment$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=__require$1(`util`);function r(e){let r=process.env[e];if(r==null||r.trim()===``)return;let i=Number(r);if(isNaN(i)){t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected a number, using defaults`);return}return i}e.getNumberFromEnv=r;function i(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=i;function a(e){let r=process.env[e]?.trim().toLowerCase();return r==null||r===``?!1:r===`true`?!0:(r===`false`||t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=a;function o(e){return i(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=o})),require_globalThis$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),require_performance$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=__require$1(`perf_hooks`).performance})),require_version$5=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),require_semconv$6=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$5(),n=(init_esm$1(),__toCommonJS(esm_exports$1)),r=require_semconv$6();e.SDK_INFO={[n.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[r.ATTR_PROCESS_RUNTIME_NAME]:`node`,[n.ATTR_TELEMETRY_SDK_LANGUAGE]:n.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[n.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_timer_util$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),require_node$11=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=e.SDK_INFO=e.otperformance=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$2();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var n=require_globalThis$2();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=require_performance$2();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return r.otperformance}});var i=require_sdk_info$2();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return i.SDK_INFO}});var a=require_timer_util$2();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return a.unrefTimer}})})),require_platform$10=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.unrefTimer=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return t.unrefTimer}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$10(),n=9,r=10**6,i=10**9;function a(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*r)]}e.millisToHrTime=a;function o(){let e=t.otperformance.timeOrigin;if(typeof e!=`number`){let n=t.otperformance;e=n.timing&&n.timing.fetchStart}return e}e.getTimeOrigin=o;function s(e){return g(a(o()),a(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=s;function c(e){if(m(e))return e;if(typeof e==`number`)return e<o()?s(e):a(e);if(e instanceof Date)return a(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=c;function l(e,t){let n=t[0]-e[0],r=t[1]-e[1];return r<0&&(--n,r+=i),[n,r]}e.hrTimeDuration=l;function u(e){let t=9,n=`${`0`.repeat(9)}${e[1]}Z`,r=n.substring(n.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,r)}e.hrTimeToTimeStamp=u;function d(e){return e[0]*i+e[1]}e.hrTimeToNanoseconds=d;function f(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=f;function p(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=p;function m(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=m;function h(e){return m(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=h;function g(e,t){let n=[e[0]+t[0],e[1]+t[1]];return n[1]>=i&&(n[1]-=i,n[0]+=1),n}e.addHrTimes=g})),require_ExportResult$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,n,r){for(let i of this._propagators)try{i.inject(e,n,r)}catch(e){t.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${e.message}`)}}extract(e,n,r){return this._propagators.reduce((e,i)=>{try{return i.extract(e,n,r)}catch(e){t.diag.warn(`Failed to extract with ${i.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,n=`[a-z]${t}{0,255}`,r=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,i=RegExp(`^(?:${n}|${r})$`),a=/^[ -~]{0,255}[!-~]$/,o=/,|=/;function s(e){return i.test(e)}e.validateKey=s;function c(e){return a.test(e)&&!o.test(e)}e.validateValue=c})),require_TraceState$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$2(),n=32,r=512,i=`,`,a=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,n)=>{let r=n.trim(),i=r.indexOf(`=`);if(i!==-1){let a=r.slice(0,i),o=r.slice(i+1,n.length);(0,t.validateKey)(a)&&(0,t.validateValue)(o)&&e.set(a,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$2(),r=require_TraceState$2();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let i=`00`,a=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function o(e){let t=a.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=o,e.W3CTraceContextPropagator=class{inject(r,i,a){let o=t.trace.getSpanContext(r);if(!o||(0,n.isTracingSuppressed)(r)||!(0,t.isSpanContextValid)(o))return;let s=`00-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||t.TraceFlags.NONE).toString(16)}`;a.set(i,e.TRACE_PARENT_HEADER,s),o.traceState&&a.set(i,e.TRACE_STATE_HEADER,o.traceState.serialize())}extract(n,i,a){let s=a.get(i,e.TRACE_PARENT_HEADER);if(!s)return n;let c=Array.isArray(s)?s[0]:s;if(typeof c!=`string`)return n;let l=o(c);if(!l)return n;l.isRemote=!0;let u=a.get(i,e.TRACE_STATE_HEADER);if(u){let e=Array.isArray(u)?u.join(`,`):u;l.traceState=new r.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(n,l)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function n(e,n){return e.setValue(t,n)}e.setRPCMetadata=n;function r(e){return e.deleteValue(t)}e.deleteRPCMetadata=r;function i(e){return e.getValue(t)}e.getRPCMetadata=i})),require_lodash_merge$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,n=`[object Null]`,r=`[object Undefined]`,i=Function.prototype.toString,a=i.call(Object),o=Object.getPrototypeOf,s=Object.prototype,c=s.hasOwnProperty,l=Symbol?Symbol.toStringTag:void 0,u=s.toString;function d(e){if(!f(e)||p(e)!==`[object Object]`)return!1;let t=o(e);if(t===null)return!0;let n=c.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&i.call(n)===a}e.isPlainObject=d;function f(e){return typeof e==`object`&&!!e}function p(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:l&&l in Object(e)?m(e):h(e)}function m(e){let t=c.call(e,l),n=e[l],r=!1;try{e[l]=void 0,r=!0}catch{}let i=u.call(e);return r&&(t?e[l]=n:delete e[l]),i}function h(e){return u.call(e)}})),require_merge$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$2(),n=20;function r(...e){let t=e.shift(),n=new WeakMap;for(;e.length>0;)t=a(t,e.shift(),0,n);return t}e.merge=r;function i(e){return s(e)?e.slice():e}function a(e,t,n=0,r){let f;if(!(n>20)){if(n++,u(e)||u(t)||c(t))f=i(t);else if(s(e)){if(f=e.slice(),s(t))for(let e=0,n=t.length;e<n;e++)f.push(i(t[e]));else if(l(t)){let e=Object.keys(t);for(let n=0,r=e.length;n<r;n++){let r=e[n];f[r]=i(t[r])}}}else if(l(e))if(l(t)){if(!d(e,t))return t;f=Object.assign({},e);let i=Object.keys(t);for(let s=0,c=i.length;s<c;s++){let c=i[s],d=t[c];if(u(d))d===void 0?delete f[c]:f[c]=d;else{let i=f[c],s=d;if(o(e,c,r)||o(t,c,r))delete f[c];else{if(l(i)&&l(s)){let n=r.get(i)||[],a=r.get(s)||[];n.push({obj:e,key:c}),a.push({obj:t,key:c}),r.set(i,n),r.set(s,a)}f[c]=a(f[c],d,n,r)}}}}else f=t;return f}}function o(e,t,n){let r=n.get(e[t])||[];for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i.key===t&&i.obj===e)return!0}return!1}function s(e){return Array.isArray(e)}function c(e){return typeof e==`function`}function l(e){return!u(e)&&!s(e)&&!c(e)&&typeof e==`object`}function u(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function d(e,n){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(n))}})),require_timeout$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function n(e,n){let r,i=new Promise(function(e,i){r=setTimeout(function(){i(new t(`Operation timed out.`))},n)});return Promise.race([e,i]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}e.callWithTimeout=n})),require_url$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function n(e,n){if(!n)return!1;for(let r of n)if(t(e,r))return!0;return!1}e.isUrlIgnored=n})),require_promise$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$2();e.BindOnceFuture=class{_callback;_that;_isCalled=!1;_deferred=new t.Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function r(e){return e==null?void 0:n[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(n)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=r})),require_exporter$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_suppress_tracing$2();function r(e,r){return new Promise(i=>{t.context.with((0,n.suppressTracing)(t.context.active()),()=>{e.export(r,e=>{i(e)})})})}e._export=r})),require_src$13=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.unrefTimer=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$2();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=require_anchored_clock$2();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=require_attributes$2();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=require_global_error_handler$2();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=require_logging_error_handler$2();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=require_time$2();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return o.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return o.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return o.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return o.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return o.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return o.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return o.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return o.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return o.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return o.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return o.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return o.timeInputToHrTime}});var s=require_ExportResult$2();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return s.ExportResultCode}});var c=require_utils$13();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return c.parseKeyPairsIntoRecord}});var l=require_platform$10();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return l.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return l._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return l.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return l.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return l.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return l.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return l.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return l.unrefTimer}});var u=require_composite$2();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return u.CompositePropagator}});var d=require_W3CTraceContextPropagator$2();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return d.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return d.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return d.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return d.parseTraceParent}});var f=require_rpc_metadata$2();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return f.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return f.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return f.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return f.setRPCMetadata}});var p=require_suppress_tracing$2();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return p.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return p.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return p.unsuppressTracing}});var m=require_TraceState$2();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return m.TraceState}});var h=require_merge$2();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return h.merge}});var g=require_timeout$2();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return g.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return g.callWithTimeout}});var _=require_url$2();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return _.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return _.urlMatches}});var v=require_callback$2();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return v.BindOnceFuture}});var y=require_configuration$2();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return y.diagLogLevelFromString}}),e.internal={_export:require_exporter$2()._export}})),require_AggregationTemporality$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregationTemporality=void 0,(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(e.AggregationTemporality||={})})),require_MetricData$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DataPointType=e.InstrumentType=void 0,(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(e.InstrumentType||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(e.DataPointType||={})})),require_utils$12=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.equalsCaseInsensitive=e.binarySearchUB=e.setEquals=e.FlatMap=e.isPromiseAllSettledRejectionResult=e.PromiseAllSettled=e.callWithTimeout=e.TimeoutError=e.instrumentationScopeId=e.hashAttributes=e.isNotNullish=void 0;function t(e){return e!=null}e.isNotNullish=t;function n(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}e.hashAttributes=n;function r(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}e.instrumentationScopeId=r;var i=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=i;function a(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new i(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}e.callWithTimeout=a;async function o(e){return Promise.all(e.map(async e=>{try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}))}e.PromiseAllSettled=o;function s(e){return e.status===`rejected`}e.isPromiseAllSettledRejectionResult=s;function c(e,t){let n=[];return e.forEach(e=>{n.push(...t(e))}),n}e.FlatMap=c;function l(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}e.setEquals=l;function u(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}e.binarySearchUB=u;function d(e,t){return e.toLowerCase()===t.toLowerCase()}e.equalsCaseInsensitive=d})),require_types$5=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregatorKind=void 0,(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(e.AggregatorKind||={})})),require_Drop$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DropAggregator=void 0;let t=require_types$5();e.DropAggregator=class{kind=t.AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}})),require_Histogram$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HistogramAggregator=e.HistogramAccumulation=void 0;let t=require_types$5(),n=require_MetricData$2(),r=require_utils$12();function i(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var a=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=i(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=(0,r.binarySearchUB)(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.HistogramAccumulation=a,e.HistogramAggregator=class{_boundaries;_recordMinMax;kind=t.AggregatorKind.HISTOGRAM;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new a(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,o=r.buckets.counts,s=Array(i.length);for(let e=0;e<i.length;e++)s[e]=i[e]+o[e];let c=1/0,l=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(c=Math.min(n.min,r.min),l=Math.max(n.max,r.max)):n.hasMinMax?(c=n.min,l=n.max):r.hasMinMax&&(c=r.min,l=r.max)),new a(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:c,max:l})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,o=r.buckets.counts,s=Array(i.length);for(let e=0;e<i.length;e++)s[e]=o[e]-i[e];return new a(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,r,i){return{descriptor:e,aggregationTemporality:t,dataPointType:n.DataPointType.HISTOGRAM,dataPoints:r.map(([t,r])=>{let a=r.toPointValue(),o=e.type===n.InstrumentType.GAUGE||e.type===n.InstrumentType.UP_DOWN_COUNTER||e.type===n.InstrumentType.OBSERVABLE_GAUGE||e.type===n.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:i,value:{min:a.hasMinMax?a.min:void 0,max:a.hasMinMax?a.max:void 0,sum:o?void 0:a.sum,buckets:a.buckets,count:a.count}}})}}}})),require_Buckets$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Buckets=void 0,e.Buckets=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new t,n=0,r=0,i=0){this.backing=e,this.indexBase=n,this.indexStart=r,this.indexEnd=i}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}};var t=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}})),require_ieee754$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSignificand=e.getNormalBase2=e.MIN_VALUE=e.MAX_NORMAL_EXPONENT=e.MIN_NORMAL_EXPONENT=e.SIGNIFICAND_WIDTH=void 0,e.SIGNIFICAND_WIDTH=52;let t=2146435072,n=1048575,r=1023;e.MIN_NORMAL_EXPONENT=-r+1,e.MAX_NORMAL_EXPONENT=r,e.MIN_VALUE=2**-1022;function i(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&2146435072)>>20)-r}e.getNormalBase2=i;function a(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),r=t.getUint32(4);return(n&1048575)*2**32+r}e.getSignificand=a})),require_util$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.nextGreaterSquare=e.ldexp=void 0;function t(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}e.ldexp=t;function n(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}e.nextGreaterSquare=n})),require_types$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MappingError=void 0,e.MappingError=class extends Error{}})),require_ExponentMapping$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentMapping=void 0;let t=require_ieee754$2(),n=require_util$2(),r=require_types$4();e.ExponentMapping=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<t.MIN_VALUE?this._minNormalLowerBoundaryIndex():t.getNormalBase2(e)+this._rightShift(t.getSignificand(e)-1,t.SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new r.MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);let i=this._maxNormalLowerBoundaryIndex();if(e>i)throw new r.MappingError(`overflow: ${e} is > maximum lower boundary: ${i}`);return n.ldexp(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=t.MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return t.MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),require_LogarithmMapping$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogarithmMapping=void 0;let t=require_ieee754$2(),n=require_util$2(),r=require_types$4();e.LogarithmMapping=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=n.ldexp(Math.LOG2E,e),this._inverseFactor=n.ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=t.MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(t.getSignificand(e)===0)return(t.getNormalBase2(e)<<this._scale)-1;let n=Math.floor(Math.log(e)*this._scaleFactor),r=this._maxNormalLowerBoundaryIndex();return n>=r?r:n}lowerBoundary(e){let n=this._maxNormalLowerBoundaryIndex();if(e>=n){if(e===n)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new r.MappingError(`overflow: ${e} is > maximum lower boundary: ${n}`)}let i=this._minNormalLowerBoundaryIndex();if(e<=i){if(e===i)return t.MIN_VALUE;if(e===i-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new r.MappingError(`overflow: ${e} is < minimum lower boundary: ${i}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return t.MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(t.MAX_NORMAL_EXPONENT+1<<this._scale)-1}}})),require_getMapping$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMapping=void 0;let t=require_ExponentMapping$2(),n=require_LogarithmMapping$2(),r=require_types$4(),i=-10,a=20,o=Array.from({length:31},(e,r)=>r>10?new n.LogarithmMapping(r-10):new t.ExponentMapping(r-10));function s(e){if(e>20||e<-10)throw new r.MappingError(`expected scale >= -10 && <= 20, got: ${e}`);return o[e+10]}e.getMapping=s})),require_ExponentialHistogram$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=void 0;let t=require_types$5(),n=require_MetricData$2(),r=(init_esm$2(),__toCommonJS(esm_exports$2)),i=require_Buckets$2(),a=require_getMapping$2(),o=require_util$2();var s=class e{low;high;static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}constructor(e,t){this.low=e,this.high=t}};let c=20,l=160,u=2;var d=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=160,n=!0,o=0,s=0,c=0,l=1/0,u=-1/0,d=new i.Buckets,f=new i.Buckets,p=(0,a.getMapping)(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=s,this._zeroCount=c,this._min=l,this._max=u,this._positive=d,this._negative=f,this._mapping=p,this._maxSize<2&&(r.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
12
12
  changing to the minimum size of: 2`),this._maxSize=2)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new e(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,n){let r=this._mapping.mapToIndex(t),i=!1,a=0,o=0;if(e.length===0?(e.indexStart=r,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):r<e.indexStart&&e.indexEnd-r>=this._maxSize?(i=!0,o=r,a=e.indexEnd):r>e.indexEnd&&r-e.indexStart>=this._maxSize&&(i=!0,o=e.indexStart,a=r),i){let e=this._changeScale(a,o);this._downscale(e),r=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,r,n)}_incrementIndexBy(e,t,n){if(n===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){let n=e.indexEnd-t;n>=e.backing.length&&this._grow(e,n+1),e.indexStart=t}else if(t>e.indexEnd){let n=t-e.indexStart;n>=e.backing.length&&this._grow(e,n+1),e.indexEnd=t}let r=t-e.indexBase;r<0&&(r+=e.backing.length),e.incrementBucket(r,n)}_grow(e,t){let n=e.backing.length,r=e.indexBase-e.indexStart,i=n-r,a=(0,o.nextGreaterSquare)(t);a>this._maxSize&&(a=this._maxSize);let s=a-r;e.backing.growTo(a,i,s)}_changeScale(e,t){let n=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n}_downscale(e){if(e===0)return;if(e<0)throw Error(`impossible change of scale: ${this.scale}`);let t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=(0,a.getMapping)(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=s.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=s.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(r.high,r.low))}_highLowAtScale(e,t,n){if(e.length===0)return new s(0,-1);let r=t-n;return new s(e.indexStart>>r,e.indexEnd>>r)}_mergeBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++)this._incrementIndexBy(e,i+t>>a,n.at(t))}_diffBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++){let r=(i+t>>a)-e.indexBase;r<0&&(r+=e.backing.length),e.decrementBucket(r,n.at(t))}e.trim()}};e.ExponentialHistogramAccumulation=d,e.ExponentialHistogramAggregator=class{_maxSize;_recordMinMax;kind=t.AggregatorKind.EXPONENTIAL_HISTOGRAM;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new d(e,this._maxSize,this._recordMinMax)}merge(e,t){let n=t.clone();return n.merge(e),n}diff(e,t){let n=t.clone();return n.diff(e),n}toMetricData(e,t,r,i){return{descriptor:e,aggregationTemporality:t,dataPointType:n.DataPointType.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{let a=r.toPointValue(),o=e.type===n.InstrumentType.GAUGE||e.type===n.InstrumentType.UP_DOWN_COUNTER||e.type===n.InstrumentType.OBSERVABLE_GAUGE||e.type===n.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:i,value:{min:a.hasMinMax?a.min:void 0,max:a.hasMinMax?a.max:void 0,sum:o?void 0:a.sum,positive:{offset:a.positive.offset,bucketCounts:a.positive.bucketCounts},negative:{offset:a.negative.offset,bucketCounts:a.negative.bucketCounts},count:a.count,scale:a.scale,zeroCount:a.zeroCount}}})}}}})),require_LastValue$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LastValueAggregator=e.LastValueAccumulation=void 0;let t=require_types$5(),n=require_src$13(),r=require_MetricData$2();var i=class{startTime;_current;sampleTime;constructor(e,t=0,n=[0,0]){this.startTime=e,this._current=t,this.sampleTime=n}record(e){this._current=e,this.sampleTime=(0,n.millisToHrTime)(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.LastValueAccumulation=i,e.LastValueAggregator=class{kind=t.AggregatorKind.LAST_VALUE;createAccumulation(e){return new i(e)}merge(e,t){let r=(0,n.hrTimeToMicroseconds)(t.sampleTime)>=(0,n.hrTimeToMicroseconds)(e.sampleTime)?t:e;return new i(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){let r=(0,n.hrTimeToMicroseconds)(t.sampleTime)>=(0,n.hrTimeToMicroseconds)(e.sampleTime)?t:e;return new i(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,n,i){return{descriptor:e,aggregationTemporality:t,dataPointType:r.DataPointType.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:i,value:t.toPointValue()}))}}}})),require_Sum$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SumAggregator=e.SumAccumulation=void 0;let t=require_types$5(),n=require_MetricData$2();var r=class{startTime;monotonic;_current;reset;constructor(e,t,n=0,r=!1){this.startTime=e,this.monotonic=t,this._current=n,this.reset=r}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.SumAccumulation=r,e.SumAggregator=class{monotonic;kind=t.AggregatorKind.SUM;constructor(e){this.monotonic=e}createAccumulation(e){return new r(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),i=t.toPointValue();return t.reset?new r(t.startTime,this.monotonic,i,t.reset):new r(e.startTime,this.monotonic,n+i)}diff(e,t){let n=e.toPointValue(),i=t.toPointValue();return this.monotonic&&n>i?new r(t.startTime,this.monotonic,i,!0):new r(t.startTime,this.monotonic,i-n)}toMetricData(e,t,r,i){return{descriptor:e,aggregationTemporality:t,dataPointType:n.DataPointType.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:i,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),require_aggregator$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SumAggregator=e.SumAccumulation=e.LastValueAggregator=e.LastValueAccumulation=e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=e.HistogramAggregator=e.HistogramAccumulation=e.DropAggregator=void 0;var t=require_Drop$2();Object.defineProperty(e,`DropAggregator`,{enumerable:!0,get:function(){return t.DropAggregator}});var n=require_Histogram$2();Object.defineProperty(e,`HistogramAccumulation`,{enumerable:!0,get:function(){return n.HistogramAccumulation}}),Object.defineProperty(e,`HistogramAggregator`,{enumerable:!0,get:function(){return n.HistogramAggregator}});var r=require_ExponentialHistogram$2();Object.defineProperty(e,`ExponentialHistogramAccumulation`,{enumerable:!0,get:function(){return r.ExponentialHistogramAccumulation}}),Object.defineProperty(e,`ExponentialHistogramAggregator`,{enumerable:!0,get:function(){return r.ExponentialHistogramAggregator}});var i=require_LastValue$2();Object.defineProperty(e,`LastValueAccumulation`,{enumerable:!0,get:function(){return i.LastValueAccumulation}}),Object.defineProperty(e,`LastValueAggregator`,{enumerable:!0,get:function(){return i.LastValueAggregator}});var a=require_Sum$2();Object.defineProperty(e,`SumAccumulation`,{enumerable:!0,get:function(){return a.SumAccumulation}}),Object.defineProperty(e,`SumAggregator`,{enumerable:!0,get:function(){return a.SumAggregator}})})),require_Aggregation$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_AGGREGATION=e.EXPONENTIAL_HISTOGRAM_AGGREGATION=e.HISTOGRAM_AGGREGATION=e.LAST_VALUE_AGGREGATION=e.SUM_AGGREGATION=e.DROP_AGGREGATION=e.DefaultAggregation=e.ExponentialHistogramAggregation=e.ExplicitBucketHistogramAggregation=e.HistogramAggregation=e.LastValueAggregation=e.SumAggregation=e.DropAggregation=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_aggregator$2(),r=require_MetricData$2();var i=class e{static DEFAULT_INSTANCE=new n.DropAggregator;createAggregator(t){return e.DEFAULT_INSTANCE}};e.DropAggregation=i;var a=class e{static MONOTONIC_INSTANCE=new n.SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new n.SumAggregator(!1);createAggregator(t){switch(t.type){case r.InstrumentType.COUNTER:case r.InstrumentType.OBSERVABLE_COUNTER:case r.InstrumentType.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}};e.SumAggregation=a;var o=class e{static DEFAULT_INSTANCE=new n.LastValueAggregator;createAggregator(t){return e.DEFAULT_INSTANCE}};e.LastValueAggregation=o;var s=class e{static DEFAULT_INSTANCE=new n.HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}};e.HistogramAggregation=s;var c=class{_recordMinMax;_boundaries;constructor(e,t=!0){if(this._recordMinMax=t,e==null)throw Error(`ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array`);e=e.concat(),e=e.sort((e,t)=>e-t);let n=e.lastIndexOf(-1/0),r=e.indexOf(1/0);r===-1&&(r=void 0),this._boundaries=e.slice(n+1,r)}createAggregator(e){return new n.HistogramAggregator(this._boundaries,this._recordMinMax)}};e.ExplicitBucketHistogramAggregation=c;var l=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new n.ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}};e.ExponentialHistogramAggregation=l;var u=class{_resolve(n){switch(n.type){case r.InstrumentType.COUNTER:case r.InstrumentType.UP_DOWN_COUNTER:case r.InstrumentType.OBSERVABLE_COUNTER:case r.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:return e.SUM_AGGREGATION;case r.InstrumentType.GAUGE:case r.InstrumentType.OBSERVABLE_GAUGE:return e.LAST_VALUE_AGGREGATION;case r.InstrumentType.HISTOGRAM:return n.advice.explicitBucketBoundaries?new c(n.advice.explicitBucketBoundaries):e.HISTOGRAM_AGGREGATION}return t.diag.warn(`Unable to recognize instrument type: ${n.type}`),e.DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}};e.DefaultAggregation=u,e.DROP_AGGREGATION=new i,e.SUM_AGGREGATION=new a,e.LAST_VALUE_AGGREGATION=new o,e.HISTOGRAM_AGGREGATION=new s,e.EXPONENTIAL_HISTOGRAM_AGGREGATION=new l,e.DEFAULT_AGGREGATION=new u})),require_AggregationOption$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toAggregation=e.AggregationType=void 0;let t=require_Aggregation$2();var n;(function(e){e[e.DEFAULT=0]=`DEFAULT`,e[e.DROP=1]=`DROP`,e[e.SUM=2]=`SUM`,e[e.LAST_VALUE=3]=`LAST_VALUE`,e[e.EXPLICIT_BUCKET_HISTOGRAM=4]=`EXPLICIT_BUCKET_HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=5]=`EXPONENTIAL_HISTOGRAM`})(n=e.AggregationType||={});function r(e){switch(e.type){case n.DEFAULT:return t.DEFAULT_AGGREGATION;case n.DROP:return t.DROP_AGGREGATION;case n.SUM:return t.SUM_AGGREGATION;case n.LAST_VALUE:return t.LAST_VALUE_AGGREGATION;case n.EXPONENTIAL_HISTOGRAM:{let n=e;return new t.ExponentialHistogramAggregation(n.options?.maxSize,n.options?.recordMinMax)}case n.EXPLICIT_BUCKET_HISTOGRAM:{let n=e;return n.options==null?t.HISTOGRAM_AGGREGATION:new t.ExplicitBucketHistogramAggregation(n.options?.boundaries,n.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}e.toAggregation=r})),require_AggregationSelector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e.DEFAULT_AGGREGATION_SELECTOR=void 0;let t=require_AggregationTemporality$2(),n=require_AggregationOption$2();e.DEFAULT_AGGREGATION_SELECTOR=e=>({type:n.AggregationType.DEFAULT}),e.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>t.AggregationTemporality.CUMULATIVE})),require_MetricReader$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricReader=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_utils$12(),r=require_AggregationSelector$2();e.MetricReader=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??r.DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??r.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw Error(`MetricReader is not bound to a MetricProducer`);if(this._shutdown)throw Error(`MetricReader is shutdown`);let[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=t.errors.concat((0,n.FlatMap)(r,e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat((0,n.FlatMap)(r,e=>e.resourceMetrics.scopeMetrics))},errors:i}}async shutdown(e){if(this._shutdown){t.diag.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await(0,n.callWithTimeout)(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){t.diag.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await(0,n.callWithTimeout)(this.onForceFlush(),e.timeoutMillis)}}})),require_PeriodicExportingMetricReader$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PeriodicExportingMetricReader=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$13(),r=require_MetricReader$2(),i=require_utils$12();e.PeriodicExportingMetricReader=class extends r.MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){if(super({aggregationSelector:e.exporter.selectAggregation?.bind(e.exporter),aggregationTemporalitySelector:e.exporter.selectAggregationTemporality?.bind(e.exporter),metricProducers:e.metricProducers}),e.exportIntervalMillis!==void 0&&e.exportIntervalMillis<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(e.exportTimeoutMillis!==void 0&&e.exportTimeoutMillis<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(e.exportTimeoutMillis!==void 0&&e.exportIntervalMillis!==void 0&&e.exportIntervalMillis<e.exportTimeoutMillis)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);this._exportInterval=e.exportIntervalMillis??6e4,this._exportTimeout=e.exportTimeoutMillis??3e4,this._exporter=e.exporter}async _runOnce(){try{await(0,i.callWithTimeout)(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof i.TimeoutError){t.diag.error(`Export took longer than %s milliseconds and timed out.`,this._exportTimeout);return}(0,n.globalErrorHandler)(e)}}async _doRun(){let{resourceMetrics:e,errors:r}=await this.collect({timeoutMillis:this._exportTimeout});if(r.length>0&&t.diag.error(`PeriodicExportingMetricReader: metrics collection errors`,...r),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){t.diag.debug(`Error while resolving async portion of resource: `,e),(0,n.globalErrorHandler)(e)}if(e.scopeMetrics.length===0)return;let i=await n.internal._export(this._exporter,e);if(i.code!==n.ExportResultCode.SUCCESS)throw Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),(0,n.unrefTimer)(this._interval)}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}})),require_InMemoryMetricExporter$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryMetricExporter=void 0;let t=require_src$13();e.InMemoryMetricExporter=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,n){if(this._shutdown){setTimeout(()=>n({code:t.ExportResultCode.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>n({code:t.ExportResultCode.SUCCESS}),0)}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}})),require_ConsoleMetricExporter$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleMetricExporter=void 0;let t=require_src$13(),n=require_AggregationSelector$2();e.ConsoleMetricExporter=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??n.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(n,r){if(this._shutdown){setImmediate(r,{code:t.ExportResultCode.FAILED});return}return e._sendMetrics(n,r)}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,n){for(let t of e.scopeMetrics)for(let e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});n({code:t.ExportResultCode.SUCCESS})}}})),require_default_service_name$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;function t(){return`unknown_service:${process.argv0}`}e.defaultServiceName=t})),require_node$10=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=require_default_service_name$2();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),require_platform$9=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=require_node$10();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),require_utils$11=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.identity=e.isPromiseLike=void 0,e.isPromiseLike=e=>typeof e==`object`&&!!e&&typeof e.then==`function`;function t(e){return e}e.identity=t})),require_ResourceImpl$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$13(),r=(init_esm$1(),__toCommonJS(esm_exports$1)),i=require_platform$9(),a=require_utils$11();var o=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,n){let r=new e({},n);return r._rawAttributes=d(t),r._asyncAttributesPending=t.filter(([e,t])=>(0,a.isPromiseLike)(t)).length>0,r}constructor(e,t){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([e,t])=>((0,a.isPromiseLike)(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=d(this._rawAttributes),this._schemaUrl=f(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[t,n]=this._rawAttributes[e];this._rawAttributes[e]=[t,(0,a.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&t.diag.error(`Accessing resource attributes before async attributes settled`),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[n,r]of this._rawAttributes){if((0,a.isPromiseLike)(r)){t.diag.debug(`Unsettled resource attribute ${n} skipped`);continue}r!=null&&(e[n]??=r)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;let n=p(this,t),r=n?{schemaUrl:n}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],r)}};function s(e,t){return o.FromAttributeList(Object.entries(e),t)}e.resourceFromAttributes=s;function c(e,t){return new o(e,t)}e.resourceFromDetectedResource=c;function l(){return s({})}e.emptyResource=l;function u(){return s({[r.ATTR_SERVICE_NAME]:(0,i.defaultServiceName)(),[r.ATTR_TELEMETRY_SDK_LANGUAGE]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_LANGUAGE],[r.ATTR_TELEMETRY_SDK_NAME]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_NAME],[r.ATTR_TELEMETRY_SDK_VERSION]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_VERSION]})}e.defaultResource=u;function d(e){return e.map(([e,n])=>(0,a.isPromiseLike)(n)?[e,n.catch(n=>{t.diag.debug(`promise rejection for resource attribute: %s - %s`,e,n)})]:[e,n])}function f(e){if(typeof e==`string`||e===void 0)return e;t.diag.warn(`Schema URL must be string or undefined, got %s. Schema URL will be ignored.`,e)}function p(e,n){let r=e?.schemaUrl,i=n?.schemaUrl,a=r===void 0||r===``,o=i===void 0||i===``;if(a)return i;if(o||r===i)return r;t.diag.warn(`Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.`,r,i)}})),require_detect_resources$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_ResourceImpl$2();e.detectResources=(e={})=>(e.detectors||[]).map(r=>{try{let i=(0,n.resourceFromDetectedResource)(r.detect(e));return t.diag.debug(`${r.constructor.name} found resource.`,i),i}catch(e){return t.diag.debug(`${r.constructor.name} failed: ${e.message}`),(0,n.emptyResource)()}}).reduce((e,t)=>e.merge(t),(0,n.emptyResource)())})),require_EnvDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=(init_esm$1(),__toCommonJS(esm_exports$1)),r=require_src$13();e.envDetector=new class{_MAX_LENGTH=255;_COMMA_SEPARATOR=`,`;_LABEL_KEY_VALUE_SPLITTER=`=`;_ERROR_MESSAGE_INVALID_CHARS=`should be a ASCII string with a length greater than 0 and not exceed `+this._MAX_LENGTH+` characters.`;_ERROR_MESSAGE_INVALID_VALUE=`should be a ASCII string with a length not exceed `+this._MAX_LENGTH+` characters.`;detect(e){let i={},a=(0,r.getStringFromEnv)(`OTEL_RESOURCE_ATTRIBUTES`),o=(0,r.getStringFromEnv)(`OTEL_SERVICE_NAME`);if(a)try{let e=this._parseResourceAttributes(a);Object.assign(i,e)}catch(e){t.diag.debug(`EnvDetector failed: ${e.message}`)}return o&&(i[n.ATTR_SERVICE_NAME]=o),{attributes:i}}_parseResourceAttributes(e){if(!e)return{};let t={},n=e.split(this._COMMA_SEPARATOR,-1);for(let e of n){let n=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(n.length!==2)continue;let[r,i]=n;if(r=r.trim(),i=i.trim().split(/^"|"$/).join(``),!this._isValidAndNotEmpty(r))throw Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[r]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<33||n===44||n===59||n===92||n>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}})),require_semconv$5=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_WEBENGINE_VERSION=e.ATTR_WEBENGINE_NAME=e.ATTR_WEBENGINE_DESCRIPTION=e.ATTR_SERVICE_NAMESPACE=e.ATTR_SERVICE_INSTANCE_ID=e.ATTR_PROCESS_RUNTIME_VERSION=e.ATTR_PROCESS_RUNTIME_NAME=e.ATTR_PROCESS_RUNTIME_DESCRIPTION=e.ATTR_PROCESS_PID=e.ATTR_PROCESS_OWNER=e.ATTR_PROCESS_EXECUTABLE_PATH=e.ATTR_PROCESS_EXECUTABLE_NAME=e.ATTR_PROCESS_COMMAND_ARGS=e.ATTR_PROCESS_COMMAND=e.ATTR_OS_VERSION=e.ATTR_OS_TYPE=e.ATTR_K8S_POD_NAME=e.ATTR_K8S_NAMESPACE_NAME=e.ATTR_K8S_DEPLOYMENT_NAME=e.ATTR_K8S_CLUSTER_NAME=e.ATTR_HOST_TYPE=e.ATTR_HOST_NAME=e.ATTR_HOST_IMAGE_VERSION=e.ATTR_HOST_IMAGE_NAME=e.ATTR_HOST_IMAGE_ID=e.ATTR_HOST_ID=e.ATTR_HOST_ARCH=e.ATTR_CONTAINER_NAME=e.ATTR_CONTAINER_IMAGE_TAGS=e.ATTR_CONTAINER_IMAGE_NAME=e.ATTR_CONTAINER_ID=e.ATTR_CLOUD_REGION=e.ATTR_CLOUD_PROVIDER=e.ATTR_CLOUD_AVAILABILITY_ZONE=e.ATTR_CLOUD_ACCOUNT_ID=void 0,e.ATTR_CLOUD_ACCOUNT_ID=`cloud.account.id`,e.ATTR_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,e.ATTR_CLOUD_PROVIDER=`cloud.provider`,e.ATTR_CLOUD_REGION=`cloud.region`,e.ATTR_CONTAINER_ID=`container.id`,e.ATTR_CONTAINER_IMAGE_NAME=`container.image.name`,e.ATTR_CONTAINER_IMAGE_TAGS=`container.image.tags`,e.ATTR_CONTAINER_NAME=`container.name`,e.ATTR_HOST_ARCH=`host.arch`,e.ATTR_HOST_ID=`host.id`,e.ATTR_HOST_IMAGE_ID=`host.image.id`,e.ATTR_HOST_IMAGE_NAME=`host.image.name`,e.ATTR_HOST_IMAGE_VERSION=`host.image.version`,e.ATTR_HOST_NAME=`host.name`,e.ATTR_HOST_TYPE=`host.type`,e.ATTR_K8S_CLUSTER_NAME=`k8s.cluster.name`,e.ATTR_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,e.ATTR_K8S_NAMESPACE_NAME=`k8s.namespace.name`,e.ATTR_K8S_POD_NAME=`k8s.pod.name`,e.ATTR_OS_TYPE=`os.type`,e.ATTR_OS_VERSION=`os.version`,e.ATTR_PROCESS_COMMAND=`process.command`,e.ATTR_PROCESS_COMMAND_ARGS=`process.command_args`,e.ATTR_PROCESS_EXECUTABLE_NAME=`process.executable.name`,e.ATTR_PROCESS_EXECUTABLE_PATH=`process.executable.path`,e.ATTR_PROCESS_OWNER=`process.owner`,e.ATTR_PROCESS_PID=`process.pid`,e.ATTR_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`,e.ATTR_PROCESS_RUNTIME_VERSION=`process.runtime.version`,e.ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,e.ATTR_SERVICE_NAMESPACE=`service.namespace`,e.ATTR_WEBENGINE_DESCRIPTION=`webengine.description`,e.ATTR_WEBENGINE_NAME=`webengine.name`,e.ATTR_WEBENGINE_VERSION=`webengine.version`})),require_getMachineId$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMachineId=void 0;let t=__require$1(`process`),n;async function r(){if(!n)switch(t.platform){case`darwin`:n=(await import(`./getMachineId-darwin-DC2qb-xd.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`linux`:n=(await import(`./getMachineId-linux-C3A6DqVu.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`freebsd`:n=(await import(`./getMachineId-bsd-DrOrzTD2.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`win32`:n=(await import(`./getMachineId-win-D8Js6D_D.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;default:n=(await import(`./getMachineId-unsupported-BrxgPAkN.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break}return n()}e.getMachineId=r})),require_utils$10=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.normalizeType=e.normalizeArch=void 0,e.normalizeArch=e=>{switch(e){case`arm`:return`arm32`;case`ppc`:return`ppc32`;case`x64`:return`amd64`;default:return e}},e.normalizeType=e=>{switch(e){case`sunos`:return`solaris`;case`win32`:return`windows`;default:return e}}})),require_HostDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=require_semconv$5(),n=__require$1(`os`),r=require_getMachineId$2(),i=require_utils$10();e.hostDetector=new class{detect(e){return{attributes:{[t.ATTR_HOST_NAME]:(0,n.hostname)(),[t.ATTR_HOST_ARCH]:(0,i.normalizeArch)((0,n.arch)()),[t.ATTR_HOST_ID]:(0,r.getMachineId)()}}}}})),require_OSDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=require_semconv$5(),n=__require$1(`os`),r=require_utils$10();e.osDetector=new class{detect(e){return{attributes:{[t.ATTR_OS_TYPE]:(0,r.normalizeType)((0,n.platform)()),[t.ATTR_OS_VERSION]:(0,n.release)()}}}}})),require_ProcessDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_semconv$5(),r=__require$1(`os`);e.processDetector=new class{detect(e){let i={[n.ATTR_PROCESS_PID]:process.pid,[n.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[n.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[n.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[n.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[n.ATTR_PROCESS_RUNTIME_NAME]:`nodejs`,[n.ATTR_PROCESS_RUNTIME_DESCRIPTION]:`Node.js`};process.argv.length>1&&(i[n.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let e=r.userInfo();i[n.ATTR_PROCESS_OWNER]=e.username}catch(e){t.diag.debug(`error obtaining process owner: ${e}`)}return{attributes:i}}}})),require_ServiceInstanceIdDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=require_semconv$5(),n=__require$1(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,n.randomUUID)()}}}}})),require_node$9=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_HostDetector$2();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var n=require_OSDetector$2();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}});var r=require_ProcessDetector$2();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return r.processDetector}});var i=require_ServiceInstanceIdDetector$2();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return i.serviceInstanceIdDetector}})})),require_platform$8=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_node$9();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return t.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return t.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return t.serviceInstanceIdDetector}})})),require_NoopDetector$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.NoopDetector=void 0;var t=class{detect(){return{attributes:{}}}};e.NoopDetector=t,e.noopDetector=new t})),require_detectors$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=require_EnvDetector$2();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var n=require_platform$8();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=require_NoopDetector$2();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return r.noopDetector}})})),require_src$12=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=e.emptyResource=e.defaultResource=e.resourceFromAttributes=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=e.detectResources=void 0;var t=require_detect_resources$2();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var n=require_detectors$2();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return n.envDetector}}),Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=require_ResourceImpl$2();Object.defineProperty(e,`resourceFromAttributes`,{enumerable:!0,get:function(){return r.resourceFromAttributes}}),Object.defineProperty(e,`defaultResource`,{enumerable:!0,get:function(){return r.defaultResource}}),Object.defineProperty(e,`emptyResource`,{enumerable:!0,get:function(){return r.emptyResource}});var i=require_platform$9();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return i.defaultServiceName}})})),require_ViewRegistry$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ViewRegistry=void 0,e.ViewRegistry=class{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(n=>this._matchInstrument(n.instrumentSelector,e)&&this._matchMeter(n.meterSelector,t))}_matchInstrument(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))}}})),require_InstrumentDescriptor$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isValidName=e.isDescriptorCompatibleWith=e.createInstrumentDescriptorWithView=e.createInstrumentDescriptor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_utils$12();function r(e,n,r){return s(e)||t.diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:n,description:r?.description??``,unit:r?.unit??``,valueType:r?.valueType??t.ValueType.DOUBLE,advice:r?.advice??{}}}e.createInstrumentDescriptor=r;function i(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}e.createInstrumentDescriptorWithView=i;function a(e,t){return(0,n.equalsCaseInsensitive)(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}e.isDescriptorCompatibleWith=a;let o=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function s(e){return e.match(o)!=null}e.isValidName=s})),require_Instruments$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isObservableInstrument=e.ObservableUpDownCounterInstrument=e.ObservableGaugeInstrument=e.ObservableCounterInstrument=e.ObservableInstrument=e.HistogramInstrument=e.GaugeInstrument=e.CounterInstrument=e.UpDownCounterInstrument=e.SyncInstrument=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$13();var r=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,r={},i=t.context.active()){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,r,i,(0,n.millisToHrTime)(Date.now()))}};e.SyncInstrument=r,e.UpDownCounterInstrument=class extends r{add(e,t,n){this._record(e,t,n)}},e.CounterInstrument=class extends r{add(e,n,r){if(e<0){t.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,n,r)}},e.GaugeInstrument=class extends r{record(e,t,n){this._record(e,t,n)}},e.HistogramInstrument=class extends r{record(e,n,r){if(e<0){t.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,n,r)}};var i=class{_observableRegistry;_metricStorages;_descriptor;constructor(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}};e.ObservableInstrument=i,e.ObservableCounterInstrument=class extends i{},e.ObservableGaugeInstrument=class extends i{},e.ObservableUpDownCounterInstrument=class extends i{};function a(e){return e instanceof i}e.isObservableInstrument=a})),require_Meter$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Meter=void 0;let t=require_InstrumentDescriptor$2(),n=require_Instruments$2(),r=require_MetricData$2();e.Meter=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.GAUGE,i),o=this._meterSharedState.registerMetricStorage(a);return new n.GaugeInstrument(o,a)}createHistogram(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.HISTOGRAM,i),o=this._meterSharedState.registerMetricStorage(a);return new n.HistogramInstrument(o,a)}createCounter(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.COUNTER,i),o=this._meterSharedState.registerMetricStorage(a);return new n.CounterInstrument(o,a)}createUpDownCounter(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.UP_DOWN_COUNTER,i),o=this._meterSharedState.registerMetricStorage(a);return new n.UpDownCounterInstrument(o,a)}createObservableGauge(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.OBSERVABLE_GAUGE,i),o=this._meterSharedState.registerAsyncMetricStorage(a);return new n.ObservableGaugeInstrument(a,o,this._meterSharedState.observableRegistry)}createObservableCounter(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.OBSERVABLE_COUNTER,i),o=this._meterSharedState.registerAsyncMetricStorage(a);return new n.ObservableCounterInstrument(a,o,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,i){let a=(0,t.createInstrumentDescriptor)(e,r.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER,i),o=this._meterSharedState.registerAsyncMetricStorage(a);return new n.ObservableUpDownCounterInstrument(a,o,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),require_MetricStorage$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricStorage=void 0;let t=require_InstrumentDescriptor$2();e.MetricStorage=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=(0,t.createInstrumentDescriptor)(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),require_HashMap$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AttributeHashMap=e.HashMap=void 0;let t=require_utils$12();var n=class{_hash;_valueMap=new Map;_keyMap=new Map;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){let n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);let r=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r),r}set(e,t,n){n??=this._hash(e),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){let e=this._keyMap.entries(),t=e.next();for(;t.done!==!0;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){let e=this._valueMap.entries(),t=e.next();for(;t.done!==!0;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}};e.HashMap=n,e.AttributeHashMap=class extends n{constructor(){super(t.hashAttributes)}}})),require_DeltaMetricProcessor$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DeltaMetricProcessor=void 0;let t=require_utils$12(),n=require_HashMap$2();e.DeltaMetricProcessor=class{_aggregator;_activeCollectionStorage=new n.AttributeHashMap;_cumulativeMemoStorage=new n.AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;constructor(e,n){this._aggregator=e,this._cardinalityLimit=(n??2e3)-1,this._overflowHashCode=(0,t.hashAttributes)(this._overflowAttributes)}record(e,t,n,r){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(r))?.record(e);return}i=this._aggregator.createAccumulation(r),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,n,r])=>{let i=this._aggregator.createAccumulation(t);i?.record(n);let a=i;if(this._cumulativeMemoStorage.has(e,r)){let t=this._cumulativeMemoStorage.get(e,r);a=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,r=this._overflowHashCode,this._cumulativeMemoStorage.has(e,r))){let t=this._cumulativeMemoStorage.get(e,r);a=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,r)){let t=this._activeCollectionStorage.get(e,r);a=this._aggregator.merge(t,a)}this._cumulativeMemoStorage.set(e,i,r),this._activeCollectionStorage.set(e,a,r)})}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new n.AttributeHashMap,e}}})),require_TemporalMetricProcessor$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TemporalMetricProcessor=void 0;let t=require_AggregationTemporality$2(),n=require_HashMap$2();e.TemporalMetricProcessor=class e{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(n,i,a,o){this._stashAccumulations(a);let s=this._getMergedUnreportedAccumulations(n),c=s,l;if(this._reportHistory.has(n)){let r=this._reportHistory.get(n),i=r.collectionTime;l=r.aggregationTemporality,c=l===t.AggregationTemporality.CUMULATIVE?e.merge(r.accumulations,s,this._aggregator):e.calibrateStartTime(r.accumulations,s,i)}else l=n.selectAggregationTemporality(i.type);this._reportHistory.set(n,{accumulations:c,collectionTime:o,aggregationTemporality:l});let u=r(c);if(u.length!==0)return this._aggregator.toMetricData(i,l,u,o)}_stashAccumulations(e){let t=this._unreportedAccumulations.keys();for(let n of t){let t=this._unreportedAccumulations.get(n);t===void 0&&(t=[],this._unreportedAccumulations.set(n,t)),t.push(e)}}_getMergedUnreportedAccumulations(t){let r=new n.AttributeHashMap,i=this._unreportedAccumulations.get(t);if(this._unreportedAccumulations.set(t,[]),i===void 0)return r;for(let t of i)r=e.merge(r,t,this._aggregator);return r}static merge(e,t,n){let r=e,i=t.entries(),a=i.next();for(;a.done!==!0;){let[t,o,s]=a.value;if(e.has(t,s)){let i=e.get(t,s),a=n.merge(i,o);r.set(t,a,s)}else r.set(t,o,s);a=i.next()}return r}static calibrateStartTime(e,t,n){for(let[r,i]of e.keys())t.get(r,i)?.setStartTime(n);return t}};function r(e){return Array.from(e.entries())}})),require_AsyncMetricStorage$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AsyncMetricStorage=void 0;let t=require_MetricStorage$2(),n=require_DeltaMetricProcessor$2(),r=require_TemporalMetricProcessor$2(),i=require_HashMap$2();e.AsyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,i,a,o){super(e),this._attributesProcessor=i,this._aggregationCardinalityLimit=o,this._deltaMetricStorage=new n.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new r.TemporalMetricProcessor(t,a)}record(e,t){let n=new i.AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{n.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(n,t)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),require_RegistrationConflicts$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getConflictResolutionRecipe=e.getDescriptionResolutionRecipe=e.getTypeConflictResolutionRecipe=e.getUnitConflictResolutionRecipe=e.getValueTypeConflictResolutionRecipe=e.getIncompatibilityDetails=void 0;function t(e,t){let n=``;return e.unit!==t.unit&&(n+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(n+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(n+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(n+=`\t- Description '${e.description}' does not match '${t.description}'\n`),n}e.getIncompatibilityDetails=t;function n(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}e.getValueTypeConflictResolutionRecipe=n;function r(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}e.getUnitConflictResolutionRecipe=r;function i(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'`}e.getTypeConflictResolutionRecipe=i;function a(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'
@@ -35,7 +35,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
35
35
  To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
36
36
  `,`Details:
37
37
  `,(0,r.getIncompatibilityDetails)(i,e),`To resolve the conflict:
38
- `,(0,r.getConflictResolutionRecipe)(i,e))}return a}}})),require_MultiWritableMetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,n,r){this._backingStorages.forEach(i=>{i.record(e,t,n,r)})}}})),require_ObservableResult=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_HashMap(),r=require_Instruments();e.ObservableResultImpl=class{_buffer=new n.AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,i,a={}){if(!(0,r.isObservableInstrument)(e))return;let o=this._buffer.get(e);if(o??(o=new n.AttributeHashMap,this._buffer.set(e,o)),typeof i!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${i}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(i)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),i=Math.trunc(i),!Number.isInteger(i))||o.set(a,i)}}})),require_ObservableRegistry=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_Instruments(),r=require_ObservableResult(),i=require_utils$1();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,r){let i=new Set(r.filter(n.isObservableInstrument));if(i.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,r);return}this._findBatchCallback(e,i)>=0||this._batchCallbacks.push({callback:e,instruments:i})}removeBatchCallback(e,t){let r=new Set(t.filter(n.isObservableInstrument)),i=this._findBatchCallback(e,r);i<0||this._batchCallbacks.splice(i,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:a})=>{let o=new r.ObservableResultImpl(a._descriptor.name,a._descriptor.valueType),s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a._metricStorages.forEach(t=>{t.record(o._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:a})=>{let o=new r.BatchObservableResultImpl,s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a.forEach(t=>{let n=o._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&(0,i.setEquals)(n.instruments,t))}}})),require_SyncMetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage(),n=require_DeltaMetricProcessor(),r=require_TemporalMetricProcessor();e.SyncMetricStorage=class extends t.MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,i,a,o){super(e),this._aggregationCardinalityLimit=o,this._deltaMetricStorage=new n.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new r.TemporalMetricProcessor(t,a),this._attributesProcessor=i}record(e,t,n,r){t=this._attributesProcessor.process(t,n),this._deltaMetricStorage.record(e,t,n,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),require_AttributesProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},n=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},r=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(n[t]=e[t])}),n}},i=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(n[t]=e[t])}),n}};function a(){return l}e.createNoopAttributesProcessor=a;function o(e){return new n(e)}e.createMultiAttributesProcessor=o;function s(e){return new r(e)}e.createAllowListAttributesProcessor=s;function c(e){return new i(e)}e.createDenyListAttributesProcessor=c;let l=new t})),require_MeterSharedState=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor(),n=require_Meter(),r=require_AsyncMetricStorage(),i=require_MetricStorageRegistry(),a=require_MultiWritableMetricStorage(),o=require_ObservableRegistry(),s=require_SyncMetricStorage(),c=require_AttributesProcessor();e.MeterSharedState=class{metricStorageRegistry=new i.MetricStorageRegistry;observableRegistry=new o.ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new n.Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,s.SyncMetricStorage);return t.length===1?t[0]:new a.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,r.AsyncMetricStorage)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,n){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{let i=(0,t.createInstrumentDescriptorWithView)(r,e),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let o=new n(i,r.aggregation.createAggregator(i),r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(r.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(i!=null)return i;let a=r.createAggregator(e),o=t.selectCardinalityLimit(e.type),s=new n(e,a,(0,c.createNoopAttributesProcessor)(),[t],o);return this.metricStorageRegistry.registerForCollector(t,s),s});r=r.concat(t)}return r}}})),require_MeterProviderSharedState=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$1(),n=require_ViewRegistry(),r=require_MeterSharedState(),i=require_AggregationOption();e.MeterProviderSharedState=class{viewRegistry=new n.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let n=(0,t.instrumentationScopeId)(e),i=this.meterSharedStates.get(n);return i??(i=new r.MeterSharedState(this,e),this.meterSharedStates.set(n,i)),i}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,(0,i.toAggregation)(n.selectAggregation(e))]);return t}}})),require_MetricCollector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$14();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let n=(0,t.millisToHrTime)(Date.now()),r=[],i=[],a=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let a=await t.collect(this,n,e);a?.scopeMetrics!=null&&r.push(a.scopeMetrics),a?.errors!=null&&i.push(...a.errors)});return await Promise.all(a),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:i}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate(),n=require_AttributesProcessor(),r=require_InstrumentSelector(),i=require_MeterSelector(),a=require_AggregationOption();function o(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function s(e){if(o(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){s(e),e.attributesProcessors==null?this.attributesProcessor=(0,n.createNoopAttributesProcessor)():this.attributesProcessor=(0,n.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,a.toAggregation)(e.aggregation??{type:a.AggregationType.DEFAULT}),this.instrumentSelector=new r.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new i.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$3(),r=require_MeterProviderSharedState(),i=require_MetricCollector(),a=require_View();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new r.MeterProviderSharedState(e?.resource??(0,n.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new a.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new i.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,n=``,r={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:n,schemaUrl:r.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=require_MetricData();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=require_MetricReader();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=require_PeriodicExportingMetricReader();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=require_InMemoryMetricExporter();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=require_ConsoleMetricExporter();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=require_MeterProvider();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=require_AggregationOption();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=require_AttributesProcessor();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=require_utils$1();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),require_enums=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExceptionEventName=void 0,e.ExceptionEventName=`exception`})),require_Span=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SpanImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=(init_esm$1(),__toCommonJS(esm_exports$1)),i=require_enums();e.SpanImpl=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:t.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=n.otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+n.otperformance.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,r){if(r==null||this._isSpanEnded())return this;if(e.length===0)return t.diag.warn(`Invalid attribute key: ${e}`),this;if(!(0,n.isAttributeValue)(r))return t.diag.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:i}=this._spanLimits,a=!Object.prototype.hasOwnProperty.call(this.attributes,e);return i!==void 0&&this._attributesCount>=i&&a?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(r),a&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,r,i){if(this._isSpanEnded())return this;let{eventCountLimit:a}=this._spanLimits;if(a===0)return t.diag.warn(`No events allowed.`),this._droppedEventsCount++,this;a!==void 0&&this.events.length>=a&&(this._droppedEventsCount===0&&t.diag.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),(0,n.isTimeInput)(r)&&((0,n.isTimeInput)(i)||(i=r),r=void 0);let o=(0,n.sanitizeAttributes)(r),{attributePerEventCountLimit:s}=this._spanLimits,c={},l=0,u=0;for(let e in o){if(!Object.prototype.hasOwnProperty.call(o,e))continue;let t=o[e];if(s!==void 0&&u>=s){l++;continue}c[e]=this._truncateToSize(t),u++}return this.events.push({name:e,attributes:c,time:this._getTime(i),droppedAttributesCount:l}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:r}=this._spanLimits;if(r===0)return this._droppedLinksCount++,this;r!==void 0&&this.links.length>=r&&(this._droppedLinksCount===0&&t.diag.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:i}=this._spanLimits,a=(0,n.sanitizeAttributes)(e.attributes),o={},s=0,c=0;for(let e in a){if(!Object.prototype.hasOwnProperty.call(a,e))continue;let t=a[e];if(i!==void 0&&c>=i){s++;continue}o[e]=this._truncateToSize(t),c++}let l={context:e.context};return c>0&&(l.attributes=o),s>0&&(l.droppedAttributesCount=s),this.links.push(l),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===t.SpanStatusCode.UNSET||this.status.code===t.SpanStatusCode.OK)return this;let n={code:e.code};return e.code===t.SpanStatusCode.ERROR&&(typeof e.message==`string`?n.message=e.message:e.message!=null&&t.diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=n,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){if(this._isSpanEnded()){t.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=(0,n.hrTimeDuration)(this.startTime,this.endTime),this._duration[0]<0&&(t.diag.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&t.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&t.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e==`number`&&e<=n.otperformance.now())return(0,n.hrTime)(e+this._performanceOffset);if(typeof e==`number`)return(0,n.millisToHrTime)(e);if(e instanceof Date)return(0,n.millisToHrTime)(e.getTime());if((0,n.isTimeInputHrTime)(e))return e;if(this._startTimeProvided)return(0,n.millisToHrTime)(Date.now());let t=n.otperformance.now()-this._performanceStartTime;return(0,n.addHrTimes)(this.startTime,(0,n.millisToHrTime)(t))}isRecording(){return this._ended===!1}recordException(e,n){let a={};typeof e==`string`?a[r.ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?a[r.ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(a[r.ATTR_EXCEPTION_TYPE]=e.name),e.message&&(a[r.ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(a[r.ATTR_EXCEPTION_STACKTRACE]=e.stack)),a[r.ATTR_EXCEPTION_TYPE]||a[r.ATTR_EXCEPTION_MESSAGE]?this.addEvent(i.ExceptionEventName,a,n):t.diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);t.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let n=this._attributeValueLengthLimit;return n<=0?(t.diag.warn(`Attribute value limit must be positive, got ${n}`),e):typeof e==`string`?this._truncateToLimitUtil(e,n):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,n):e):e}}})),require_Sampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=void 0,(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(e.SamplingDecision||={})})),require_AlwaysOffSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOffSampler=void 0;let t=require_Sampler();e.AlwaysOffSampler=class{shouldSample(){return{decision:t.SamplingDecision.NOT_RECORD}}toString(){return`AlwaysOffSampler`}}})),require_AlwaysOnSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOnSampler=void 0;let t=require_Sampler();e.AlwaysOnSampler=class{shouldSample(){return{decision:t.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}}})),require_ParentBasedSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ParentBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_AlwaysOffSampler(),i=require_AlwaysOnSampler();e.ParentBasedSampler=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||=((0,n.globalErrorHandler)(Error(`ParentBasedSampler must have a root sampler configured`)),new i.AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new i.AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new r.AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new i.AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new r.AlwaysOffSampler}shouldSample(e,n,r,i,a,o){let s=t.trace.getSpanContext(e);return!s||!(0,t.isSpanContextValid)(s)?this._root.shouldSample(e,n,r,i,a,o):s.isRemote?s.traceFlags&t.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,n,r,i,a,o):this._remoteParentNotSampled.shouldSample(e,n,r,i,a,o):s.traceFlags&t.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,n,r,i,a,o):this._localParentNotSampled.shouldSample(e,n,r,i,a,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}})),require_TraceIdRatioBasedSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceIdRatioBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_Sampler();e.TraceIdRatioBasedSampler=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,r){return{decision:(0,t.isValidTraceId)(r)&&this._accumulate(r)<this._upperBound?n.SamplingDecision.RECORD_AND_SAMPLED:n.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let n=0;n<e.length/8;n++){let r=n*8,i=parseInt(e.slice(r,r+8),16);t=(t^i)>>>0}return t}}})),require_config=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildSamplerFromEnv=e.loadDefaultConfig=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_AlwaysOffSampler(),i=require_AlwaysOnSampler(),a=require_ParentBasedSampler(),o=require_TraceIdRatioBasedSampler();var s;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(s||={});let c=1;function l(){return{sampler:u(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}e.loadDefaultConfig=l;function u(){let e=(0,n.getStringFromEnv)(`OTEL_TRACES_SAMPLER`)??s.ParentBasedAlwaysOn;switch(e){case s.AlwaysOn:return new i.AlwaysOnSampler;case s.AlwaysOff:return new r.AlwaysOffSampler;case s.ParentBasedAlwaysOn:return new a.ParentBasedSampler({root:new i.AlwaysOnSampler});case s.ParentBasedAlwaysOff:return new a.ParentBasedSampler({root:new r.AlwaysOffSampler});case s.TraceIdRatio:return new o.TraceIdRatioBasedSampler(d());case s.ParentBasedTraceIdRatio:return new a.ParentBasedSampler({root:new o.TraceIdRatioBasedSampler(d())});default:return t.diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${s.ParentBasedAlwaysOn}".`),new a.ParentBasedSampler({root:new i.AlwaysOnSampler})}}e.buildSamplerFromEnv=u;function d(){let e=(0,n.getNumberFromEnv)(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1.`),1):e<0||e>1?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to 1.`),1):e}})),require_utility=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.mergeConfig=e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=void 0;let t=require_config(),n=require_src$14();e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function r(e){let n={sampler:(0,t.buildSamplerFromEnv)()},r=(0,t.loadDefaultConfig)(),i=Object.assign({},r,n,e);return i.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),i.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),i}e.mergeConfig=r;function i(t){let r=Object.assign({},t.spanLimits);return r.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??e.DEFAULT_ATTRIBUTE_COUNT_LIMIT,r.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},t,{spanLimits:r})}e.reconfigureLimits=i})),require_BatchSpanProcessorBase=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessorBase=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14();e.BatchSpanProcessorBase=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,r){this._exporter=e,this._maxExportBatchSize=typeof r?.maxExportBatchSize==`number`?r.maxExportBatchSize:(0,n.getNumberFromEnv)(`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=typeof r?.maxQueueSize==`number`?r.maxQueueSize:(0,n.getNumberFromEnv)(`OTEL_BSP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis==`number`?r.scheduledDelayMillis:(0,n.getNumberFromEnv)(`OTEL_BSP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis==`number`?r.exportTimeoutMillis:(0,n.getNumberFromEnv)(`OTEL_BSP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&t.diag.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(t.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=r;e<t;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,r)=>{let i=setTimeout(()=>{r(Error(`Timeout`))},this._exportTimeoutMillis);t.context.with((0,n.suppressTracing)(t.context.active()),()=>{let t;this._finishedSpans.length<=this._maxExportBatchSize?(t=this._finishedSpans,this._finishedSpans=[]):t=this._finishedSpans.splice(0,this._maxExportBatchSize);let a=()=>this._exporter.export(t,t=>{clearTimeout(i),t.code===n.ExportResultCode.SUCCESS?e():r(t.error??Error(`BatchSpanProcessor: span export failed`))}),o=null;for(let e=0,n=t.length;e<n;e++){let n=t[e];n.resource.asyncAttributesPending&&n.resource.waitForAsyncAttributes&&(o??=[],o.push(n.resource.waitForAsyncAttributes()))}o===null?a():Promise.all(o).then(a,e=>{(0,n.globalErrorHandler)(e),r(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,(0,n.globalErrorHandler)(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}})),require_BatchSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessor=void 0;let t=require_BatchSpanProcessorBase();e.BatchSpanProcessor=class extends t.BatchSpanProcessorBase{onShutdown(){}}})),require_RandomIdGenerator=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=void 0;let t=8,n=16;e.RandomIdGenerator=class{generateTraceId=i(16);generateSpanId=i(8)};let r=Buffer.allocUnsafe(16);function i(e){return function(){for(let t=0;t<e/4;t++)r.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(r[t]>0);t++)t===e-1&&(r[e-1]=1);return r.toString(`hex`,0,e)}}})),require_node$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_BatchSpanProcessor();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}});var n=require_RandomIdGenerator();Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return n.RandomIdGenerator}})})),require_platform=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_node$1();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return t.RandomIdGenerator}})})),require_semconv=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.METRIC_OTEL_SDK_SPAN_STARTED=e.METRIC_OTEL_SDK_SPAN_LIVE=e.ATTR_OTEL_SPAN_SAMPLING_RESULT=e.ATTR_OTEL_SPAN_PARENT_ORIGIN=void 0,e.ATTR_OTEL_SPAN_PARENT_ORIGIN=`otel.span.parent.origin`,e.ATTR_OTEL_SPAN_SAMPLING_RESULT=`otel.span.sampling_result`,e.METRIC_OTEL_SDK_SPAN_LIVE=`otel.sdk.span.live`,e.METRIC_OTEL_SDK_SPAN_STARTED=`otel.sdk.span.started`})),require_TracerMetrics=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TracerMetrics=void 0;let t=require_Sampler(),n=require_semconv();e.TracerMetrics=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(n.METRIC_OTEL_SDK_SPAN_STARTED,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(n.METRIC_OTEL_SDK_SPAN_LIVE,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,a){let o=i(a);if(this.startedSpans.add(1,{[n.ATTR_OTEL_SPAN_PARENT_ORIGIN]:r(e),[n.ATTR_OTEL_SPAN_SAMPLING_RESULT]:o}),a===t.SamplingDecision.NOT_RECORD)return()=>{};let s={[n.ATTR_OTEL_SPAN_SAMPLING_RESULT]:o};return this.liveSpans.add(1,s),()=>{this.liveSpans.add(-1,s)}}};function r(e){return e?e.isRemote?`remote`:`local`:`none`}function i(e){switch(e){case t.SamplingDecision.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case t.SamplingDecision.RECORD:return`RECORD_ONLY`;case t.SamplingDecision.NOT_RECORD:return`DROP`}}})),require_version=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`})),require_Tracer=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Tracer=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_Span(),i=require_utility(),a=require_platform(),o=require_TracerMetrics(),s=require_version();e.Tracer=class{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,n,r,c){let l=(0,i.mergeConfig)(n);this._sampler=l.sampler,this._generalLimits=l.generalLimits,this._spanLimits=l.spanLimits,this._idGenerator=n.idGenerator||new a.RandomIdGenerator,this._resource=r,this._spanProcessor=c,this.instrumentationScope=e;let u=l.meterProvider?l.meterProvider.getMeter(`@opentelemetry/sdk-trace`,s.VERSION):t.createNoopMeter();this._tracerMetrics=new o.TracerMetrics(u)}startSpan(e,i={},a=t.context.active()){i.root&&(a=t.trace.deleteSpan(a));let o=t.trace.getSpan(a);if((0,n.isTracingSuppressed)(a))return t.diag.debug(`Instrumentation suppressed, returning Noop Span`),t.trace.wrapSpanContext(t.INVALID_SPAN_CONTEXT);let s=o?.spanContext(),c=this._idGenerator.generateSpanId(),l,u,d;!s||!t.trace.isSpanContextValid(s)?u=this._idGenerator.generateTraceId():(u=s.traceId,d=s.traceState,l=s);let f=i.kind??t.SpanKind.INTERNAL,p=(i.links??[]).map(e=>({context:e.context,attributes:(0,n.sanitizeAttributes)(e.attributes)})),m=(0,n.sanitizeAttributes)(i.attributes),h=this._sampler.shouldSample(a,u,e,f,m,p),g=this._tracerMetrics.startSpan(s,h.decision);d=h.traceState??d;let _=h.decision===t.SamplingDecision.RECORD_AND_SAMPLED?t.TraceFlags.SAMPLED:t.TraceFlags.NONE,v={traceId:u,spanId:c,traceFlags:_,traceState:d};if(h.decision===t.SamplingDecision.NOT_RECORD)return t.diag.debug(`Recording is off, propagating context in a non-recording span`),t.trace.wrapSpanContext(v);let y=(0,n.sanitizeAttributes)(Object.assign(m,h.attributes));return new r.SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:a,spanContext:v,name:e,kind:f,links:p,parentSpanContext:l,attributes:y,startTime:i.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:g})}startActiveSpan(e,n,r,i){let a,o,s;if(arguments.length<2)return;arguments.length===2?s=n:arguments.length===3?(a=n,s=r):(a=n,o=r,s=i);let c=o??t.context.active(),l=this.startSpan(e,a,c),u=t.trace.setSpan(c,l);return t.context.with(u,s,void 0,l)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}})),require_MultiSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiSpanProcessor=void 0;let t=require_src$14();e.MultiSpanProcessor=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(n=>{Promise.all(e).then(()=>{n()}).catch(e=>{(0,t.globalErrorHandler)(e||Error(`MultiSpanProcessor: forceFlush failed`)),n()})})}onStart(e,t){for(let n of this._spanProcessors)n.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,n)=>{Promise.all(e).then(()=>{t()},n)})}}})),require_BasicTracerProvider=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BasicTracerProvider=e.ForceFlushState=void 0;let t=require_src$14(),n=require_src$3(),r=require_Tracer(),i=require_config(),a=require_MultiSpanProcessor(),o=require_utility();var s;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(s=e.ForceFlushState||={}),e.BasicTracerProvider=class{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){let r=(0,t.merge)({},(0,i.loadDefaultConfig)(),(0,o.reconfigureLimits)(e));this._resource=r.resource??(0,n.defaultResource)(),this._config=Object.assign({},r,{resource:this._resource});let s=[];e.spanProcessors?.length&&s.push(...e.spanProcessors),this._activeSpanProcessor=new a.MultiSpanProcessor(s)}getTracer(e,t,n){let i=`${e}@${t||``}:${n?.schemaUrl||``}`;return this._tracers.has(i)||this._tracers.set(i,new r.Tracer({name:e,version:t,schemaUrl:n?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(i)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(n=>{let r,i=setTimeout(()=>{n(Error(`Span processor did not completed within timeout period of ${e} ms`)),r=s.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),r!==s.timeout&&(r=s.resolved,n(r))}).catch(e=>{clearTimeout(i),r=s.error,n(e)})}));return new Promise((e,n)=>{Promise.all(t).then(t=>{let r=t.filter(e=>e!==s.resolved);r.length>0?n(r):e()}).catch(e=>n([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}})),require_ConsoleSpanExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleSpanExporter=void 0;let t=require_src$14();e.ConsoleSpanExporter=class{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:(0,t.hrTimeToMicroseconds)(e.startTime),duration:(0,t.hrTimeToMicroseconds)(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,n){for(let t of e)console.dir(this._exportInfo(t),{depth:3});if(n)return n({code:t.ExportResultCode.SUCCESS})}}})),require_InMemorySpanExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemorySpanExporter=void 0;let t=require_src$14();e.InMemorySpanExporter=class{_finishedSpans=[];_stopped=!1;export(e,n){if(this._stopped)return n({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedSpans.push(...e),setTimeout(()=>n({code:t.ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}})),require_SimpleSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleSpanProcessor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14();e.SimpleSpanProcessor=class{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)===0)return;let r=this._doExport(e).catch(e=>(0,n.globalErrorHandler)(e));this._pendingExports.add(r),r.finally(()=>this._pendingExports.delete(r))}async _doExport(e){e.resource.asyncAttributesPending&&await e.resource.waitForAsyncAttributes?.();let t=await n.internal._export(this._exporter,[e]);if(t.code!==n.ExportResultCode.SUCCESS)throw t.error??Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),require_NoopSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopSpanProcessor=void 0,e.NoopSpanProcessor=class{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}})),require_src$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=e.TraceIdRatioBasedSampler=e.ParentBasedSampler=e.AlwaysOnSampler=e.AlwaysOffSampler=e.NoopSpanProcessor=e.SimpleSpanProcessor=e.InMemorySpanExporter=e.ConsoleSpanExporter=e.RandomIdGenerator=e.BatchSpanProcessor=e.BasicTracerProvider=void 0;var t=require_BasicTracerProvider();Object.defineProperty(e,`BasicTracerProvider`,{enumerable:!0,get:function(){return t.BasicTracerProvider}});var n=require_platform();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return n.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return n.RandomIdGenerator}});var r=require_ConsoleSpanExporter();Object.defineProperty(e,`ConsoleSpanExporter`,{enumerable:!0,get:function(){return r.ConsoleSpanExporter}});var i=require_InMemorySpanExporter();Object.defineProperty(e,`InMemorySpanExporter`,{enumerable:!0,get:function(){return i.InMemorySpanExporter}});var a=require_SimpleSpanProcessor();Object.defineProperty(e,`SimpleSpanProcessor`,{enumerable:!0,get:function(){return a.SimpleSpanProcessor}});var o=require_NoopSpanProcessor();Object.defineProperty(e,`NoopSpanProcessor`,{enumerable:!0,get:function(){return o.NoopSpanProcessor}});var s=require_AlwaysOffSampler();Object.defineProperty(e,`AlwaysOffSampler`,{enumerable:!0,get:function(){return s.AlwaysOffSampler}});var c=require_AlwaysOnSampler();Object.defineProperty(e,`AlwaysOnSampler`,{enumerable:!0,get:function(){return c.AlwaysOnSampler}});var l=require_ParentBasedSampler();Object.defineProperty(e,`ParentBasedSampler`,{enumerable:!0,get:function(){return l.ParentBasedSampler}});var u=require_TraceIdRatioBasedSampler();Object.defineProperty(e,`TraceIdRatioBasedSampler`,{enumerable:!0,get:function(){return u.TraceIdRatioBasedSampler}});var d=require_Sampler();Object.defineProperty(e,`SamplingDecision`,{enumerable:!0,get:function(){return d.SamplingDecision}})}));init_esm$2();var import_src$1=require_src$15(),import_src$2=require_src$14(),import_src$3=require_src$5(),import_src$4=require_src$4(),import_src$5=require_src$3(),import_src$6=require_src$2(),import_src$7=require_src$1();init_esm$1();const TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src$1.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let n=new import_src$7.BasicTracerProvider({resource:e,spanProcessors:[new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter)]});trace.setGlobalTracerProvider(n),propagation.setGlobalPropagator(new import_src$2.W3CTraceContextPropagator);let r=new import_src$6.MeterProvider({resource:e,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]});metrics.setGlobalMeterProvider(r),tracerProvider=n,meterProvider=r,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,n){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,n){return getTracer().startActiveSpan(e,t??{},e=>{try{return n(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}const log$5=getLogger(`agent-sessions`);function applyAgentMarkdownWrite(e,t,n){withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,n))}function applyAgentMarkdownWriteInner(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=yXmlFragmentToProseMirrorRootNode(r,schema).toJSON(),s=mdManager.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:l,body:u}=stripFrontmatter(t),d,f;switch(n){case`replace`:d=l||c,f=u.trim();break;case`prepend`:d=c,f=`${u.trim()}\n\n${s}`;break;case`append`:d=c,f=s.trim()?`${s}\n\n${u.trim()}\n`:`${u.trim()}\n`;break}let p=mdManager.parseWithFallback(f);updateYFragment(e,r,schema.nodeFromJSON(p),{mapping:new Map,isOMark:new Map}),d!==c&&a.set(`frontmatter`,d);let m=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(r,schema).toJSON()),h=prependFrontmatter(d,m);applyFastDiff(i,i.toString(),h)}catch(r){throw log$5.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function applyAgentUndo(e,t){return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let n=applyAgentUndoInner(e,t);return setActiveSpanAttributes({"agent.undo_effective":n}),n})}function applyAgentUndoInner(e,t){let{dc:n,um:r,undoOrigin:i}=e,a=n.document,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=a.getMap(`metadata`),l=!1;return a.transact(()=>{if(t===`last`){if(r.undoStack.length===0)return;r.undo(),l=!0}else for(;r.undoStack.length>0;)r.undo(),l=!0;let{body:e,frontmatter:n}=stripFrontmatter(s.toString()),i=mdManager.parseWithFallback(e);updateYFragment(a,o,schema.nodeFromJSON(i),{mapping:new Map,isOMark:new Map});let u=c.get(`frontmatter`)??``,d=n||u;n&&n!==u&&c.set(`frontmatter`,d);let f=prependFrontmatter(d,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(o,schema).toJSON()));applyFastDiff(s,s.toString(),f)},i),l}function createSessionOrigin(e,t,n){let r={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(r.agent_type=t),n!==void 0&&(r.principal=n),Object.freeze(r);let i={source:`local`,skipStoreHooks:!1,context:r};return Object.freeze(i),i}function createUndoOrigin(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}var AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}async getSession(e,t=`claude-1`,n){if(isSystemDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return i;let a=this.pendingSessions.get(r);if(a)return a;let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=createSessionOrigin(i,r,n?.principalId),o=createUndoOrigin(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s),l=new UndoManager([c.document.getText(`source`),c.document.getMap(`metadata`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0});return log$5.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(r.um.destroy(),await r.dc.disconnect(),this.sessions.delete(n),log$5.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of r){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$5.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of n){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$5.error({err:t,docName:e},`[agent-session] Failed to close session for doc ${e}`)}}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);if(t)try{t.um.destroy(),await t.dc.disconnect(),this.sessions.delete(e)}catch(t){log$5.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}};const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function resolveShadowDir(e){return resolve(e,`.git/open-knowledge`)}function getShadowRepoPath(e){let t=resolveShadowDir(e);return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let n of e.split(`
38
+ `,(0,r.getConflictResolutionRecipe)(i,e))}return a}}})),require_MultiWritableMetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,n,r){this._backingStorages.forEach(i=>{i.record(e,t,n,r)})}}})),require_ObservableResult=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_HashMap(),r=require_Instruments();e.ObservableResultImpl=class{_buffer=new n.AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,i,a={}){if(!(0,r.isObservableInstrument)(e))return;let o=this._buffer.get(e);if(o??(o=new n.AttributeHashMap,this._buffer.set(e,o)),typeof i!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${i}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(i)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),i=Math.trunc(i),!Number.isInteger(i))||o.set(a,i)}}})),require_ObservableRegistry=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_Instruments(),r=require_ObservableResult(),i=require_utils$1();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,r){let i=new Set(r.filter(n.isObservableInstrument));if(i.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,r);return}this._findBatchCallback(e,i)>=0||this._batchCallbacks.push({callback:e,instruments:i})}removeBatchCallback(e,t){let r=new Set(t.filter(n.isObservableInstrument)),i=this._findBatchCallback(e,r);i<0||this._batchCallbacks.splice(i,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:a})=>{let o=new r.ObservableResultImpl(a._descriptor.name,a._descriptor.valueType),s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a._metricStorages.forEach(t=>{t.record(o._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:a})=>{let o=new r.BatchObservableResultImpl,s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a.forEach(t=>{let n=o._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&(0,i.setEquals)(n.instruments,t))}}})),require_SyncMetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage(),n=require_DeltaMetricProcessor(),r=require_TemporalMetricProcessor();e.SyncMetricStorage=class extends t.MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,i,a,o){super(e),this._aggregationCardinalityLimit=o,this._deltaMetricStorage=new n.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new r.TemporalMetricProcessor(t,a),this._attributesProcessor=i}record(e,t,n,r){t=this._attributesProcessor.process(t,n),this._deltaMetricStorage.record(e,t,n,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),require_AttributesProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},n=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},r=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(n[t]=e[t])}),n}},i=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(n[t]=e[t])}),n}};function a(){return l}e.createNoopAttributesProcessor=a;function o(e){return new n(e)}e.createMultiAttributesProcessor=o;function s(e){return new r(e)}e.createAllowListAttributesProcessor=s;function c(e){return new i(e)}e.createDenyListAttributesProcessor=c;let l=new t})),require_MeterSharedState=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor(),n=require_Meter(),r=require_AsyncMetricStorage(),i=require_MetricStorageRegistry(),a=require_MultiWritableMetricStorage(),o=require_ObservableRegistry(),s=require_SyncMetricStorage(),c=require_AttributesProcessor();e.MeterSharedState=class{metricStorageRegistry=new i.MetricStorageRegistry;observableRegistry=new o.ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new n.Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,s.SyncMetricStorage);return t.length===1?t[0]:new a.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,r.AsyncMetricStorage)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,n){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{let i=(0,t.createInstrumentDescriptorWithView)(r,e),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let o=new n(i,r.aggregation.createAggregator(i),r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(r.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(i!=null)return i;let a=r.createAggregator(e),o=t.selectCardinalityLimit(e.type),s=new n(e,a,(0,c.createNoopAttributesProcessor)(),[t],o);return this.metricStorageRegistry.registerForCollector(t,s),s});r=r.concat(t)}return r}}})),require_MeterProviderSharedState=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$1(),n=require_ViewRegistry(),r=require_MeterSharedState(),i=require_AggregationOption();e.MeterProviderSharedState=class{viewRegistry=new n.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let n=(0,t.instrumentationScopeId)(e),i=this.meterSharedStates.get(n);return i??(i=new r.MeterSharedState(this,e),this.meterSharedStates.set(n,i)),i}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,(0,i.toAggregation)(n.selectAggregation(e))]);return t}}})),require_MetricCollector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$14();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let n=(0,t.millisToHrTime)(Date.now()),r=[],i=[],a=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let a=await t.collect(this,n,e);a?.scopeMetrics!=null&&r.push(a.scopeMetrics),a?.errors!=null&&i.push(...a.errors)});return await Promise.all(a),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:i}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate(),n=require_AttributesProcessor(),r=require_InstrumentSelector(),i=require_MeterSelector(),a=require_AggregationOption();function o(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function s(e){if(o(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){s(e),e.attributesProcessors==null?this.attributesProcessor=(0,n.createNoopAttributesProcessor)():this.attributesProcessor=(0,n.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,a.toAggregation)(e.aggregation??{type:a.AggregationType.DEFAULT}),this.instrumentSelector=new r.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new i.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$3(),r=require_MeterProviderSharedState(),i=require_MetricCollector(),a=require_View();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new r.MeterProviderSharedState(e?.resource??(0,n.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new a.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new i.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,n=``,r={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:n,schemaUrl:r.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=require_MetricData();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=require_MetricReader();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=require_PeriodicExportingMetricReader();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=require_InMemoryMetricExporter();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=require_ConsoleMetricExporter();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=require_MeterProvider();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=require_AggregationOption();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=require_AttributesProcessor();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=require_utils$1();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),require_enums=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExceptionEventName=void 0,e.ExceptionEventName=`exception`})),require_Span=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SpanImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=(init_esm$1(),__toCommonJS(esm_exports$1)),i=require_enums();e.SpanImpl=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:t.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=n.otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+n.otperformance.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,r){if(r==null||this._isSpanEnded())return this;if(e.length===0)return t.diag.warn(`Invalid attribute key: ${e}`),this;if(!(0,n.isAttributeValue)(r))return t.diag.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:i}=this._spanLimits,a=!Object.prototype.hasOwnProperty.call(this.attributes,e);return i!==void 0&&this._attributesCount>=i&&a?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(r),a&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,r,i){if(this._isSpanEnded())return this;let{eventCountLimit:a}=this._spanLimits;if(a===0)return t.diag.warn(`No events allowed.`),this._droppedEventsCount++,this;a!==void 0&&this.events.length>=a&&(this._droppedEventsCount===0&&t.diag.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),(0,n.isTimeInput)(r)&&((0,n.isTimeInput)(i)||(i=r),r=void 0);let o=(0,n.sanitizeAttributes)(r),{attributePerEventCountLimit:s}=this._spanLimits,c={},l=0,u=0;for(let e in o){if(!Object.prototype.hasOwnProperty.call(o,e))continue;let t=o[e];if(s!==void 0&&u>=s){l++;continue}c[e]=this._truncateToSize(t),u++}return this.events.push({name:e,attributes:c,time:this._getTime(i),droppedAttributesCount:l}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:r}=this._spanLimits;if(r===0)return this._droppedLinksCount++,this;r!==void 0&&this.links.length>=r&&(this._droppedLinksCount===0&&t.diag.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:i}=this._spanLimits,a=(0,n.sanitizeAttributes)(e.attributes),o={},s=0,c=0;for(let e in a){if(!Object.prototype.hasOwnProperty.call(a,e))continue;let t=a[e];if(i!==void 0&&c>=i){s++;continue}o[e]=this._truncateToSize(t),c++}let l={context:e.context};return c>0&&(l.attributes=o),s>0&&(l.droppedAttributesCount=s),this.links.push(l),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===t.SpanStatusCode.UNSET||this.status.code===t.SpanStatusCode.OK)return this;let n={code:e.code};return e.code===t.SpanStatusCode.ERROR&&(typeof e.message==`string`?n.message=e.message:e.message!=null&&t.diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=n,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){if(this._isSpanEnded()){t.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=(0,n.hrTimeDuration)(this.startTime,this.endTime),this._duration[0]<0&&(t.diag.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&t.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&t.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e==`number`&&e<=n.otperformance.now())return(0,n.hrTime)(e+this._performanceOffset);if(typeof e==`number`)return(0,n.millisToHrTime)(e);if(e instanceof Date)return(0,n.millisToHrTime)(e.getTime());if((0,n.isTimeInputHrTime)(e))return e;if(this._startTimeProvided)return(0,n.millisToHrTime)(Date.now());let t=n.otperformance.now()-this._performanceStartTime;return(0,n.addHrTimes)(this.startTime,(0,n.millisToHrTime)(t))}isRecording(){return this._ended===!1}recordException(e,n){let a={};typeof e==`string`?a[r.ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?a[r.ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(a[r.ATTR_EXCEPTION_TYPE]=e.name),e.message&&(a[r.ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(a[r.ATTR_EXCEPTION_STACKTRACE]=e.stack)),a[r.ATTR_EXCEPTION_TYPE]||a[r.ATTR_EXCEPTION_MESSAGE]?this.addEvent(i.ExceptionEventName,a,n):t.diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);t.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let n=this._attributeValueLengthLimit;return n<=0?(t.diag.warn(`Attribute value limit must be positive, got ${n}`),e):typeof e==`string`?this._truncateToLimitUtil(e,n):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,n):e):e}}})),require_Sampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=void 0,(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(e.SamplingDecision||={})})),require_AlwaysOffSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOffSampler=void 0;let t=require_Sampler();e.AlwaysOffSampler=class{shouldSample(){return{decision:t.SamplingDecision.NOT_RECORD}}toString(){return`AlwaysOffSampler`}}})),require_AlwaysOnSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOnSampler=void 0;let t=require_Sampler();e.AlwaysOnSampler=class{shouldSample(){return{decision:t.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}}})),require_ParentBasedSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ParentBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_AlwaysOffSampler(),i=require_AlwaysOnSampler();e.ParentBasedSampler=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||=((0,n.globalErrorHandler)(Error(`ParentBasedSampler must have a root sampler configured`)),new i.AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new i.AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new r.AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new i.AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new r.AlwaysOffSampler}shouldSample(e,n,r,i,a,o){let s=t.trace.getSpanContext(e);return!s||!(0,t.isSpanContextValid)(s)?this._root.shouldSample(e,n,r,i,a,o):s.isRemote?s.traceFlags&t.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,n,r,i,a,o):this._remoteParentNotSampled.shouldSample(e,n,r,i,a,o):s.traceFlags&t.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,n,r,i,a,o):this._localParentNotSampled.shouldSample(e,n,r,i,a,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}})),require_TraceIdRatioBasedSampler=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceIdRatioBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_Sampler();e.TraceIdRatioBasedSampler=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,r){return{decision:(0,t.isValidTraceId)(r)&&this._accumulate(r)<this._upperBound?n.SamplingDecision.RECORD_AND_SAMPLED:n.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let n=0;n<e.length/8;n++){let r=n*8,i=parseInt(e.slice(r,r+8),16);t=(t^i)>>>0}return t}}})),require_config=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildSamplerFromEnv=e.loadDefaultConfig=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_AlwaysOffSampler(),i=require_AlwaysOnSampler(),a=require_ParentBasedSampler(),o=require_TraceIdRatioBasedSampler();var s;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(s||={});let c=1;function l(){return{sampler:u(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}e.loadDefaultConfig=l;function u(){let e=(0,n.getStringFromEnv)(`OTEL_TRACES_SAMPLER`)??s.ParentBasedAlwaysOn;switch(e){case s.AlwaysOn:return new i.AlwaysOnSampler;case s.AlwaysOff:return new r.AlwaysOffSampler;case s.ParentBasedAlwaysOn:return new a.ParentBasedSampler({root:new i.AlwaysOnSampler});case s.ParentBasedAlwaysOff:return new a.ParentBasedSampler({root:new r.AlwaysOffSampler});case s.TraceIdRatio:return new o.TraceIdRatioBasedSampler(d());case s.ParentBasedTraceIdRatio:return new a.ParentBasedSampler({root:new o.TraceIdRatioBasedSampler(d())});default:return t.diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${s.ParentBasedAlwaysOn}".`),new a.ParentBasedSampler({root:new i.AlwaysOnSampler})}}e.buildSamplerFromEnv=u;function d(){let e=(0,n.getNumberFromEnv)(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1.`),1):e<0||e>1?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to 1.`),1):e}})),require_utility=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.mergeConfig=e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=void 0;let t=require_config(),n=require_src$14();e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function r(e){let n={sampler:(0,t.buildSamplerFromEnv)()},r=(0,t.loadDefaultConfig)(),i=Object.assign({},r,n,e);return i.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),i.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),i}e.mergeConfig=r;function i(t){let r=Object.assign({},t.spanLimits);return r.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??e.DEFAULT_ATTRIBUTE_COUNT_LIMIT,r.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??(0,n.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,n.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},t,{spanLimits:r})}e.reconfigureLimits=i})),require_BatchSpanProcessorBase=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessorBase=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14();e.BatchSpanProcessorBase=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,r){this._exporter=e,this._maxExportBatchSize=typeof r?.maxExportBatchSize==`number`?r.maxExportBatchSize:(0,n.getNumberFromEnv)(`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=typeof r?.maxQueueSize==`number`?r.maxQueueSize:(0,n.getNumberFromEnv)(`OTEL_BSP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis==`number`?r.scheduledDelayMillis:(0,n.getNumberFromEnv)(`OTEL_BSP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis==`number`?r.exportTimeoutMillis:(0,n.getNumberFromEnv)(`OTEL_BSP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&t.diag.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(t.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=r;e<t;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,r)=>{let i=setTimeout(()=>{r(Error(`Timeout`))},this._exportTimeoutMillis);t.context.with((0,n.suppressTracing)(t.context.active()),()=>{let t;this._finishedSpans.length<=this._maxExportBatchSize?(t=this._finishedSpans,this._finishedSpans=[]):t=this._finishedSpans.splice(0,this._maxExportBatchSize);let a=()=>this._exporter.export(t,t=>{clearTimeout(i),t.code===n.ExportResultCode.SUCCESS?e():r(t.error??Error(`BatchSpanProcessor: span export failed`))}),o=null;for(let e=0,n=t.length;e<n;e++){let n=t[e];n.resource.asyncAttributesPending&&n.resource.waitForAsyncAttributes&&(o??=[],o.push(n.resource.waitForAsyncAttributes()))}o===null?a():Promise.all(o).then(a,e=>{(0,n.globalErrorHandler)(e),r(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,(0,n.globalErrorHandler)(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}})),require_BatchSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessor=void 0;let t=require_BatchSpanProcessorBase();e.BatchSpanProcessor=class extends t.BatchSpanProcessorBase{onShutdown(){}}})),require_RandomIdGenerator=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=void 0;let t=8,n=16;e.RandomIdGenerator=class{generateTraceId=i(16);generateSpanId=i(8)};let r=Buffer.allocUnsafe(16);function i(e){return function(){for(let t=0;t<e/4;t++)r.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(r[t]>0);t++)t===e-1&&(r[e-1]=1);return r.toString(`hex`,0,e)}}})),require_node$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_BatchSpanProcessor();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}});var n=require_RandomIdGenerator();Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return n.RandomIdGenerator}})})),require_platform=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_node$1();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return t.RandomIdGenerator}})})),require_semconv=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.METRIC_OTEL_SDK_SPAN_STARTED=e.METRIC_OTEL_SDK_SPAN_LIVE=e.ATTR_OTEL_SPAN_SAMPLING_RESULT=e.ATTR_OTEL_SPAN_PARENT_ORIGIN=void 0,e.ATTR_OTEL_SPAN_PARENT_ORIGIN=`otel.span.parent.origin`,e.ATTR_OTEL_SPAN_SAMPLING_RESULT=`otel.span.sampling_result`,e.METRIC_OTEL_SDK_SPAN_LIVE=`otel.sdk.span.live`,e.METRIC_OTEL_SDK_SPAN_STARTED=`otel.sdk.span.started`})),require_TracerMetrics=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TracerMetrics=void 0;let t=require_Sampler(),n=require_semconv();e.TracerMetrics=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(n.METRIC_OTEL_SDK_SPAN_STARTED,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(n.METRIC_OTEL_SDK_SPAN_LIVE,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,a){let o=i(a);if(this.startedSpans.add(1,{[n.ATTR_OTEL_SPAN_PARENT_ORIGIN]:r(e),[n.ATTR_OTEL_SPAN_SAMPLING_RESULT]:o}),a===t.SamplingDecision.NOT_RECORD)return()=>{};let s={[n.ATTR_OTEL_SPAN_SAMPLING_RESULT]:o};return this.liveSpans.add(1,s),()=>{this.liveSpans.add(-1,s)}}};function r(e){return e?e.isRemote?`remote`:`local`:`none`}function i(e){switch(e){case t.SamplingDecision.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case t.SamplingDecision.RECORD:return`RECORD_ONLY`;case t.SamplingDecision.NOT_RECORD:return`DROP`}}})),require_version=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`})),require_Tracer=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Tracer=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14(),r=require_Span(),i=require_utility(),a=require_platform(),o=require_TracerMetrics(),s=require_version();e.Tracer=class{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,n,r,c){let l=(0,i.mergeConfig)(n);this._sampler=l.sampler,this._generalLimits=l.generalLimits,this._spanLimits=l.spanLimits,this._idGenerator=n.idGenerator||new a.RandomIdGenerator,this._resource=r,this._spanProcessor=c,this.instrumentationScope=e;let u=l.meterProvider?l.meterProvider.getMeter(`@opentelemetry/sdk-trace`,s.VERSION):t.createNoopMeter();this._tracerMetrics=new o.TracerMetrics(u)}startSpan(e,i={},a=t.context.active()){i.root&&(a=t.trace.deleteSpan(a));let o=t.trace.getSpan(a);if((0,n.isTracingSuppressed)(a))return t.diag.debug(`Instrumentation suppressed, returning Noop Span`),t.trace.wrapSpanContext(t.INVALID_SPAN_CONTEXT);let s=o?.spanContext(),c=this._idGenerator.generateSpanId(),l,u,d;!s||!t.trace.isSpanContextValid(s)?u=this._idGenerator.generateTraceId():(u=s.traceId,d=s.traceState,l=s);let f=i.kind??t.SpanKind.INTERNAL,p=(i.links??[]).map(e=>({context:e.context,attributes:(0,n.sanitizeAttributes)(e.attributes)})),m=(0,n.sanitizeAttributes)(i.attributes),h=this._sampler.shouldSample(a,u,e,f,m,p),g=this._tracerMetrics.startSpan(s,h.decision);d=h.traceState??d;let _=h.decision===t.SamplingDecision.RECORD_AND_SAMPLED?t.TraceFlags.SAMPLED:t.TraceFlags.NONE,v={traceId:u,spanId:c,traceFlags:_,traceState:d};if(h.decision===t.SamplingDecision.NOT_RECORD)return t.diag.debug(`Recording is off, propagating context in a non-recording span`),t.trace.wrapSpanContext(v);let y=(0,n.sanitizeAttributes)(Object.assign(m,h.attributes));return new r.SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:a,spanContext:v,name:e,kind:f,links:p,parentSpanContext:l,attributes:y,startTime:i.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:g})}startActiveSpan(e,n,r,i){let a,o,s;if(arguments.length<2)return;arguments.length===2?s=n:arguments.length===3?(a=n,s=r):(a=n,o=r,s=i);let c=o??t.context.active(),l=this.startSpan(e,a,c),u=t.trace.setSpan(c,l);return t.context.with(u,s,void 0,l)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}})),require_MultiSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiSpanProcessor=void 0;let t=require_src$14();e.MultiSpanProcessor=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(n=>{Promise.all(e).then(()=>{n()}).catch(e=>{(0,t.globalErrorHandler)(e||Error(`MultiSpanProcessor: forceFlush failed`)),n()})})}onStart(e,t){for(let n of this._spanProcessors)n.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,n)=>{Promise.all(e).then(()=>{t()},n)})}}})),require_BasicTracerProvider=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BasicTracerProvider=e.ForceFlushState=void 0;let t=require_src$14(),n=require_src$3(),r=require_Tracer(),i=require_config(),a=require_MultiSpanProcessor(),o=require_utility();var s;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(s=e.ForceFlushState||={}),e.BasicTracerProvider=class{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){let r=(0,t.merge)({},(0,i.loadDefaultConfig)(),(0,o.reconfigureLimits)(e));this._resource=r.resource??(0,n.defaultResource)(),this._config=Object.assign({},r,{resource:this._resource});let s=[];e.spanProcessors?.length&&s.push(...e.spanProcessors),this._activeSpanProcessor=new a.MultiSpanProcessor(s)}getTracer(e,t,n){let i=`${e}@${t||``}:${n?.schemaUrl||``}`;return this._tracers.has(i)||this._tracers.set(i,new r.Tracer({name:e,version:t,schemaUrl:n?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(i)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(n=>{let r,i=setTimeout(()=>{n(Error(`Span processor did not completed within timeout period of ${e} ms`)),r=s.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),r!==s.timeout&&(r=s.resolved,n(r))}).catch(e=>{clearTimeout(i),r=s.error,n(e)})}));return new Promise((e,n)=>{Promise.all(t).then(t=>{let r=t.filter(e=>e!==s.resolved);r.length>0?n(r):e()}).catch(e=>n([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}})),require_ConsoleSpanExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleSpanExporter=void 0;let t=require_src$14();e.ConsoleSpanExporter=class{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:(0,t.hrTimeToMicroseconds)(e.startTime),duration:(0,t.hrTimeToMicroseconds)(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,n){for(let t of e)console.dir(this._exportInfo(t),{depth:3});if(n)return n({code:t.ExportResultCode.SUCCESS})}}})),require_InMemorySpanExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemorySpanExporter=void 0;let t=require_src$14();e.InMemorySpanExporter=class{_finishedSpans=[];_stopped=!1;export(e,n){if(this._stopped)return n({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedSpans.push(...e),setTimeout(()=>n({code:t.ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}})),require_SimpleSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleSpanProcessor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),n=require_src$14();e.SimpleSpanProcessor=class{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)===0)return;let r=this._doExport(e).catch(e=>(0,n.globalErrorHandler)(e));this._pendingExports.add(r),r.finally(()=>this._pendingExports.delete(r))}async _doExport(e){e.resource.asyncAttributesPending&&await e.resource.waitForAsyncAttributes?.();let t=await n.internal._export(this._exporter,[e]);if(t.code!==n.ExportResultCode.SUCCESS)throw t.error??Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),require_NoopSpanProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopSpanProcessor=void 0,e.NoopSpanProcessor=class{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}})),require_src$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=e.TraceIdRatioBasedSampler=e.ParentBasedSampler=e.AlwaysOnSampler=e.AlwaysOffSampler=e.NoopSpanProcessor=e.SimpleSpanProcessor=e.InMemorySpanExporter=e.ConsoleSpanExporter=e.RandomIdGenerator=e.BatchSpanProcessor=e.BasicTracerProvider=void 0;var t=require_BasicTracerProvider();Object.defineProperty(e,`BasicTracerProvider`,{enumerable:!0,get:function(){return t.BasicTracerProvider}});var n=require_platform();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return n.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return n.RandomIdGenerator}});var r=require_ConsoleSpanExporter();Object.defineProperty(e,`ConsoleSpanExporter`,{enumerable:!0,get:function(){return r.ConsoleSpanExporter}});var i=require_InMemorySpanExporter();Object.defineProperty(e,`InMemorySpanExporter`,{enumerable:!0,get:function(){return i.InMemorySpanExporter}});var a=require_SimpleSpanProcessor();Object.defineProperty(e,`SimpleSpanProcessor`,{enumerable:!0,get:function(){return a.SimpleSpanProcessor}});var o=require_NoopSpanProcessor();Object.defineProperty(e,`NoopSpanProcessor`,{enumerable:!0,get:function(){return o.NoopSpanProcessor}});var s=require_AlwaysOffSampler();Object.defineProperty(e,`AlwaysOffSampler`,{enumerable:!0,get:function(){return s.AlwaysOffSampler}});var c=require_AlwaysOnSampler();Object.defineProperty(e,`AlwaysOnSampler`,{enumerable:!0,get:function(){return c.AlwaysOnSampler}});var l=require_ParentBasedSampler();Object.defineProperty(e,`ParentBasedSampler`,{enumerable:!0,get:function(){return l.ParentBasedSampler}});var u=require_TraceIdRatioBasedSampler();Object.defineProperty(e,`TraceIdRatioBasedSampler`,{enumerable:!0,get:function(){return u.TraceIdRatioBasedSampler}});var d=require_Sampler();Object.defineProperty(e,`SamplingDecision`,{enumerable:!0,get:function(){return d.SamplingDecision}})}));init_esm$2();var import_src$1=require_src$15(),import_src$2=require_src$14(),import_src$3=require_src$5(),import_src$4=require_src$4(),import_src$5=require_src$3(),import_src$6=require_src$2(),import_src$7=require_src$1();init_esm$1();const TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src$1.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let n=new import_src$7.BasicTracerProvider({resource:e,spanProcessors:[new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter)]});trace.setGlobalTracerProvider(n),propagation.setGlobalPropagator(new import_src$2.W3CTraceContextPropagator);let r=new import_src$6.MeterProvider({resource:e,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]});metrics.setGlobalMeterProvider(r),tracerProvider=n,meterProvider=r,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,n){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,n){return getTracer().startActiveSpan(e,t??{},e=>{try{return n(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}const log$5=getLogger(`agent-sessions`);function applyAgentMarkdownWrite(e,t,n){withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,n))}function applyAgentMarkdownWriteInner(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=yXmlFragmentToProseMirrorRootNode(r,schema).toJSON(),s=mdManager.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:l,body:u}=stripFrontmatter(t),d,f;switch(n){case`replace`:d=l||c,f=u.trim();break;case`prepend`:d=c,f=`${u.trim()}\n\n${s}`;break;case`append`:d=c,f=s.trim()?`${s}\n\n${u.trim()}\n`:`${u.trim()}\n`;break}let p=mdManager.parseWithFallback(f);updateYFragment(e,r,schema.nodeFromJSON(p),{mapping:new Map,isOMark:new Map}),d!==c&&a.set(`frontmatter`,d);let m=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(r,schema).toJSON()),h=prependFrontmatter(d,m);applyFastDiff(i,i.toString(),h)}catch(r){throw log$5.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function applyAgentUndo(e,t){return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let n=applyAgentUndoInner(e,t);return setActiveSpanAttributes({"agent.undo_effective":n}),n})}function applyAgentUndoInner(e,t){let{dc:n,um:r,undoOrigin:i}=e,a=n.document,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=a.getMap(`metadata`),l=!1;return a.transact(()=>{if(t===`last`){if(r.undoStack.length===0)return;r.undo(),l=!0}else for(;r.undoStack.length>0;)r.undo(),l=!0;let{body:e,frontmatter:n}=stripFrontmatter(s.toString()),i=mdManager.parseWithFallback(e);updateYFragment(a,o,schema.nodeFromJSON(i),{mapping:new Map,isOMark:new Map});let u=c.get(`frontmatter`)??``,d=n||u;n&&n!==u&&c.set(`frontmatter`,d);let f=prependFrontmatter(d,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(o,schema).toJSON()));applyFastDiff(s,s.toString(),f)},i),l}function createSessionOrigin(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function createUndoOrigin(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}var AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,n){if(isSystemDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return i;let a=this.pendingSessions.get(r);if(a)return a;let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=createSessionOrigin(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=createUndoOrigin(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s),l=new UndoManager([c.document.getText(`source`),c.document.getMap(`metadata`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),log$5.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(r.um.destroy(),await r.dc.disconnect(),this.sessions.delete(n),log$5.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of r){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$5.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of n){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$5.error({err:t,docName:e},`[agent-session] Failed to close session for doc ${e}`)}}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);if(t)try{t.um.destroy(),await t.dc.disconnect(),this.sessions.delete(e)}catch(t){log$5.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}};const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function resolveShadowDir(e){return resolve(e,`.git/open-knowledge`)}function getShadowRepoPath(e){let t=resolveShadowDir(e);return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let n of e.split(`
39
39
  `)){let e=n.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let n=JSON.parse(e.slice(17));if(typeof n==`object`&&n&&`id`in n&&typeof n.id==`string`&&`name`in n&&typeof n.name==`string`&&`docs`in n&&Array.isArray(n.docs)&&n.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in n)||typeof n.colorSeed==`string`)){let e=n;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(n)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
40
40
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let n;try{n=JSON.parse(e.slice(18))}catch{return null}if(typeof n!=`object`||!n)return null;let r=n,i=r.kind,a=r.metadata;if(typeof a!=`object`||!a)return null;let o=typeof r.docName==`string`?r.docName:null,s=typeof r.size==`number`&&Number.isFinite(r.size)?r.size:null;if(i===`bridge-merge-loss`){let e=a;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:o,size:s,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(i===`external-change-rescue`){let e=a;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:o,size:s,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,...n}=e,r=t&&t.length>0?{...n,summaries:t}:n;return`${OK_ACTOR_PREFIX}${JSON.stringify(r)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,n=typeof e.agent_session==`string`?e.agent_session:null,r;if(typeof e.writer_id==`string`&&e.writer_id.length>0)r=e.writer_id;else if(n)r=`agent-${n}`;else if(t)r=t;else switch(e.display_name){case`File System`:r=`file-system`;break;case`Git (upstream)`:r=`git-upstream`;break;default:r=`openknowledge-service`}let i=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0;return{v:1,writer_id:r,principal:t,agent_session:n,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...i&&i.length>0?{summaries:i}:{}}}function parseOkActors(e){if(!e)return[];let t=[];for(let n of e.split(`
41
41
  `)){let e=n.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=parseOkActorObject(r);i&&t.push(i)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const COMMIT_SUBJECT_MAX_LEN=72;function composeCommitSubject(e,t){if(t.length===0)return e;if(t.length>=2)return`${e} (${t.length} edits)`;let[n]=t;if(n===void 0)return e;let r=`${e} — ${n}`;if(r.length<=72)return r;let i=`${e} — `,a=72-i.length-1;return a<=0?r.slice(0,72):`${i}${n.slice(0,a)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_utils=__commonJSMin$1(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),require_sbmh=__commonJSMin$1(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),require_multipart=__commonJSMin$1(((e,t)=>{let{Readable:n,Writable:r}=__require$1(`stream`),i=require_sbmh(),{basename:a,convertToUTF8:o,getDecoder:s,parseContentType:c,parseDisposition:l}=require_utils(),u=Buffer.from(`\r
@@ -44,14 +44,21 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
44
44
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
45
45
  `)&&(e=e.slice(0,-1)),t.endsWith(`
46
46
  `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const lineDiff=new LineDiff;function diffLines(e,t,n){return lineDiff.diff(e,t,n)}function tokenize(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
47
- `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function isSentenceEndPunct(e){return e==`.`||e==`!`||e==`?`}var SentenceDiff=class extends Diff{tokenize(e){var t;let n=[],r=0;for(let t=0;t<e.length;t++){if(t==e.length-1){n.push(e.slice(r));break}if(isSentenceEndPunct(e[t])&&e[t+1].match(/\s/)){for(n.push(e.slice(r,t+1)),t=r=t+1;e[t+1]?.match(/\s/);)t++;n.push(e.slice(r,t+1)),r=t+1}}return n}};const sentenceDiff=new SentenceDiff;var CssDiff=class extends Diff{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};const cssDiff=new CssDiff;var JsonDiff=class extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(canonicalize(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};const jsonDiff=new JsonDiff;function canonicalize(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=canonicalize(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=canonicalize(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var ArrayDiff=class extends Diff{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const arrayDiff=new ArrayDiff,WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,n){t.push(n),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,n){if(n<=65535){pushCodeUnit(e,t,n);return}n-=65536,pushCodeUnit(e,t,55296+(n>>10)),pushCodeUnit(e,t,56320+(n&1023))}function decodeUTF8(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){pushCodeUnit(t,n,i),r++;continue}if(i<194||i>244){pushCodeUnit(t,n,REPLACEMENT),r++;continue}if(i<=223){if(r+1>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1];if((a&192)!=128){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodeUnit(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodeUnit(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodePoint(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return flushChunk(t,n),t.join(``)}function decodeUTF16LE(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(pushCodeUnit(t,n,a),pushCodeUnit(t,n,r),i+=2):pushCodeUnit(t,n,REPLACEMENT)}else pushCodeUnit(t,n,REPLACEMENT);continue}if(a>=56320&&a<=57343){pushCodeUnit(t,n,REPLACEMENT);continue}pushCodeUnit(t,n,a)}return i<r&&pushCodeUnit(t,n,REPLACEMENT),flushChunk(t,n),t.join(``)}function decodeASCII(e){let t=[];for(let n=0;n<e.length;n+=CHUNK){let r=Math.min(e.length,n+CHUNK),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function decodeLatin1(e){let t=[];for(let n=0;n<e.length;n+=CHUNK){let r=Math.min(e.length,n+CHUNK),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function decodeWindows1252(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?WINDOWS_1252_EXTRA[i]:void 0;n+=a??String.fromCharCode(i),n.length>=CHUNK&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,n){return dv(e).setUint8(t,n),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,n){return dv(e).setUint16(t,n,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,n){return dv(e).setUint16(t,n),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,n){return dv(e).setUint32(t,n,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,n){return dv(e).setUint32(t,n),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,n){return dv(e).setInt32(t,n),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,n){return dv(e).setBigUint64(t,n,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new EndOfStreamError;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new EndOfStreamError;return n}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new EndOfStreamError;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new EndOfStreamError;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new EndOfStreamError;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new EndOfStreamError;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let n=makeWebStreamReader(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new ReadStreamTokenizer(n,r)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}var require_ms=__commonJSMin$1(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),require_common=__commonJSMin$1(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=require_ms(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),require_browser=__commonJSMin$1(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=require_common()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),require_has_flag=__commonJSMin$1(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),require_supports_color=__commonJSMin$1(((e,t)=>{let n=__require$1(`os`),r=__require$1(`tty`),i=require_has_flag(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){return s(c(e,e&&e.isTTY))}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})),require_node=__commonJSMin$1(((e,t)=>{let n=__require$1(`tty`),r=__require$1(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=require_supports_color();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
47
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function isSentenceEndPunct(e){return e==`.`||e==`!`||e==`?`}var SentenceDiff=class extends Diff{tokenize(e){var t;let n=[],r=0;for(let t=0;t<e.length;t++){if(t==e.length-1){n.push(e.slice(r));break}if(isSentenceEndPunct(e[t])&&e[t+1].match(/\s/)){for(n.push(e.slice(r,t+1)),t=r=t+1;e[t+1]?.match(/\s/);)t++;n.push(e.slice(r,t+1)),r=t+1}}return n}};const sentenceDiff=new SentenceDiff;var CssDiff=class extends Diff{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};const cssDiff=new CssDiff;var JsonDiff=class extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(canonicalize(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};const jsonDiff=new JsonDiff;function canonicalize(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=canonicalize(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=canonicalize(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var ArrayDiff=class extends Diff{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const arrayDiff=new ArrayDiff,INCLUDE_HEADERS={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function structuredPatch(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;diffLines(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(diffLines(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||splitLines$1(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
48
+ `)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function formatPatch(e,t){if(t||=INCLUDE_HEADERS,Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders)throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>formatPatch(e,t)).join(`
49
+ `)}let n=[];t.includeIndex&&e.oldFileName==e.newFileName&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`),t.includeFileHeaders&&(n.push(`--- `+e.oldFileName+(e.oldHeader===void 0?``:` `+e.oldHeader)),n.push(`+++ `+e.newFileName+(e.newHeader===void 0?``:` `+e.newHeader)));for(let t=0;t<e.hunks.length;t++){let r=e.hunks[t];r.oldLines===0&&--r.oldStart,r.newLines===0&&--r.newStart,n.push(`@@ -`+r.oldStart+`,`+r.oldLines+` +`+r.newStart+`,`+r.newLines+` @@`);for(let e of r.lines)n.push(e)}return n.join(`
50
+ `)+`
51
+ `}function createTwoFilesPatch(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;structuredPatch(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?formatPatch(e,o.headerOptions):void 0)}}))}else{let s=structuredPatch(e,t,n,r,i,a,o);return s?formatPatch(s,o?.headerOptions):void 0}}function createPatch(e,t,n,r,i,a){return createTwoFilesPatch(e,e,t,n,r,i,a)}function splitLines$1(e){let t=e.endsWith(`
52
+ `),n=e.split(`
53
+ `).map(e=>e+`
54
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,n){t.push(n),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,n){if(n<=65535){pushCodeUnit(e,t,n);return}n-=65536,pushCodeUnit(e,t,55296+(n>>10)),pushCodeUnit(e,t,56320+(n&1023))}function decodeUTF8(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){pushCodeUnit(t,n,i),r++;continue}if(i<194||i>244){pushCodeUnit(t,n,REPLACEMENT),r++;continue}if(i<=223){if(r+1>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1];if((a&192)!=128){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodeUnit(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodeUnit(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){pushCodeUnit(t,n,REPLACEMENT),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){pushCodeUnit(t,n,REPLACEMENT),r++;continue}pushCodePoint(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return flushChunk(t,n),t.join(``)}function decodeUTF16LE(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(pushCodeUnit(t,n,a),pushCodeUnit(t,n,r),i+=2):pushCodeUnit(t,n,REPLACEMENT)}else pushCodeUnit(t,n,REPLACEMENT);continue}if(a>=56320&&a<=57343){pushCodeUnit(t,n,REPLACEMENT);continue}pushCodeUnit(t,n,a)}return i<r&&pushCodeUnit(t,n,REPLACEMENT),flushChunk(t,n),t.join(``)}function decodeASCII(e){let t=[];for(let n=0;n<e.length;n+=CHUNK){let r=Math.min(e.length,n+CHUNK),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function decodeLatin1(e){let t=[];for(let n=0;n<e.length;n+=CHUNK){let r=Math.min(e.length,n+CHUNK),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function decodeWindows1252(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?WINDOWS_1252_EXTRA[i]:void 0;n+=a??String.fromCharCode(i),n.length>=CHUNK&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,n){return dv(e).setUint8(t,n),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,n){return dv(e).setUint16(t,n,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,n){return dv(e).setUint16(t,n),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,n){return dv(e).setUint32(t,n,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,n){return dv(e).setUint32(t,n),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,n){return dv(e).setInt32(t,n),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,n){return dv(e).setBigUint64(t,n,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new EndOfStreamError;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new EndOfStreamError;return n}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new EndOfStreamError;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new EndOfStreamError;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new EndOfStreamError;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new EndOfStreamError;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new EndOfStreamError;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let n=makeWebStreamReader(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new ReadStreamTokenizer(n,r)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}var require_ms=__commonJSMin$1(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),require_common=__commonJSMin$1(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=require_ms(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),require_browser=__commonJSMin$1(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=require_common()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),require_has_flag=__commonJSMin$1(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),require_supports_color=__commonJSMin$1(((e,t)=>{let n=__require$1(`os`),r=__require$1(`tty`),i=require_has_flag(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){return s(c(e,e&&e.isTTY))}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})),require_node=__commonJSMin$1(((e,t)=>{let n=__require$1(`tty`),r=__require$1(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=require_supports_color();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
48
55
  `).join(`
49
56
  `+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
50
57
  `)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=require_common()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
51
58
  `).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),require_src=__commonJSMin$1(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=require_browser():t.exports=require_node()}));const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src=__toESM$1(require_src(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===eocdSignatureBytes[0]&&n[r+1]===eocdSignatureBytes[1]&&n[r+2]===eocdSignatureBytes[2]&&n[r+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),debug(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===syncBufferSize;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=indexOf(this.syncBuffer.subarray(0,n),ddSignatureArray);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,mergeArrays(e),r.handler)}else r.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,n){return e?e.constructor===t?!0:objectToString.call(e)===n:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)assertUint8Array(t),n.set(t,r),r+=t.length;return n}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let n=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:n=maximumUntrustedSkipSizeInBytes,reason:r=`skip`}={}){let i=getSafeBound(t,n,r);await e.ignore(i)}async function safeReadBuffer(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=getSafeBound(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function checkBytes(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,n){return hasUnknownFileSize(e)&&e.position-t>n}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function mergeByteChunks(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let n=e.length-zipDataDescriptorLengthInBytes;for(let r=0;r<=n;r++)if(UINT32_LE.get(e,r)===zipDataDescriptorSignature&&UINT32_LE.get(e,r+8)===t+r)return r;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:n=maximumZipEntrySizeInBytes}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=findZipDataDescriptorOffset(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(zipDataDescriptorOverlapLengthInBytes,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return mergeByteChunks(a,o)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:n,maximumDescriptorLength:r=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:n,maximumLength:r});if(!n){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}ZipHandler.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,r,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await readZipEntryData(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,r,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,n=createOpenXmlZipDetectionState(),r=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(n,e.filename),updateIWorkZipDetectionStateFromFilename(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=getOpenXmlFileTypeFromZipEntries(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(n.isParsingContentTypes=!0,{async handler(e){let r=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));r&&(t=getFileTypeFromMimeType(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!n.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(n))}let i=hasUnknownFileSize(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(r);return t??getOpenXmlFileTypeFromZipEntries(n)??i??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await safeReadBuffer(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:getUintBE(i),len:getUintBE(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(o.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,o.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let i=hasUnknownFileSize(e),a=e.position,o=0,s=!1;do{if(o++,o>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,a,maximumPngStreamScanBudgetInBytes))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>maximumPngChunkSizeInBytes)return s&&isPngAncillaryChunk(l.type)?t:void 0;try{await safeIgnore(e,l.length+4,{maximumLength:i?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=hasUnknownFileSize(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(checkBytes(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,o,{maximumLength:r?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof EndOfStreamError||n instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function fileTypeFromBuffer(e,t){return new FileTypeParser(t).fromBuffer(e)}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=normalizeSampleSize(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await readWithSignal(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await readWithSignal(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:concatUint8Arrays(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof EndOfStreamError))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let n=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),r=hasUnknownFileSize(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),n=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||n&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:n?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
52
59
  `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return detectPng(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new StringType(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
53
60
  `))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return detectAsf(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new StringType(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&tarHeaderChecksumMatches(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
54
- `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},n=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),r=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(n===42){if(r>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),n=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&r>maximumTiffStreamIfdOffsetInBytes)return t;let n=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes),RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,n,r){let i=e.doc;if(!i)return;let a=++_effectCounter,o=i.getMap(`agent-effects`),s=l=>{e.unobserve(s),i.off(`destroy`,c);let u=`${t}:${a}`,d={sessionId:t,timestamp:Date.now(),delta:l.delta,agent_type:r??`agent`,color_seed:n??t};try{i.transact(()=>{if(o.set(u,d),o.size>RING_BUFFER_LIMIT){let e=[...o.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,o.size-RING_BUFFER_LIMIT))o.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},c=()=>{e.unobserve(s)};e.observe(s),i.once(`destroy`,c)}const MAX_SUMMARY_LENGTH=80,ELLIPSIS=`…`;function normalizeSummary(e){return e===void 0?{kind:`absent`}:typeof e==`string`?e.length===0||e.trim().length===0?{kind:`absent`}:e.length<=80?{kind:`value`,value:e}:{kind:`value`,value:e.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}:{kind:`invalid`}}let pendingContributors=new Map;function recordContributor(e,t,n,r,i,a,o){let s=pendingContributors.get(t);if(s||(s={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[]},pendingContributors.set(t,s)),s.docs.add(e),i!==void 0&&(s.subjectOverride=i),a!==void 0){let e=s.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),s.actor=e}typeof o==`string`&&o.length>0&&s.summaries.push(o)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,n]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[]},pendingContributors.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries])}}function restoreContributorEntry(e,t){let n=pendingContributors.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[]},pendingContributors.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries])}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_CACHE_TTL_MS=6e4,INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}async function handleInstalledAgents(e,t,n){if(e.method!==`GET`){writeJson(t,405,{error:`Method not allowed`});return}try{writeJson(t,200,await n())}catch(e){console.error(`[installed-agents]`,e),writeJson(t,500,{error:`Internal server error`})}}function writeJson(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function createOsProbe(e,t=execFile){return n=>e===`darwin`?probeMacOs(n,t):e===`win32`?probeWindows(n,t):probeLinux(n,t)}function probeMacOs(e,t){let n=MACOS_APP_NAMES[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{n(!e)})})}function probeLinux(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=buildLowerDocNameIndex(t),o=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES)return n;let e=o===``?null:basename$1(o);if(e&&(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES))return n;if(o===``)break;o=parentFolder(o)}return n}function lookup(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let n=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(n))return normalizeFrontmatterScalar(t.slice(n.length))||null;return null}function parseInlineAliases(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=normalizeFrontmatterScalar(n);e&&t.push(e),n=``;continue}n+=i}let i=normalizeFrontmatterScalar(n);return i&&t.push(i),t}function dedupeExact(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let n=splitFrontmatterLines(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return dedupeExact(parseInlineAliases(r.slice(1,-1)));let e=normalizeFrontmatterScalar(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(i)}return[]}function extractPageTitle(e,t){let{frontmatter:n,body:r}=stripFrontmatter(e),i=extractFrontmatterScalar(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let n=`${t}:`,r=splitFrontmatterLines(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=parseInlineAliases(i.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function extractPageIdentity(e,t){let n=extractPageTitle(e,t),r=extractPageAliases(e),i=dedupeExact([n,...r]),a=[],o=new Set;for(let e of i){let t=toWikiLinkSlug(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function stripDocExtension(e){let t=e.toLowerCase();for(let n of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(n))return e.slice(0,-n.length);return e}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let n=docExtensionByName.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:rank(t)<rank(n)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,n){if(!normalizeSnippet$1(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
61
+ `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},n=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),r=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(n===42){if(r>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),n=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&r>maximumTiffStreamIfdOffsetInBytes)return t;let n=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes),RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,n,r){let i=e.doc;if(!i)return;let a=++_effectCounter,o=i.getMap(`agent-effects`),s=l=>{e.unobserve(s),i.off(`destroy`,c);let u=`${t}:${a}`,d={sessionId:t,timestamp:Date.now(),delta:l.delta,agent_type:r??`agent`,color_seed:n??t};try{i.transact(()=>{if(o.set(u,d),o.size>RING_BUFFER_LIMIT){let e=[...o.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,o.size-RING_BUFFER_LIMIT))o.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},c=()=>{e.unobserve(s)};e.observe(s),i.once(`destroy`,c)}function collectItemsInDeleteSet(e,t,n){iterateDeletedStructs(e,t,e=>{e instanceof Item&&n.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let n=[],r=[],i=t.doc,a=new Set,o=new Set;i&&i.transact(t=>{collectItemsInDeleteSet(t,e.insertions,a),collectItemsInDeleteSet(t,e.deletions,o)});let s=``,c=``,l=0,u=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,i=t.length,d=a.has(e),f=o.has(e);e.deleted?f&&(r.push({position:l,content:t,length:i}),s+=t,l+=i):(c+=t,d?n.push({position:u,content:t,length:i}):(s+=t,l+=i),u+=i)}return{insertions:n,deletions:r,before:s,after:c}}function synthesizeStackItemDiffText(e,t,n){let{before:r,after:i}=synthesizeStackItemDiff(e,t);return r===i?``:createPatch(n,r,i,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let n=t.doc,r=new Set,i=new Set;n&&n.transact(t=>{collectItemsInDeleteSet(t,e.insertions,r),collectItemsInDeleteSet(t,e.deletions,i)});let a=0,o=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&r.has(e)&&(a+=t),i.has(e)&&(o+=t)}return{additions:a,deletions:o}}function listAgentActivity(e,t){let n=[],r=null,i=!1;for(let a of e.sessionsForConnection(t)){if(i=!0,!r){let e=a.origin.context,n=typeof e?.agent_type==`string`?e.agent_type:void 0,i=typeof e?.color_seed==`string`?e.color_seed:t,o=iconFromClientName(n),s=AGENT_ICON_COLORS[o]??colorFromSeed(i);r={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:s,icon:o,connectionId:t}}let e=a.docName,o=a.um,s=a.dc.document.getText(`source`),c=[];for(let e=0;e<o.undoStack.length;e++){let t=o.undoStack[e],n=getBurstTs(t),{additions:r,deletions:i}=countStackItemChanges(t,s);c.push({stackIndex:e,ts:n,additions:r,deletions:i})}if(c.length===0)continue;c.sort((e,t)=>t.stackIndex-e.stackIndex);let l=c.reduce((e,t)=>e+t.additions,0),u=c.reduce((e,t)=>e+t.deletions,0),d=Math.max(...c.map(e=>e.ts));n.push({docName:e,additionsTotal:l,deletionsTotal:u,lastTs:d,bursts:c})}return i?(n.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:r,files:n}):{sessionAlive:!1,agent:null,files:[]}}const MAX_SUMMARY_LENGTH=80,ELLIPSIS=`…`;function normalizeSummary(e){return e===void 0?{kind:`absent`}:typeof e==`string`?e.length===0||e.trim().length===0?{kind:`absent`}:e.length<=80?{kind:`value`,value:e}:{kind:`value`,value:e.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}:{kind:`invalid`}}let pendingContributors=new Map;function recordContributor(e,t,n,r,i,a,o){let s=pendingContributors.get(t);if(s||(s={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[]},pendingContributors.set(t,s)),s.docs.add(e),i!==void 0&&(s.subjectOverride=i),a!==void 0){let e=s.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),s.actor=e}typeof o==`string`&&o.length>0&&s.summaries.push(o)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,n]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[]},pendingContributors.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries])}}function restoreContributorEntry(e,t){let n=pendingContributors.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[]},pendingContributors.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries])}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_CACHE_TTL_MS=6e4,INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}async function handleInstalledAgents(e,t,n){if(e.method!==`GET`){writeJson(t,405,{error:`Method not allowed`});return}try{writeJson(t,200,await n())}catch(e){console.error(`[installed-agents]`,e),writeJson(t,500,{error:`Internal server error`})}}function writeJson(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function createOsProbe(e,t=execFile){return n=>e===`darwin`?probeMacOs(n,t):e===`win32`?probeWindows(n,t):probeLinux(n,t)}function probeMacOs(e,t){let n=MACOS_APP_NAMES[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{n(!e)})})}function probeLinux(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=buildLowerDocNameIndex(t),o=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES)return n;let e=o===``?null:basename$1(o);if(e&&(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES))return n;if(o===``)break;o=parentFolder(o)}return n}function lookup(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let n=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(n))return normalizeFrontmatterScalar(t.slice(n.length))||null;return null}function parseInlineAliases(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=normalizeFrontmatterScalar(n);e&&t.push(e),n=``;continue}n+=i}let i=normalizeFrontmatterScalar(n);return i&&t.push(i),t}function dedupeExact(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let n=splitFrontmatterLines(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return dedupeExact(parseInlineAliases(r.slice(1,-1)));let e=normalizeFrontmatterScalar(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(i)}return[]}function extractPageTitle(e,t){let{frontmatter:n,body:r}=stripFrontmatter(e),i=extractFrontmatterScalar(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let n=`${t}:`,r=splitFrontmatterLines(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=parseInlineAliases(i.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function extractPageIdentity(e,t){let n=extractPageTitle(e,t),r=extractPageAliases(e),i=dedupeExact([n,...r]),a=[],o=new Set;for(let e of i){let t=toWikiLinkSlug(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function stripDocExtension(e){let t=e.toLowerCase();for(let n of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(n))return e.slice(0,-n.length);return e}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let n=docExtensionByName.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:rank(t)<rank(n)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,n){if(!normalizeSnippet$1(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
55
62
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
56
63
  `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=normalizeSnippet$1(e.slice(a,o));return l?`${s}${l}${c}`:null}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i++;continue}let t=0;for(;e[i+t]==="`";)t++;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function readWikiLink$2(e,t){WIKI_LINK_RE$1.lastIndex=t;let n=WIKI_LINK_RE$1.exec(e);if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function extractWikiLinksFromLine(e){let t=``,n=[],r=leadingMarkdownPrefixLength$2(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=readInlineCode$2(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=readWikiLink$2(e,r);if(i){let e=getWikiLinkText(i),a=t.length;t+=e;let o=classifyWikiLinkTarget(i.target,i.anchor);o?.kind===`doc`&&n.push({target:o.docName,anchor:o.anchor,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function extractExternalWikiLinksFromLine(e){let t=``,n=[],r=leadingMarkdownPrefixLength$2(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=readInlineCode$2(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=readWikiLink$2(e,r);if(i){let e=getWikiLinkText(i),a=t.length;t+=e;let o=classifyWikiLinkTarget(i.target,i.anchor);o?.kind===`external`&&n.push({url:o.url,label:e,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$2(e,t){MD_LINK_RE$1.lastIndex=t;let n=MD_LINK_RE$1.exec(e);return n?{text:n[1]??``,href:normalizeMarkdownHref$1(n[2]??``),nextIndex:t+n[0].length}:null}function extractMarkdownLinksFromLine(e,t){let n=``,r=[],i=leadingMarkdownPrefixLength$2(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=readInlineCode$2(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=readWikiLink$2(e,i);if(t){n+=getWikiLinkText(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=readMarkdownLink$2(e,i);if(a){let e=classifyMarkdownHref(a.href,t);if(e?.kind===`doc`){let t=n.length;n+=a.text,r.push({target:e.docName,anchor:e.anchor,start:t,end:t+a.text.length})}else n+=a.text;i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function extractExternalMarkdownLinksFromLine(e,t){let n=``,r=[],i=leadingMarkdownPrefixLength$2(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=readInlineCode$2(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=readWikiLink$2(e,i);if(t){n+=getWikiLinkText(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=readMarkdownLink$2(e,i);if(a){let e=classifyMarkdownHref(a.href,t);if(n+=a.text,e?.kind===`external`){let t=n.length-a.text.length;r.push({url:e.url,label:a.text||null,start:t,end:t+a.text.length})}i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function extractMarkdownLinksFromMarkdown(e,t){let n=e.replaceAll(`\r
57
64
  `,`
@@ -73,7 +80,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
73
80
  `).filter(e=>e.length>0)}catch{return 0}let r=[],i={server:0,"human-":0,upstream:0};for(let e of n){let t=e.split(`/`);if(t.length<4)continue;let n=t.slice(3).join(`/`);parseWriterId(n).classification===`unknown`&&(n===`server`?(r.push(e),i.server++):n.startsWith(`human-`)?(r.push(e),i[`human-`]++):n===`upstream`&&(r.push(e),i.upstream++))}if(r.length===0)return 0;for(let e of r)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let a=r.length;return incrementShadowMigrationLegacyRefsDeleted(a),console.warn(`[shadow-migration] deleted ${a} legacy refs: server=${i.server} human-=${i[`human-`]} upstream=${i.upstream}`),a}async function commitWip(e,t,n,r,i=`main`){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":i}},async()=>commitWipInner(e,t,n,r,i))}async function commitWipInner(e,t,n,r,i=`main`){let a=resolve(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=shadowGit(e),c=n||`.`;try{try{let t=(await s.raw(`rev-parse`,`${o}^{tree}`)).trim();await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${o}:`,e),e}await s.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:a}).raw(`add`,c);let n=(await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),i=null;try{i=(await s.raw(`rev-parse`,o)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${o}:`,e),e}let l=[`commit-tree`,n,`-m`,r];i&&l.push(`-p`,i);let u=(await s.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim();return await s.raw(`update-ref`,o,u),u}finally{try{rmSync(a)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let n of readdirSync(e.gitDir))if(n.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,n)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let n=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),r=shadowGit(e),i=t||`.`;try{return await r.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:n}).raw(`add`,i),(await r.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:n}).raw(`write-tree`)).trim()}finally{try{rmSync(n)}catch{}}}async function commitWipFromTree(e,t,n,r,i=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":i,"shadow.tree":n.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,n,r,i))}async function commitWipFromTreeInner(e,t,n,r,i=`main`){let a=`refs/wip/${i}/${t.id}`,o=shadowGit(e),s=null;try{s=(await o.raw(`rev-parse`,a)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${a}:`,e),e}let c=[`commit-tree`,n,`-m`,r];s&&c.push(`-p`,s);let l=(await o.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...c)).trim();return await o.raw(`update-ref`,a,l),l}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,n,r,i=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":i,"shadow.new_head":r.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,n,r,i))}async function commitUpstreamImportInner(e,t,n,r,i=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(n,r)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,i)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,n,r=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${n.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,r)}async function saveInMemoryCheckpoint(e,t,n){let r=n.branch??`main`,i=shadowGit(e),a=randomUUID(),o=resolve(e.gitDir,`index-checkpoint-${a}`),s=resolve(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=formatCheckpointBodyLine(n.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:n.docName,size:l,metadata:n.metadata}:{kind:`external-change-rescue`,docName:n.docName,size:l,metadata:n.metadata}),d=`checkpoint: ${n.label}\n\n${u}`;try{tracedWriteFileSync(s,n.contents,`utf-8`);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${c}`);let a=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,a,`-m`,d)).trim();return await i.raw(`update-ref`,`refs/checkpoints/${r}/${l}`,l),l}finally{try{rmSync(o)}catch{}try{rmSync(s)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let n=shadowGit(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
74
81
  `).filter(e=>e.length===40);if(i.length===0)return[];let a;try{a=await n.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...i)}catch{return[]}let o=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[r=``,i=``,a=``,s=``]=t.split(`\0`),c=parseCheckpoint(s);if(c?.kind!==`external-change-rescue`)continue;let l=c.docName??``,u=c.size??0;if(!l)try{let e=(await n.raw(`ls-tree`,`-r`,`--long`,r)).trim().split(`
75
82
  `)[0];if(e){let t=e.split(/\s+/),n=4,r=3;u===0&&(u=Number(t[3]??`0`)),l=(t[4]??``).replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``}}catch{}l&&o.push({docName:l,timestamp:i,size:u,sha:r,label:a.replace(/^checkpoint:\s*/,``),incomingDiskSha:c.metadata.incomingDiskSha})}return o}async function parkBranch(e,t,n,r,i){return r.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":i??``,"shadow.doc_count":r.length}},async()=>parkBranchInner(e,t,n,r,i))}async function parkBranchInner(e,t,n,r,i){let a=shadowGit(e),o=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),s=`refs/wip/${t}/${n}`,c=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of r){tracedWriteFileSync(c,t.markdown,`utf-8`);let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),tracedWriteFileSync(c,t.diskSnapshot,`utf-8`);let r=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=null;try{l=(await a.raw(`rev-parse`,s)).trim()}catch{}let u={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:r.map(e=>e.docName)},d=[`commit-tree`,n,`-m`,`${formatParkSubject(t,i??t)}\n\n${formatOkActor(u)}`];l&&d.push(`-p`,l);let f=(await a.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...d)).trim();return await a.raw(`update-ref`,s,f),f}finally{try{rmSync(o)}catch{}try{rmSync(c)}catch{}}}async function readParkedState(e,t,n,r){let i=shadowGit(e),a=`refs/wip/${t}/${n}`,o;try{o=(await i.raw(`rev-parse`,a)).trim()}catch{return null}try{return(await i.raw(`log`,`-1`,`--format=%s`,o)).trim().startsWith(`park:`)?{markdown:(await i.raw(`show`,`${o}:${r}`)).trim(),diskSnapshot:(await i.raw(`show`,`${o}:.park-base/${r}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${r} from ${a}:`,e),e}}async function saveVersion(e,t,n,r=`main`){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":r,"shadow.writer_count":n.length}},async()=>saveVersionInner(e,t,n,r))}async function saveVersionInner(e,t,n,r=`main`){let i=shadowGit(e),a=t||`.`,o=resolve(e.gitDir,`index-checkpoint`);try{await i.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:o}).raw(`add`,a);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),s=[];for(let e of[...n,GIT_UPSTREAM_WRITER])try{let t=(await i.raw(`rev-parse`,`refs/wip/${r}/${e.id}`)).trim();s.push(t)}catch{}let c=[...new Set(s)];if(c.length===0)try{let e=(await i.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
76
- `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},u=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(`Checkpoint version`)}\n\n${formatOkActor(l)}`];for(let e of c)u.push(`-p`,e);let d=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:f}}finally{try{rmSync(o)}catch{}}}const log$4=getLogger(`persistence`);function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return SERVICE_WRITER}return null}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=resolve(t,`${e}${getDocExtension(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),n;try{n=realpathSync(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(relative(r,n)||`content`),o=e?.backlinkIndex,s=e?.getPrincipal,c=new Map,l=e?.gitEnabled??!0,u=e?.commitDebounceMs??15e3,d=e?.wipRef??`refs/wip/main`,f=e?.getCurrentBranch,p=null,m=0,h=null,g=!1;async function _(){T();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await v()).finally(()=>{w?.record((Date.now()-e)/1e3)})}async function v(){let e=i?.current;if(e){let t=swapContributors(),n=f?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},r=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,a,r,n);m=0,log$4.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`)}catch(e){m++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:m},`[persistence] Shadow commit failed (attempt ${m})`),m>=3&&log$4.error({attempt:m},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await buildWipTree(e,a)}catch(e){restoreContributors(t),m++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:m},`[persistence] Shadow WIP tree build failed (attempt ${m})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],c=o.actor,l=[...o.summaries],u={v:1,writer_id:a,principal:c?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:c?.agentType??null,client_name:c?.clientName??null,client_version:c?.clientVersion??null,label:c?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...l.length>0?{summaries:l}:{}},d=`${composeCommitSubject(o.subjectOverride??formatWipSubject(s),l)}\n\n${formatOkActor(u)}`;try{let o=await commitWipFromTree(e,t,r,d,n);i=!0,log$4.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`)}catch(e){restoreContributorEntry(a,o),incrementGitWriterCommitFailure(),log$4.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?m=0:(m++,incrementGitAutoSaveFailure(),m>=3&&log$4.error({attempt:m},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(r,`.git`),workTree:r}),n=resolve(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$4.info({},`[persistence] Empty repo — starting with empty index`):log$4.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,d)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,d,i),m=0,log$4.info({sha:i.slice(0,8),wipRef:d},`[persistence] Git commit: ${i.slice(0,8)} on ${d}`)}catch(e){m++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:m},`[persistence] Git commit failed (attempt ${m})`),m>=3&&log$4.error({attempt:m},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(n)}catch{}}}function y(e){if(e<=0)return u;let t=2**Math.min(e,5),n=Math.random()*.25*u;return u*t+n}function b(){l&&(isBatchInProgress()||(p&&clearTimeout(p),p=setTimeout(()=>{if(p=null,h){g=!0;return}h=_().finally(()=>{h=null,g&&(g=!1,b())})},y(m))))}async function x(){p&&(clearTimeout(p),p=null,h||=_().finally(()=>{h=null,g&&(g=!1,b())})),h&&await h}let S=null,C=null,w=null;function T(){if(S)return;let e=getMeter();S=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),C=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),w=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}let E={async onLoadDocument({document:e,documentName:t,context:r}){if(isSystemDoc(t))return;T();let i=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":t}},async()=>{log$4.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let r=safeContentPath(t,n);if(!existsSync(r))return;try{let e=realpathSync(r);if(!isWithinContentDir(e,n)){console.warn(`[persistence] symlink-escape on load: ${r} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${r}, refusing`);return}}let{frontmatter:i,body:a}=stripFrontmatter(readFileSync(r,`utf-8`));i&&(c.set(t,i),e.getMap(`metadata`).set(`frontmatter`,i));let o=mdManager.parseWithFallback(a),s=e.getXmlFragment(`default`);log$4.info({documentName:t,fragmentLength:s.length},`[persistence] onLoadDocument ${t}: fragment.length=${s.length} before update`),s.length===0?(updateYFragment(e,s,schema.nodeFromJSON(o),{mapping:new Map,isOMark:new Map}),log$4.info({filePath:r,children:s.length},`[persistence] Loaded ${r} into Y.Doc (${s.length} children)`),s.observeDeep(()=>{log$4.info({documentName:t,fragmentLength:s.length},`[persistence] MUTATION on ${t}: fragment.length=${s.length}`)})):log$4.info({documentName:t,children:s.length},`[persistence] Skipped load for ${t} — fragment already has ${s.length} children`),setReconciledBase(t,prependFrontmatter(i,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(s,schema).toJSON())))}).finally(()=>{S?.record((Date.now()-i)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(isSystemDoc(t)||isBatchInProgress())return;T();let a=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let i=yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON(),a=mdManager.serialize(i),l=e.getMap(`metadata`).get(`frontmatter`),u=prependFrontmatter(typeof l==`string`?l:c.get(t)||``,a),d=getReconciledBase(t);if(d!==void 0&&normalizeBridge(u)===normalizeBridge(d)){contributorCount()>0&&b();return}let f=resolveWriterFromOrigin(r,s);f&&f.id!==SERVICE_WRITER.id&&(hasContributor(f.id)||recordContributor(t,f.id,f.name,f.id)),d&&u.length>d.length*1.5&&(log$4.warn({documentName:t,markdownLength:u.length,baseLength:d.length},`[persistence] WARNING: serialized content is ${u.length} bytes vs base ${d.length} bytes for ${t} — possible duplication`),log$4.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let p=safeContentPath(t,n);await tracedMkdir(dirname(p),{recursive:!0});let m;try{m=await realpath(p)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=lstatSync(p).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$4.warn({err:e,path:p},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),m=p}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${p}`),Error(`Symlink cycle detected at ${p}`);else throw e}if(!isWithinContentDir(m,n)){let e=`symlink-escape: ${p} resolves to ${m} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:p,canonical:m,contentDir:n}),Error(e)}let h=`${m}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(h,u,`utf-8`),await tracedRename(h,m),registerWrite(m,contentHash(u)),incrementPersistenceDiskWrite()}catch(e){try{tracedUnlinkSync(h)}catch{}throw log$4.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$4.info({filePath:m,bytes:u.length},`[persistence] Wrote ${m} (${u.length} bytes)`),setReconciledBase(t,u),o&&(o.updateDocumentFromMarkdown(t,u),o.saveToDisk().catch(e=>{log$4.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":u.length}),b()}).finally(()=>{C?.record((Date.now()-a)/1e3)})}};async function D(){h&&await h}return{extension:E,flushPendingGitCommit:x,waitForPendingCommits:D}}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
83
+ `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},u=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(`Checkpoint version`)}\n\n${formatOkActor(l)}`];for(let e of c)u.push(`-p`,e);let d=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:f}}finally{try{rmSync(o)}catch{}}}const log$4=getLogger(`persistence`);function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return SERVICE_WRITER}return null}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=resolve(t,`${e}${getDocExtension(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),n;try{n=realpathSync(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(relative(r,n)||`content`),o=e?.backlinkIndex,s=e?.getPrincipal,c=e?.onAgentCommit,l=new Map,u=e?.gitEnabled??!0,d=e?.commitDebounceMs??15e3,f=e?.wipRef??`refs/wip/main`,p=e?.getCurrentBranch,m=null,h=0,g=null,_=!1;async function v(){E();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await y()).finally(()=>{T?.record((Date.now()-e)/1e3)})}async function y(){let e=i?.current;if(e){let t=swapContributors(),n=p?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},r=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,a,r,n);h=0,log$4.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`)}catch(e){h++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:h},`[persistence] Shadow commit failed (attempt ${h})`),h>=3&&log$4.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await buildWipTree(e,a)}catch(e){restoreContributors(t),h++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:h},`[persistence] Shadow WIP tree build failed (attempt ${h})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],l=o.actor,u=[...o.summaries],d={v:1,writer_id:a,principal:l?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:l?.agentType??null,client_name:l?.clientName??null,client_version:l?.clientVersion??null,label:l?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...u.length>0?{summaries:u}:{}},f=`${composeCommitSubject(o.subjectOverride??formatWipSubject(s),u)}\n\n${formatOkActor(d)}`;try{let o=await commitWipFromTree(e,t,r,f,n);i=!0,log$4.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`),a.startsWith(`agent-`)&&c?.()}catch(e){restoreContributorEntry(a,o),incrementGitWriterCommitFailure(),log$4.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?h=0:(h++,incrementGitAutoSaveFailure(),h>=3&&log$4.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(r,`.git`),workTree:r}),n=resolve(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$4.info({},`[persistence] Empty repo — starting with empty index`):log$4.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,f)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,f,i),h=0,log$4.info({sha:i.slice(0,8),wipRef:f},`[persistence] Git commit: ${i.slice(0,8)} on ${f}`)}catch(e){h++,incrementGitAutoSaveFailure(),log$4.error({err:e,attempt:h},`[persistence] Git commit failed (attempt ${h})`),h>=3&&log$4.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(n)}catch{}}}function b(e){if(e<=0)return d;let t=2**Math.min(e,5),n=Math.random()*.25*d;return d*t+n}function x(){u&&(isBatchInProgress()||(m&&clearTimeout(m),m=setTimeout(()=>{if(m=null,g){_=!0;return}g=v().finally(()=>{g=null,_&&(_=!1,x())})},b(h))))}async function S(){m&&(clearTimeout(m),m=null,g||=v().finally(()=>{g=null,_&&(_=!1,x())})),g&&await g}let C=null,w=null,T=null;function E(){if(C)return;let e=getMeter();C=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),w=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),T=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}let D={async onLoadDocument({document:e,documentName:t,context:r}){if(isSystemDoc(t))return;E();let i=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":t}},async()=>{log$4.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let r=safeContentPath(t,n);if(!existsSync(r))return;try{let e=realpathSync(r);if(!isWithinContentDir(e,n)){console.warn(`[persistence] symlink-escape on load: ${r} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${r}, refusing`);return}}let{frontmatter:i,body:a}=stripFrontmatter(readFileSync(r,`utf-8`));i&&(l.set(t,i),e.getMap(`metadata`).set(`frontmatter`,i));let o=mdManager.parseWithFallback(a),s=e.getXmlFragment(`default`);log$4.info({documentName:t,fragmentLength:s.length},`[persistence] onLoadDocument ${t}: fragment.length=${s.length} before update`),s.length===0?(updateYFragment(e,s,schema.nodeFromJSON(o),{mapping:new Map,isOMark:new Map}),log$4.info({filePath:r,children:s.length},`[persistence] Loaded ${r} into Y.Doc (${s.length} children)`),s.observeDeep(()=>{log$4.info({documentName:t,fragmentLength:s.length},`[persistence] MUTATION on ${t}: fragment.length=${s.length}`)})):log$4.info({documentName:t,children:s.length},`[persistence] Skipped load for ${t} — fragment already has ${s.length} children`),setReconciledBase(t,prependFrontmatter(i,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(s,schema).toJSON())))}).finally(()=>{C?.record((Date.now()-i)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(isSystemDoc(t)||isBatchInProgress())return;E();let a=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let i=yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON(),a=mdManager.serialize(i),c=e.getMap(`metadata`).get(`frontmatter`),u=prependFrontmatter(typeof c==`string`?c:l.get(t)||``,a),d=getReconciledBase(t);if(d!==void 0&&normalizeBridge(u)===normalizeBridge(d)){contributorCount()>0&&x();return}let f=resolveWriterFromOrigin(r,s);f&&f.id!==SERVICE_WRITER.id&&(hasContributor(f.id)||recordContributor(t,f.id,f.name,f.id)),d&&u.length>d.length*1.5&&(log$4.warn({documentName:t,markdownLength:u.length,baseLength:d.length},`[persistence] WARNING: serialized content is ${u.length} bytes vs base ${d.length} bytes for ${t} — possible duplication`),log$4.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let p=safeContentPath(t,n);await tracedMkdir(dirname(p),{recursive:!0});let m;try{m=await realpath(p)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=lstatSync(p).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$4.warn({err:e,path:p},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),m=p}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${p}`),Error(`Symlink cycle detected at ${p}`);else throw e}if(!isWithinContentDir(m,n)){let e=`symlink-escape: ${p} resolves to ${m} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:p,canonical:m,contentDir:n}),Error(e)}let h=`${m}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(h,u,`utf-8`),await tracedRename(h,m),registerWrite(m,contentHash(u)),incrementPersistenceDiskWrite()}catch(e){try{tracedUnlinkSync(h)}catch{}throw log$4.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$4.info({filePath:m,bytes:u.length},`[persistence] Wrote ${m} (${u.length} bytes)`),setReconciledBase(t,u),o&&(o.updateDocumentFromMarkdown(t,u),o.saveToDisk().catch(e=>{log$4.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":u.length}),x()}).finally(()=>{w?.record((Date.now()-a)/1e3)})}};async function O(){g&&await g}return{extension:D,flushPendingGitCommit:S,waitForPendingCommits:O}}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
77
84
  `),r=[],i=[],a=null;for(let e of n){let t=e.match(/^(`{3,}|~{3,})/);if(t){let e=t[1][0];a?e===a&&(a=null):a=e}a===null&&e.trim()===``&&i.length>0?(r.push(i.join(`
78
85
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
79
86
  `).trim();e&&r.push(e)}return r}function reconcile(e){if(isSystemDoc(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return containsConflictMarkers(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:mergeBlocks(splitMarkdownBlocks(t),splitMarkdownBlocks(n),splitMarkdownBlocks(r))}function mergeBlocks(e,t,n){let r=computeEditOps(e,t),i=computeEditOps(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
@@ -109,14 +116,14 @@ Append-only record of ingests, research, consolidations, and maintenance. Each e
109
116
  `)||e.startsWith(`---\r
110
117
  `)){let n=e.indexOf(`
111
118
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=createCodeFenceTracker();for(let e of t.split(`
112
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:c,getCurrentBranch:l,contentRoot:u,backlinkIndex:d,signalChannel:f,agentFocusBroadcaster:p,agentPresenceBroadcaster:m,onAgentWrite:h,getSyncEngine:g,localOpCliArgs:_=[`open-knowledge`],projectDir:v,getPrincipal:y,installedAgentsProbe:b}=e,x=createConcurrencyGuard(),S=createInstalledAgentsProbe({probe:b??createOsProbe(process.platform)});function C(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=C(e);if(!t||!existsSync(t))return T;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):T}catch{return T}}function D(e){if(d)try{if(d.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,i()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function A(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>c?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function N(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let P=N();function F(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function I(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function L(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function R(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function z(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function B(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let a=i();a instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},a)}function V(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function H(e,n){return P(async()=>{if(!d)throw Error(`Managed rename requires backlink index support`);let a=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(d.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],p=[];for(let t of[e,...c]){if(l.has(t))continue;let n=z(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&p.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let m=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:R([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,m,async()=>{for(let e of p)d.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?V(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(B(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),d.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await I([e])).get(e)??l.get(e)??readFileSync(a,`utf-8`),e,e,n);await renameTrackedPathInGit(v,a,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(a,o)),L(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=i();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),d.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),d.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),f?.(`files`),f?.(`backlinks`),f?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let U=128;function W(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function G(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function K(e){return{principalId:y?.()?.id,agentType:G(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function q(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function J(e){return{value:e.value}}function Y(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function X(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=W(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let g=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),_=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${_}`,{response:y,stored:b}=q(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);m?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(g.dc.document.getText(`source`),s,l,u),g.dc.document.transact(()=>{applyAgentMarkdownWrite(g.dc.document,`${v}\n`,`append`),g.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},g.origin),recordContributor(o,s,c,l,void 0,K({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Y(p)}finally{m?.touchMode(s,`idle`)}j(o,`agent-write`),h?.(),json(t,200,{ok:!0,timestamp:_,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:g,clientName:_,clientVersion:v,label:y}=W(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=q(b),C=await n.getSession(u,d,{displayName:f,colorSeed:g,clientName:_}),w=new Date().toISOString();try{let e=iconFromClientName(_),t=AGENT_ICON_COLORS[e]??colorFromSeed(g??d);m?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,g,_),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,g,void 0,K({clientName:_,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Y(b)}finally{m?.touchMode(d,`idle`)}j(u,`agent-write-md`),p?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),h?.();let T=D(u),E=k(u),M=A();M===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":G(_)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:M,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function Z(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function te(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function Q(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:d.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ne(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=d.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:d.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=d.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=d.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:d.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:d.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;json(t,200,{ok:!0,deadLinks:d.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ce(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=O(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:g,agentName:_,colorSeed:v,clientName:y,clientVersion:b,label:x}=W(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,g,{displayName:_,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??g);if(m?.setPresence(g,{displayName:_,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),g,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(g,{agentId:g,timestamp:Date.now(),type:`insert`,description:`Patched (${_}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=q(S);recordContributor(f,g,_,v,void 0,K({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Y(S)}}finally{m?.touchMode(g,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}j(f,`agent-patch`),p?.setFocus(g,{agentName:_,currentDoc:f,writeKind:`edit`,ts:Date.now()}),h?.();let D=k(f),M=A();M===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":G(y)});let{response:N}=q(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:M,...N?{summary:N}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function le(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=W(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=O(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let h=typeof i.connectionId==`string`?i.connectionId:void 0;if(!h){json(t,400,{ok:!1,error:`connectionId required`});return}let g=i.scope===`session`?`session`:`last`;if(!n.hasSession(f,h)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let _=await n.getSession(f,h),v=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);m?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),v=applyAgentUndo(_,g),v&&recordContributor(f,h,o,s,void 0,K({clientName:c,clientVersion:l,label:u}))}finally{m?.touchMode(a,`idle`)}v&&j(f,`agent-undo`),p?.setFocus(h,{agentName:h,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:g,undone:v})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ue(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),writeFileSync(o,``,`utf-8`),d&&(d.deleteDocument(a),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),f?.(`backlinks`),f?.(`graph`)),f?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}d.rebuildFromDisk(),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),f?.(`backlinks`),f?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:d,agentId:f,agentName:p,clientName:m}=W(s);a.length===0&&(a=d===void 0?[SERVICE_WRITER]:[{id:f,name:m?`${p} (${m})`:p,email:`${f}@openknowledge.local`}]);let h=u??`content`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),y;if(v){let e=!1;try{await simpleGit({baseDir:v,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{y=await withParentLock(async()=>{let e=simpleGit({baseDir:v,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(v);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
113
- `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...y?{versionTag:y}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??l?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(o)?o:50),f=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:d,offset:f,type:p,author:m,excludeAuthor:h},u??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function me(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,u??`content`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function he(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,u??`content`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let d=l.path,f=shadowGit(r);try{let e;try{e=await f.raw(`show`,`${c}:${d}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await f.raw(`show`,`${o}:${d}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,s=stripFrontmatter(e).body,l=diffLines(i,s),u=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
114
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)u.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:u,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ge(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:c,colorSeed:l,clientName:d,clientVersion:f,label:m}=W(a),{docName:h,commitSha:g,versionTag:_}=a,y=typeof h==`string`?h:``,b=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!y){json(n,400,{ok:!1,error:`docName required`});return}if(!b||!/^[0-9a-f]{40}$/i.test(b)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=u??`content`,E=safeDocPath(y,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${b}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${b}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:y,targetSha:b}});let a=t.documents.get(y);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:s,body:h}=stripFrontmatter(e),g=mdManager.parseWithFallback(h),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,s)},ROLLBACK_ORIGIN);let E;if(C){let e=b.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=q(n);E=t||!r.response?r.response:J(r.response),recordContributor(y,o,c,l,formatRollbackSubject(y,b),K({clientName:d,clientVersion:f,label:m}),r.stored),incrementAgentWriteCalls(),Y(n,!t)}j(y,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${y} from=${b.slice(0,8)} duration=${A}ms`),v){let e=`Restored to ${x??b.slice(0,8)}: ${y}`,t=u??`content`;withParentLock(async()=>{let n=simpleGit({baseDir:v,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&p?.setFocus(o,{agentName:c,currentDoc:y,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:b,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function _e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function ve(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=y?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function be(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=m?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function xe(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let Se=1440*60*1e3;async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(s.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>Se){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=l?.()??`main`,t=await listRescueCheckpoints(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function we(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(s.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>Se)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=l?.()??`main`,r=(await listRescueCheckpoints(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
115
- `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Te(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:p}=W(a),{path:m}=a;if(!m||typeof m!=`string`||m.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(m)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(m.includes(`..`)||m.startsWith(`/`)||m.includes(`\0`)||m.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,m);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(m);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(m);recordContributor(y,o,s,c,void 0,K({clientName:l,clientVersion:u,label:p}));let b=typeof i==`function`?i():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),d&&(d.updateDocumentFromMarkdown(y,``),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),f?.(`backlinks`),f?.(`graph`)),f?.(`files`),json(t,200,{ok:!0,docName:y})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function Ee(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function De(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=W(i),{docName:f,newDocName:p}=i;if(typeof f!=`string`||typeof p!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(f)||!isValidRelativeContentPath(p)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(f)||isSystemDoc(p)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(f===p){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!d){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,f),v=resolveContentEntryPath(r,`file`,p);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await H(f,p),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${f} → ${p}`),n=q(t);b=e||!n.response?n.response:J(n.response),recordContributor(p,a,o,s,formatRenameSubject(f,p),K({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Y(t,!e),j(p,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:F(e)})}}async function Oe(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}W(a);let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let p=statSync(l);if(o===`file`&&!p.isFile()||o===`folder`&&!p.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let m=listAffectedDocNames(i(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:m.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await I(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(v,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),L(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:R(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=i();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(d){for(let{fromDocName:e,toDocName:t}of h)d.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),f?.(`backlinks`),f?.(`graph`)}f?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function ke(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}W(a);let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(i(),o,s);await I(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function je(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Me(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(W(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let Ne=`/api/local-op/clone`,Pe=`/api/local-op/open`,Fe=600*1e3,Ie=45e3;async function Le(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!x.tryAcquire(Ne)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=_,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},Fe);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
116
- `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){x.release(Ne);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await Re(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),x.release(Ne)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(Ne)})}async function Re(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=_,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!x.tryAcquire(Pe)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Re(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{x.release(Pe)}}let Be=`/api/local-op/auth/login`,Ve=`/api/local-op/auth/status`,He=`/api/local-op/auth/repos`,Ue=`/api/local-op/auth/signout`,We=`/api/local-op/auth/pat`;async function Ge(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Be)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=_,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Fe),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
117
- `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),x.release(Be)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(Be)})}async function Ke(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Ve)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=_,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
118
- `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{x.release(Ve)}}async function qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(He)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=_,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},Fe);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),x.release(He)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(He)})}async function Je(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Ue)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=_,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{x.release(Ue)}}async function Ye(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(We)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=_,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
119
- `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{x.release(We)}}async function Xe(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!v){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(v)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let Ze=`/api/local-op/auth/set-identity`;async function Qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!v){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!x.tryAcquire(Ze)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(v,n,r),g?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{x.release(Ze)}}async function $e(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function et(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function tt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function nt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function rt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!v){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=simpleGit({baseDir:v,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function at(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function st(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,S.probeAll)}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let lt={"/api/document":Z,"/api/documents":te,"/api/backlinks":Q,"/api/backlink-counts":ne,"/api/forward-links":re,"/api/link-graph":ie,"/api/dead-links":se,"/api/orphans":ae,"/api/hubs":oe,"/api/pages":Ae,"/api/suggest-links":je,"/api/page-headings":Ee,"/api/create-page":Te,"/api/rename":De,"/api/rename-path":Oe,"/api/delete-path":ke,"/api/upload-image":Me,"/api/agent-write":X,"/api/agent-write-md":ee,"/api/agent-patch":ce,"/api/agent-undo":le,"/api/save-version":fe,"/api/history":pe,"/api/diff":he,"/api/rollback":ge,"/api/metrics/reconciliation":_e,"/api/metrics/parse-health":ve,"/api/metrics/agent-presence":be,"/api/principal":ye,"/api/rescue":Ce,"/api/workspace":xe,"/api/sync/status":$e,"/api/sync/trigger":et,"/api/sync/set-enabled":tt,"/api/sync/conflicts":nt,"/api/sync/conflict-content":it,"/api/sync/resolve-conflict":rt,"/api/sync/abort-merge":ct,"/api/local-op/clone":Le,"/api/local-op/open":ze,"/api/local-op/auth/login":Ge,"/api/local-op/auth/status":Ke,"/api/local-op/auth/repos":qe,"/api/local-op/auth/signout":Je,"/api/local-op/auth/pat":Ye,"/api/local-op/auth/identity":Xe,"/api/local-op/auth/set-identity":Qe,"/api/installed-agents":st,"/api/seed/plan":at,"/api/seed/apply":ot};return o&&(lt[`/api/test-reset`]=ue,lt[`/api/test-rescan-backlinks`]=de),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=lt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await we(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await me(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let n=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,n);for(let t=0;t<n;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint$1(e,r);for(let t=0;t<r;t++)write$1(e,n.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min$1(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=findIndexFromEnd(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let n=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function findIndexFromEnd(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var __awaiter$1=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function chain(e,t){let n={has:e,keys:t};return n.reset=$.reset.bind(n),n.bold=$.bold.bind(n),n.dim=$.dim.bind(n),n.italic=$.italic.bind(n),n.underline=$.underline.bind(n),n.inverse=$.inverse.bind(n),n.hidden=$.hidden.bind(n),n.strikethrough=$.strikethrough.bind(n),n.black=$.black.bind(n),n.red=$.red.bind(n),n.green=$.green.bind(n),n.yellow=$.yellow.bind(n),n.blue=$.blue.bind(n),n.magenta=$.magenta.bind(n),n.cyan=$.cyan.bind(n),n.white=$.white.bind(n),n.gray=$.gray.bind(n),n.grey=$.grey.bind(n),n.bgBlack=$.bgBlack.bind(n),n.bgRed=$.bgRed.bind(n),n.bgGreen=$.bgGreen.bind(n),n.bgYellow=$.bgYellow.bind(n),n.bgBlue=$.bgBlue.bind(n),n.bgMagenta=$.bgMagenta.bind(n),n.bgCyan=$.bgCyan.bind(n),n.bgWhite=$.bgWhite.bind(n),n}function init(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[n]):$.enabled?run([n],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},write=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let n=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,n);for(let t=0;t<n;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint(e,r);for(let t=0;t<r;t++)write(e,n.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&BITS7)*n,n*=128,r<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let n=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(readUint8(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!equalityDeep(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let n in e)if(!hasProperty(e,n)||!equalityDeep(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!equalityDeep(e[n],t[n]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&outdatedTimeout<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:getUnixTime()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),equalityDeep(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:getUnixTime()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},encodeAwarenessUpdate=(e,t,n=e.states)=>{let r=t.length,i=createEncoder();writeVarUint(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;writeVarUint(i,r),writeVarUint(i,s),writeVarString(i,JSON.stringify(o))}return toUint8Array(i)},applyAwarenessUpdate=(e,t,n)=>{let r=createDecoder(t),i=getUnixTime(),a=[],o=[],s=[],c=[],l=readVarUint(r);for(let t=0;t<l;t++){let t=readVarUint(r),n=readVarUint(r),l=JSON.parse(readVarString(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(equalityDeep(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,n)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,n))},readSyncStep1=(e,t,n)=>writeSyncStep2(t,n,readVarUint8Array(e)),readSyncStep2=(e,t,n,r)=>{try{applyUpdate(t,readVarUint8Array(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let n=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,n),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case MessageType.Sync:case MessageType.SyncReply:r.writeVarUint(MessageType.Sync),await this.readSyncMessage(r,e,t,n,i!==MessageType.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,r.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(r.decoder)});break;case MessageType.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(r.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),r&&i)r(new OutgoingMessage(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new OutgoingMessage(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(n?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new OutgoingMessage(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new OutgoingMessage(o).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(n?.readOnly){n.send(new OutgoingMessage(o).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new OutgoingMessage(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new IncomingMessage(e);if(readVarString(r.decoder),!(readVarUint(r.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(r.decoder);let i=readVarString(r.decoder),a=null;hasContent(r.decoder)&&(a=readVarString(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new OutgoingMessage(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Forbidden,r=new OutgoingMessage(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new Connection(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:getParameters(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:getParameters(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},DirectConnection=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,n={}){let r=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:getParameters(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),shouldSkipStoreHooks(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=getParameters(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new Document(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof Doc?applyUpdate(l,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:isTransactionOrigin(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:awarenessStatesToArray(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=__getOwnPropNames(t),a=0,o=i.length,s;a<o;a++)s=i[a],!__hasOwnProp.call(e,s)&&s!==n&&__defProp(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(n,`default`,{value:e,enumerable:!0}):n,e)),__require=createRequire(import.meta.url),require_constants=__commonJSMin(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=require_constants(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),require_limiter=__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),require_permessage_deflate=__commonJSMin(((e,t)=>{let n=__require(`zlib`),r=require_buffer_util(),i=require_limiter(),{kStatusCode:a}=require_constants(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),require_validation=__commonJSMin(((e,t)=>{let{isUtf8:n}=__require(`buffer`),{hasBlob:r}=require_constants(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),require_receiver=__commonJSMin(((e,t)=>{let{Writable:n}=__require(`stream`),r=require_permessage_deflate(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=require_constants(),{concat:c,toArrayBuffer:l,unmask:u}=require_buffer_util(),{isValidStatusCode:d,isValidUTF8:f}=require_validation(),p=Buffer[Symbol.species],m=0,h=1,g=2,_=3,v=4,y=5,b=6;t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),require_sender=__commonJSMin(((e,t)=>{let{Duplex:n}=__require(`stream`),{randomFillSync:r}=__require(`crypto`),i=require_permessage_deflate(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=require_constants(),{isBlob:c,isValidStatusCode:l}=require_validation(),{mask:u,toBuffer:d}=require_buffer_util(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m,_=0,v=1,y=2;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(b,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(x,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){b(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function b(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function x(e,t,n){b(e,t,n),e.onerror(t)}})),require_event_target=__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=require_constants(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),require_extension=__commonJSMin(((e,t)=>{let{tokenChars:n}=require_validation();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),require_websocket=__commonJSMin(((e,t)=>{let n=__require(`events`),r=__require(`https`),i=__require(`http`),a=__require(`net`),o=__require(`tls`),{randomBytes:s,createHash:c}=__require(`crypto`),{Duplex:l,Readable:u}=__require(`stream`),{URL:d}=__require(`url`),f=require_permessage_deflate(),p=require_receiver(),m=require_sender(),{isBlob:h}=require_validation(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=require_constants(),{EventTarget:{addEventListener:T,removeEventListener:E}}=require_event_target(),{format:D,parse:O}=require_extension(),{toBuffer:k}=require_buffer_util(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,V),i.on(`drain`,H),i.on(`error`,U),i.on(`message`,G),i.on(`ping`,K),i.on(`pong`,q),a.onerror=Y,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ee),t.on(`data`,Z),t.on(`end`,te),t.on(`error`,Q),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),X(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function F(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;I(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?R:L),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{z(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,I(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){z(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{I(e,SyntaxError(`Invalid URL: ${i}`));return}F(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||z(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){z(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){z(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){z(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){z(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){z(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function I(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function L(e){return e.path=e.socketPath,a.connect(e)}function R(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function z(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,z),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(I,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function B(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function V(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,Z),process.nextTick(J,n._socket),e===1005?n.close():n.close(e,t))}function H(){let e=this[C];e.isPaused||e._socket.resume()}function U(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,Z),process.nextTick(J,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function W(){this[C].emitClose()}function G(e,t){this[C].emit(`message`,e,t)}function K(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function q(e){this[C].emit(`pong`,e)}function J(e){e.resume()}function Y(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,X(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function X(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ee(){let e=this[C];if(this.removeListener(`close`,ee),this.removeListener(`data`,Z),this.removeListener(`end`,te),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,W),e._receiver.on(`finish`,W))}function Z(e){this[C]._receiver.write(e)||this.pause()}function te(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Q(){let e=this[C];this.removeListener(`error`,Q),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),require_stream=__commonJSMin(((e,t)=>{require_websocket();let{Duplex:n}=__require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),require_subprotocol=__commonJSMin(((e,t)=>{let{tokenChars:n}=require_validation();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),require_websocket_server=__commonJSMin(((e,t)=>{let n=__require(`events`),r=__require(`http`),{Duplex:i}=__require(`stream`),{createHash:a}=__require(`crypto`),o=require_extension(),s=require_permessage_deflate(),c=require_subprotocol(),l=require_websocket(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=require_constants(),p=/^[+/0-9A-Za-z]{22}==$/,m=0,h=1,g=2;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=_(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(v,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(v,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{v(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,y);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){x(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){x(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){x(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){x(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){b(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{x(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{x(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return b(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return b(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return b(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
119
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:c,getCurrentBranch:l,contentRoot:u,backlinkIndex:d,signalChannel:f,agentFocusBroadcaster:p,agentPresenceBroadcaster:m,onAgentWrite:h,getSyncEngine:g,localOpCliArgs:_=[`open-knowledge`],projectDir:v,getPrincipal:y,installedAgentsProbe:b}=e,x=createConcurrencyGuard(),S=createInstalledAgentsProbe({probe:b??createOsProbe(process.platform)});function C(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=C(e);if(!t||!existsSync(t))return T;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):T}catch{return T}}function D(e){if(d)try{if(d.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,i()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function A(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>c?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function N(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let P=N();function F(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function I(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function L(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function R(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function z(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function B(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let a=i();a instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},a)}function V(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function H(e,n){return P(async()=>{if(!d)throw Error(`Managed rename requires backlink index support`);let a=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(d.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],p=[];for(let t of[e,...c]){if(l.has(t))continue;let n=z(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&p.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let m=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:R([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,m,async()=>{for(let e of p)d.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?V(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(B(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),d.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await I([e])).get(e)??l.get(e)??readFileSync(a,`utf-8`),e,e,n);await renameTrackedPathInGit(v,a,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(a,o)),L(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=i();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),d.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),d.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),f?.(`files`),f?.(`backlinks`),f?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let U=128;function W(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function G(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function K(e){return{principalId:y?.()?.id,agentType:G(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function q(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function J(e){return{value:e.value}}function Y(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function X(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=W(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let g=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),_=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${_}`,{response:y,stored:b}=q(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);m?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(g.dc.document.getText(`source`),s,l,u),g.dc.document.transact(()=>{applyAgentMarkdownWrite(g.dc.document,`${v}\n`,`append`),g.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},g.origin),recordContributor(o,s,c,l,void 0,K({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Y(p)}finally{m?.touchMode(s,`idle`)}j(o,`agent-write`),h?.(),json(t,200,{ok:!0,timestamp:_,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:g,clientName:_,clientVersion:v,label:y}=W(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=q(b),C=await n.getSession(u,d,{displayName:f,colorSeed:g,clientName:_}),w=new Date().toISOString();try{let e=iconFromClientName(_),t=AGENT_ICON_COLORS[e]??colorFromSeed(g??d);m?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,g,_),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,g,void 0,K({clientName:_,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Y(b)}finally{m?.touchMode(d,`idle`)}j(u,`agent-write-md`),p?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),h?.();let T=D(u),E=k(u),M=A();M===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":G(_)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:M,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function Z(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function te(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function Q(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:d.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ne(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=d.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:d.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=d.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=d.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:d.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:d.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;json(t,200,{ok:!0,deadLinks:d.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ce(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=O(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:g,agentName:_,colorSeed:v,clientName:y,clientVersion:b,label:x}=W(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,g,{displayName:_,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??g);if(m?.setPresence(g,{displayName:_,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),g,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(g,{agentId:g,timestamp:Date.now(),type:`insert`,description:`Patched (${_}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=q(S);recordContributor(f,g,_,v,void 0,K({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Y(S)}}finally{m?.touchMode(g,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}j(f,`agent-patch`),p?.setFocus(g,{agentName:_,currentDoc:f,writeKind:`edit`,ts:Date.now()}),h?.();let D=k(f),M=A();M===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":G(y)});let{response:N}=q(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:M,...N?{summary:N}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function le(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=W(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=O(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let h=typeof i.connectionId==`string`?i.connectionId:void 0;if(!h){json(t,400,{ok:!1,error:`connectionId required`});return}let g=i.scope,_=g===`session`||g===`file`?`session`:`last`;if(!n.hasSession(f,h)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,h),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);m?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,h,o,s,void 0,K({clientName:c,clientVersion:l,label:u}))}finally{m?.touchMode(a,`idle`)}y&&j(f,`agent-undo`),p?.setFocus(h,{agentName:h,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ue(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=O(a);if(isSystemDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),writeFileSync(o,``,`utf-8`),d&&(d.deleteDocument(a),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),f?.(`backlinks`),f?.(`graph`)),f?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!d){json(t,503,{ok:!1,error:`Backlink index not configured`});return}d.rebuildFromDisk(),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),f?.(`backlinks`),f?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:d,agentId:f,agentName:p,clientName:m}=W(s);a.length===0&&(a=d===void 0?[SERVICE_WRITER]:[{id:f,name:m?`${p} (${m})`:p,email:`${f}@openknowledge.local`}]);let h=u??`content`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),y;if(v){let e=!1;try{await simpleGit({baseDir:v,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{y=await withParentLock(async()=>{let e=simpleGit({baseDir:v,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(v);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
120
+ `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...y?{versionTag:y}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function he(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??l?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(o)?o:50),f=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:d,offset:f,type:p,author:m,excludeAuthor:h},u??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ge(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,u??`content`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,u??`content`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let d=l.path,f=shadowGit(r);try{let e;try{e=await f.raw(`show`,`${c}:${d}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await f.raw(`show`,`${o}:${d}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,s=stripFrontmatter(e).body,l=diffLines(i,s),u=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
121
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)u.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:u,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ve(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:c,colorSeed:l,clientName:d,clientVersion:f,label:m}=W(a),{docName:h,commitSha:g,versionTag:_}=a,y=typeof h==`string`?h:``,b=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!y){json(n,400,{ok:!1,error:`docName required`});return}if(!b||!/^[0-9a-f]{40}$/i.test(b)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=u??`content`,E=safeDocPath(y,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${b}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${b}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:y,targetSha:b}});let a=t.documents.get(y);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:s,body:h}=stripFrontmatter(e),g=mdManager.parseWithFallback(h),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,s)},ROLLBACK_ORIGIN);let E;if(C){let e=b.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=q(n);E=t||!r.response?r.response:J(r.response),recordContributor(y,o,c,l,formatRollbackSubject(y,b),K({clientName:d,clientVersion:f,label:m}),r.stored),incrementAgentWriteCalls(),Y(n,!t)}j(y,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${y} from=${b.slice(0,8)} duration=${A}ms`),v){let e=`Restored to ${x??b.slice(0,8)}: ${y}`,t=u??`content`;withParentLock(async()=>{let n=simpleGit({baseDir:v,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&p?.setFocus(o,{agentName:c,currentDoc:y,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:b,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=y?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Se(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=m?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function Ce(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let we=1440*60*1e3;async function Te(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(s.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>we){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=l?.()??`main`,t=await listRescueCheckpoints(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function Ee(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(s.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>we)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=l?.()??`main`,r=(await listRescueCheckpoints(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
122
+ `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function De(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:p}=W(a),{path:m}=a;if(!m||typeof m!=`string`||m.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(m)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(m.includes(`..`)||m.startsWith(`/`)||m.includes(`\0`)||m.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,m);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(m);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(m);recordContributor(y,o,s,c,void 0,K({clientName:l,clientVersion:u,label:p}));let b=typeof i==`function`?i():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),d&&(d.updateDocumentFromMarkdown(y,``),d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),f?.(`backlinks`),f?.(`graph`)),f?.(`files`),json(t,200,{ok:!0,docName:y})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function Oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function ke(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=W(i),{docName:f,newDocName:p}=i;if(typeof f!=`string`||typeof p!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(f)||!isValidRelativeContentPath(p)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(f)||isSystemDoc(p)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(f===p){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!d){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,f),v=resolveContentEntryPath(r,`file`,p);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await H(f,p),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${f} → ${p}`),n=q(t);b=e||!n.response?n.response:J(n.response),recordContributor(p,a,o,s,formatRenameSubject(f,p),K({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Y(t,!e),j(p,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:F(e)})}}async function Ae(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}W(a);let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let p=statSync(l);if(o===`file`&&!p.isFile()||o===`folder`&&!p.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let m=listAffectedDocNames(i(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:m.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await I(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(v,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),L(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:R(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=i();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(d){for(let{fromDocName:e,toDocName:t}of h)d.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));d.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),f?.(`backlinks`),f?.(`graph`)}f?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function je(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}W(a);let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(i(),o,s);await I(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Me(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Ne(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Pe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(W(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let Fe=`/api/local-op/clone`,Ie=`/api/local-op/open`,Le=600*1e3,Re=45e3;async function ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!x.tryAcquire(Fe)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=_,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},Le);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
123
+ `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){x.release(Fe);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await Be(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),x.release(Fe)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(Fe)})}async function Be(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=_,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function Ve(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!x.tryAcquire(Ie)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Be(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{x.release(Ie)}}let He=`/api/local-op/auth/login`,Ue=`/api/local-op/auth/status`,We=`/api/local-op/auth/repos`,Ge=`/api/local-op/auth/signout`,Ke=`/api/local-op/auth/pat`;async function qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(He)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=_,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Le),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
124
+ `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),x.release(He)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(He)})}async function Je(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Ue)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=_,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
125
+ `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{x.release(Ue)}}async function Ye(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(We)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=_,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},Le);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),x.release(We)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),x.release(We)})}async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=_,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{x.release(Ge)}}async function Ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x.tryAcquire(Ke)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=_,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
126
+ `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{x.release(Ke)}}async function Qe(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!v){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(v)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let $e=`/api/local-op/auth/set-identity`;async function et(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!v){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!x.tryAcquire($e)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(v,n,r),g?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{x.release($e)}}async function tt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function nt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function rt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function at(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!v){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=simpleGit({baseDir:v,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function st(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function lt(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,S.probeAll)}async function ut(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=g?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let dt={"/api/document":Z,"/api/documents":te,"/api/backlinks":Q,"/api/backlink-counts":ne,"/api/forward-links":re,"/api/link-graph":ie,"/api/dead-links":se,"/api/orphans":ae,"/api/hubs":oe,"/api/pages":Me,"/api/suggest-links":Ne,"/api/page-headings":Oe,"/api/create-page":De,"/api/rename":ke,"/api/rename-path":Ae,"/api/delete-path":je,"/api/upload-image":Pe,"/api/agent-write":X,"/api/agent-write-md":ee,"/api/agent-patch":ce,"/api/agent-undo":le,"/api/agent-activity":ue,"/api/agent-burst-diff":de,"/api/save-version":me,"/api/history":he,"/api/diff":_e,"/api/rollback":ve,"/api/metrics/reconciliation":ye,"/api/metrics/parse-health":be,"/api/metrics/agent-presence":Se,"/api/principal":xe,"/api/rescue":Te,"/api/workspace":Ce,"/api/sync/status":tt,"/api/sync/trigger":nt,"/api/sync/set-enabled":rt,"/api/sync/conflicts":it,"/api/sync/conflict-content":ot,"/api/sync/resolve-conflict":at,"/api/sync/abort-merge":ut,"/api/local-op/clone":ze,"/api/local-op/open":Ve,"/api/local-op/auth/login":qe,"/api/local-op/auth/status":Je,"/api/local-op/auth/repos":Ye,"/api/local-op/auth/signout":Xe,"/api/local-op/auth/pat":Ze,"/api/local-op/auth/identity":Qe,"/api/local-op/auth/set-identity":et,"/api/installed-agents":lt,"/api/seed/plan":st,"/api/seed/apply":ct};return o&&(dt[`/api/test-reset`]=fe,dt[`/api/test-rescan-backlinks`]=pe),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=dt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ee(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ge(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let n=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,n);for(let t=0;t<n;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint$1(e,r);for(let t=0;t<r;t++)write$1(e,n.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min$1(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=findIndexFromEnd(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let n=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function findIndexFromEnd(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var __awaiter$1=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function chain(e,t){let n={has:e,keys:t};return n.reset=$.reset.bind(n),n.bold=$.bold.bind(n),n.dim=$.dim.bind(n),n.italic=$.italic.bind(n),n.underline=$.underline.bind(n),n.inverse=$.inverse.bind(n),n.hidden=$.hidden.bind(n),n.strikethrough=$.strikethrough.bind(n),n.black=$.black.bind(n),n.red=$.red.bind(n),n.green=$.green.bind(n),n.yellow=$.yellow.bind(n),n.blue=$.blue.bind(n),n.magenta=$.magenta.bind(n),n.cyan=$.cyan.bind(n),n.white=$.white.bind(n),n.gray=$.gray.bind(n),n.grey=$.grey.bind(n),n.bgBlack=$.bgBlack.bind(n),n.bgRed=$.bgRed.bind(n),n.bgGreen=$.bgGreen.bind(n),n.bgYellow=$.bgYellow.bind(n),n.bgBlue=$.bgBlue.bind(n),n.bgMagenta=$.bgMagenta.bind(n),n.bgCyan=$.bgCyan.bind(n),n.bgWhite=$.bgWhite.bind(n),n}function init(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[n]):$.enabled?run([n],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},write=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let n=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,n);for(let t=0;t<n;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;writeVarUint(e,r);for(let t=0;t<r;t++)write(e,n.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=min(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&BITS7)*n,n*=128,r<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let n=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(readUint8(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!equalityDeep(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let n in e)if(!hasProperty(e,n)||!equalityDeep(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!equalityDeep(e[n],t[n]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&outdatedTimeout<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:getUnixTime()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),equalityDeep(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:getUnixTime()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},encodeAwarenessUpdate=(e,t,n=e.states)=>{let r=t.length,i=createEncoder();writeVarUint(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;writeVarUint(i,r),writeVarUint(i,s),writeVarString(i,JSON.stringify(o))}return toUint8Array(i)},applyAwarenessUpdate=(e,t,n)=>{let r=createDecoder(t),i=getUnixTime(),a=[],o=[],s=[],c=[],l=readVarUint(r);for(let t=0;t<l;t++){let t=readVarUint(r),n=readVarUint(r),l=JSON.parse(readVarString(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(equalityDeep(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,n)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,n))},readSyncStep1=(e,t,n)=>writeSyncStep2(t,n,readVarUint8Array(e)),readSyncStep2=(e,t,n,r)=>{try{applyUpdate(t,readVarUint8Array(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let n=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,n),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case MessageType.Sync:case MessageType.SyncReply:r.writeVarUint(MessageType.Sync),await this.readSyncMessage(r,e,t,n,i!==MessageType.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,r.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(r.decoder)});break;case MessageType.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(r.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),r&&i)r(new OutgoingMessage(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new OutgoingMessage(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(n?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new OutgoingMessage(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new OutgoingMessage(o).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(n?.readOnly){n.send(new OutgoingMessage(o).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new OutgoingMessage(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new IncomingMessage(e);if(readVarString(r.decoder),!(readVarUint(r.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(r.decoder);let i=readVarString(r.decoder),a=null;hasContent(r.decoder)&&(a=readVarString(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new OutgoingMessage(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Forbidden,r=new OutgoingMessage(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new Connection(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:getParameters(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:getParameters(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},DirectConnection=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,n={}){let r=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:getParameters(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),shouldSkipStoreHooks(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=getParameters(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new Document(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof Doc?applyUpdate(l,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:isTransactionOrigin(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:awarenessStatesToArray(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=__getOwnPropNames(t),a=0,o=i.length,s;a<o;a++)s=i[a],!__hasOwnProp.call(e,s)&&s!==n&&__defProp(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(n,`default`,{value:e,enumerable:!0}):n,e)),__require=createRequire(import.meta.url),require_constants=__commonJSMin(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=require_constants(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),require_limiter=__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),require_permessage_deflate=__commonJSMin(((e,t)=>{let n=__require(`zlib`),r=require_buffer_util(),i=require_limiter(),{kStatusCode:a}=require_constants(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),require_validation=__commonJSMin(((e,t)=>{let{isUtf8:n}=__require(`buffer`),{hasBlob:r}=require_constants(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),require_receiver=__commonJSMin(((e,t)=>{let{Writable:n}=__require(`stream`),r=require_permessage_deflate(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=require_constants(),{concat:c,toArrayBuffer:l,unmask:u}=require_buffer_util(),{isValidStatusCode:d,isValidUTF8:f}=require_validation(),p=Buffer[Symbol.species],m=0,h=1,g=2,_=3,v=4,y=5,b=6;t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),require_sender=__commonJSMin(((e,t)=>{let{Duplex:n}=__require(`stream`),{randomFillSync:r}=__require(`crypto`),i=require_permessage_deflate(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=require_constants(),{isBlob:c,isValidStatusCode:l}=require_validation(),{mask:u,toBuffer:d}=require_buffer_util(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m,_=0,v=1,y=2;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(b,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(x,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){b(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function b(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function x(e,t,n){b(e,t,n),e.onerror(t)}})),require_event_target=__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=require_constants(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),require_extension=__commonJSMin(((e,t)=>{let{tokenChars:n}=require_validation();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),require_websocket=__commonJSMin(((e,t)=>{let n=__require(`events`),r=__require(`https`),i=__require(`http`),a=__require(`net`),o=__require(`tls`),{randomBytes:s,createHash:c}=__require(`crypto`),{Duplex:l,Readable:u}=__require(`stream`),{URL:d}=__require(`url`),f=require_permessage_deflate(),p=require_receiver(),m=require_sender(),{isBlob:h}=require_validation(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=require_constants(),{EventTarget:{addEventListener:T,removeEventListener:E}}=require_event_target(),{format:D,parse:O}=require_extension(),{toBuffer:k}=require_buffer_util(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,V),i.on(`drain`,H),i.on(`error`,U),i.on(`message`,G),i.on(`ping`,K),i.on(`pong`,q),a.onerror=Y,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ee),t.on(`data`,Z),t.on(`end`,te),t.on(`error`,Q),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),X(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){B(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function F(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;I(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?R:L),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{z(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,I(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){z(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{I(e,SyntaxError(`Invalid URL: ${i}`));return}F(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||z(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){z(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){z(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){z(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){z(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){z(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function I(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function L(e){return e.path=e.socketPath,a.connect(e)}function R(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function z(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,z),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(I,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function B(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function V(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,Z),process.nextTick(J,n._socket),e===1005?n.close():n.close(e,t))}function H(){let e=this[C];e.isPaused||e._socket.resume()}function U(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,Z),process.nextTick(J,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function W(){this[C].emitClose()}function G(e,t){this[C].emit(`message`,e,t)}function K(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function q(e){this[C].emit(`pong`,e)}function J(e){e.resume()}function Y(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,X(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function X(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ee(){let e=this[C];if(this.removeListener(`close`,ee),this.removeListener(`data`,Z),this.removeListener(`end`,te),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,W),e._receiver.on(`finish`,W))}function Z(e){this[C]._receiver.write(e)||this.pause()}function te(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Q(){let e=this[C];this.removeListener(`error`,Q),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),require_stream=__commonJSMin(((e,t)=>{require_websocket();let{Duplex:n}=__require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),require_subprotocol=__commonJSMin(((e,t)=>{let{tokenChars:n}=require_validation();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),require_websocket_server=__commonJSMin(((e,t)=>{let n=__require(`events`),r=__require(`http`),{Duplex:i}=__require(`stream`),{createHash:a}=__require(`crypto`),o=require_extension(),s=require_permessage_deflate(),c=require_subprotocol(),l=require_websocket(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=require_constants(),p=/^[+/0-9A-Za-z]{22}==$/,m=0,h=1,g=2;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=_(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(v,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(v,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{v(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,y);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){x(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){x(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){x(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){x(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){b(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{x(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{x(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return b(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return b(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return b(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
120
127
  `).join(`\r
121
128
  `)),i.removeListener(`error`,y),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(v,this)})),l(p,r)}};function _(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function v(e){e._state=2,e.emit(`close`)}function y(){this.destroy()}function b(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
122
129
  `)+`\r
@@ -131,6 +138,6 @@ Append-only record of ingests, research, consolidations, and maintenance. Each e
131
138
  `):[]){let t=e.trim();if(!t)continue;let n=join(this.projectDir,t),r=relative(this.contentDir,n);!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&a.add(t)}}catch{}if(t.length>0){let n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));s.length>0&&await e.git.raw([`rm`,`--cached`,`--`,...s]);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){log.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.transitionTo(`idle`);return}log.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[];try{let n=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,i,c])).trim();if(n){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n.split(`
132
139
  `)){let n=t.trim();if(!n)continue;let r=e.get(n)??relative(this.contentDir,join(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await resolveGitIdentity(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!SHA_HEX_40.test(g)){log.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=classifyGitError(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){log.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{unlinkSync(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);let r=100;for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let a=(await i.git.raw([`write-tree`])).trim();if(a===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let o=await resolveGitIdentity(this.projectDir),s=o?.name??`Open Knowledge`,c=o?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:c,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:c});let l=(await i.git.raw([`commit-tree`,a,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!l||!SHA_HEX_40.test(l))return log.warn({raw:l},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,l,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return l}finally{try{unlinkSync(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
133
140
  `).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=join(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=relative(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=relative(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
134
- `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=getLogger(`server`);initTelemetry();let _=resolve(t,`.open-knowledge`);acquireServerLock(_,{port:e.port??0,worktreeRoot:n});let v,y,b,x,S,C,w=null,T=null,E=null,D=null;function O(e){w?.signal(e)}try{v=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),y=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:v}),b={current:u},x=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:b,contentRoot:d,backlinkIndex:y,getCurrentBranch:()=>z?.getLastKnownBranch()??null,getPrincipal:()=>D}),S=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[x.extension]}),w=new CC1Broadcaster(S),T=new AgentFocusBroadcaster(S),E=new AgentPresenceBroadcaster(S),C=new AgentSessionManager(S);let m=createLiveDerivedIndexExtension({backlinkIndex:y,signalChannel:O});S.configuration.extensions.push(m),S.configuration.extensions.push({async onAuthenticate(e){try{let t=e.token;if(!t)return;let n=JSON.parse(t),r=e.context;typeof n.principalId==`string`&&(D&&n.principalId===D.id?r.principalId=D.id:D?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:D.id})):r.principalId=n.principalId),typeof n.tabSessionId==`string`&&(r.tabSessionId=n.tabSessionId),r.kind=`human`}catch{}}});let g=createApiExtension({hocuspocus:S,sessionManager:C,contentDir:t,getFileIndex:()=>R?R.getFileIndex():new Map,getAliasMap:()=>R?R.getAliasMap():new Map,enableTestRoutes:l,shadowRef:b,flushGitCommit:()=>x.flushPendingGitCommit(),getCurrentBranch:()=>z?.getLastKnownBranch()??null,contentRoot:d,backlinkIndex:y,signalChannel:O,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>B,localOpCliArgs:h,projectDir:n,getPrincipal:()=>D});S.configuration.extensions.push(g),S.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:b,contentRoot:d,getCurrentBranch:()=>z?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(_),e}let k=null;function A(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function j(e){let t=S.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let M=(e,t)=>applyExternalChange(S,e,t);function N(e){return e.kind===`rename`?e.newDocName:e.docName}async function P(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),y.updateDocumentFromMarkdown(e.docName,e.content),y.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),O(`files`),O(`backlinks`),O(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=S.documents.get(t);if(!r){y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),O(`backlinks`),O(`graph`);return}let i=getReconciledBase(t)??``,a=j(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),O(`backlinks`),O(`graph`);break;case`clean`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=S.documents.get(t);if(!n){y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),O(`files`),O(`backlinks`),O(`graph`);return}let r=getReconciledBase(t)??``,i=j(t)??``,a=i!==r;if(a&&b.current){let e=b.current,n=z?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),S.closeConnections(t),await S.unloadDocument(n),O(`files`),O(`backlinks`),O(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=S.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),y.renameDocument(t,n,r),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),O(`files`),O(`backlinks`),O(`graph`);break}case`conflict`:{let{docName:t}=e,n=S.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:N(e)},`[reconcile] failed to handle ${e.kind} for ${N(e)}`)}}let F=[];async function I(e){if(isBatchInProgress()){F.push(e);return}await P(e)}async function L(){let e=F.splice(0,F.length);for(let t of e)await P(t)}let R=null,z=null,B=null,V=null;async function H(e){if(S.documents.size===0)return;let t=!1,n=new Promise(e=>{S.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(S.documents.keys());S.closeConnections(),S.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(S.documents.keys()),i=[],o=[];if(b.current){for(let e of n)if(!isSystemDoc(e))try{let t=j(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=A(b.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:b.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function U(){return V||(V=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([K.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=S.documents.size;try{try{try{z&&=(await z.unsubscribe(),null),R&&=(await R.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{w?.destroy(),E?.destroy(),k&&=(await k.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await C.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await H(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await x.flushPendingGitCommit(),await x.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{B&&=(await B.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(b.current){try{let e=(await simpleGit({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(b.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(b.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(_)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),V)}let W=[];async function G(){try{D=await loadPrincipal(t),g.info({principalId:D.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!b.current)try{b.current=await initShadowRepo(n),g.info({gitDir:b.current.gitDir},`[server] history repo initialized at ${b.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),W.push(`shadow-repo`)}if(b.current)try{await shadowGit(b.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{b.current=await initShadowRepo(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),b.current=void 0,W.includes(`shadow-repo`)||W.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(b.current)try{let e=resolve(b.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await simpleGit({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await simpleGit({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(b.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&g.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){g.error({err:e},`[server] managed rename recovery failed`),W.push(`managed-rename-recovery`)}try{k=await S.openDirectConnection(SYSTEM_DOC_NAME)}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),W.push(`cc1-push`)}try{R=await startWatcher(t,I,v),y.rebuildFromDisk(getActiveBranch()),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),W.push(`file-watcher`)}try{z=await startHeadWatcher(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),S.flushPendingStores(),await x.flushPendingGitCommit(),setBatchInProgress(!0),b.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of S.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=j(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(b.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=F.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await L();else{incrementBranchSwitch(),F.splice(0,F.length),switchReconciledBaseScope(r),y.switchBranch(r);for(let[e,n]of S.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=j(e)??``;if(i!==t&&b.current){let t=b.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);M(e,a),setReconciledBase(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:S.documents.size},`[branch-switch] loaded branch ${r} (${S.documents.size} docs)`),y.rebuildFromDisk(r),y.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),b.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of S.documents)if(!isSystemDoc(t))try{let n=await readParkedState(b.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:M(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:M(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&b.current)try{let t=shadowGit(b.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
141
+ `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=getLogger(`server`);initTelemetry();let _=resolve(t,`.open-knowledge`);acquireServerLock(_,{port:e.port??0,worktreeRoot:n});let v,y,b,x,S,C,w=null,T=null,E=null,D=null;function O(e){w?.signal(e)}try{v=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),y=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:v}),b={current:u},x=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:b,contentRoot:d,backlinkIndex:y,getCurrentBranch:()=>z?.getLastKnownBranch()??null,getPrincipal:()=>D,onAgentCommit:()=>w?.signal(`session-activity`)}),S=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[x.extension]}),w=new CC1Broadcaster(S),T=new AgentFocusBroadcaster(S),E=new AgentPresenceBroadcaster(S),C=new AgentSessionManager(S);let m=createLiveDerivedIndexExtension({backlinkIndex:y,signalChannel:O});S.configuration.extensions.push(m),S.configuration.extensions.push({async onAuthenticate(e){try{let t=e.token;if(!t)return;let n=JSON.parse(t),r=e.context;typeof n.principalId==`string`&&(D&&n.principalId===D.id?r.principalId=D.id:D?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:D.id})):r.principalId=n.principalId),typeof n.tabSessionId==`string`&&(r.tabSessionId=n.tabSessionId),r.kind=`human`}catch{}}});let g=createApiExtension({hocuspocus:S,sessionManager:C,contentDir:t,getFileIndex:()=>R?R.getFileIndex():new Map,getAliasMap:()=>R?R.getAliasMap():new Map,enableTestRoutes:l,shadowRef:b,flushGitCommit:()=>x.flushPendingGitCommit(),getCurrentBranch:()=>z?.getLastKnownBranch()??null,contentRoot:d,backlinkIndex:y,signalChannel:O,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>B,localOpCliArgs:h,projectDir:n,getPrincipal:()=>D});S.configuration.extensions.push(g),S.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:b,contentRoot:d,getCurrentBranch:()=>z?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(_),e}let k=null;function A(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function j(e){let t=S.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let M=(e,t)=>applyExternalChange(S,e,t);function N(e){return e.kind===`rename`?e.newDocName:e.docName}async function P(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),y.updateDocumentFromMarkdown(e.docName,e.content),y.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),O(`files`),O(`backlinks`),O(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=S.documents.get(t);if(!r){y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),O(`backlinks`),O(`graph`);return}let i=getReconciledBase(t)??``,a=j(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),O(`backlinks`),O(`graph`);break;case`clean`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{M(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=S.documents.get(t);if(!n){y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),O(`files`),O(`backlinks`),O(`graph`);return}let r=getReconciledBase(t)??``,i=j(t)??``,a=i!==r;if(a&&b.current){let e=b.current,n=z?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),S.closeConnections(t),await S.unloadDocument(n),O(`files`),O(`backlinks`),O(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=S.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),y.renameDocument(t,n,r),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),O(`files`),O(`backlinks`),O(`graph`);break}case`conflict`:{let{docName:t}=e,n=S.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:N(e)},`[reconcile] failed to handle ${e.kind} for ${N(e)}`)}}let F=[];async function I(e){if(isBatchInProgress()){F.push(e);return}await P(e)}async function L(){let e=F.splice(0,F.length);for(let t of e)await P(t)}let R=null,z=null,B=null,V=null;async function H(e){if(S.documents.size===0)return;let t=!1,n=new Promise(e=>{S.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(S.documents.keys());S.closeConnections(),S.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(S.documents.keys()),i=[],o=[];if(b.current){for(let e of n)if(!isSystemDoc(e))try{let t=j(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=A(b.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:b.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function U(){return V||(V=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([K.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=S.documents.size;try{try{try{z&&=(await z.unsubscribe(),null),R&&=(await R.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{w?.destroy(),E?.destroy(),k&&=(await k.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await C.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await H(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await x.flushPendingGitCommit(),await x.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{B&&=(await B.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(b.current){try{let e=(await simpleGit({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(b.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(b.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(_)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),V)}let W=[];async function G(){try{D=await loadPrincipal(t),g.info({principalId:D.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!b.current)try{b.current=await initShadowRepo(n),g.info({gitDir:b.current.gitDir},`[server] history repo initialized at ${b.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),W.push(`shadow-repo`)}if(b.current)try{await shadowGit(b.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{b.current=await initShadowRepo(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),b.current=void 0,W.includes(`shadow-repo`)||W.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(b.current)try{let e=resolve(b.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await simpleGit({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await simpleGit({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(b.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&g.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){g.error({err:e},`[server] managed rename recovery failed`),W.push(`managed-rename-recovery`)}try{k=await S.openDirectConnection(SYSTEM_DOC_NAME)}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),W.push(`cc1-push`)}try{R=await startWatcher(t,I,v),y.rebuildFromDisk(getActiveBranch()),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),W.push(`file-watcher`)}try{z=await startHeadWatcher(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),S.flushPendingStores(),await x.flushPendingGitCommit(),setBatchInProgress(!0),b.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of S.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=j(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(b.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=F.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await L();else{incrementBranchSwitch(),F.splice(0,F.length),switchReconciledBaseScope(r),y.switchBranch(r);for(let[e,n]of S.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=j(e)??``;if(i!==t&&b.current){let t=b.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);M(e,a),setReconciledBase(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:S.documents.size},`[branch-switch] loaded branch ${r} (${S.documents.size} docs)`),y.rebuildFromDisk(r),y.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),b.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of S.documents)if(!isSystemDoc(t))try{let n=await readParkedState(b.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:M(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:M(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&b.current)try{let t=shadowGit(b.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
135
142
  `))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&b.current&&n>0){let t=d??`content`;try{let n=await commitUpstreamImport(b.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),W.push(`head-watcher`)}let e=h?.[0]??`open-knowledge`,r=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):e} auth git-credential`];try{B=new SyncEngine({projectDir:n,contentDir:t,contentFilter:v,contentRoot:d,credentialArgs:r,cc1Broadcaster:w,setBatchInProgress,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await B.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),B=null}}let K=G();return{hocuspocus:S,sessionManager:C,cc1Broadcaster:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,contentFilter:v,destroy:U,ready:K,degraded:W,lockDir:_,get syncEngine(){return B}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`);initTelemetry();let{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-BlhyhsXg.mjs`),{updateServerLockPort:s}=await import(`./server-lock-CJkiM3qX.mjs`),c=!1;!t&&e.ensureProjectGitFn&&(c=!!(await e.ensureProjectGitFn()).didInit);let l=!1;if(!t&&e.autoInitFn)try{l=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let u=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:d,destroy:f,ready:p,degraded:m,lockDir:h,agentPresenceBroadcaster:g}=u,_=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){d.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),v=new o({noServer:!0});v.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let y=e.keepaliveGraceMs??1e4,b=new Map,x=new Set,S=!1;_.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=b.get(n);e!==void 0&&(clearTimeout(e),b.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{g?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(b.delete(n),S)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await u.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{u.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{g?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();x.add(e),e.finally(()=>x.delete(e))},y);e.unref?.(),b.set(n,e),i.info({connectionId:n,graceMs:y},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=d.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let C=null;r!==null&&(C=attachIdleShutdown({httpServer:_,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await f()})})),await new Promise((t,n)=>{let r=e=>n(e);_.once(`error`,r),_.listen(e.port,e.host,()=>{_.removeListener(`error`,r),t()})});let w=_.address(),T=typeof w==`object`&&w?w.port:e.port??0;if(s(h,T),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let E=!1;return{httpServer:_,destroy:async()=>{if(!E){E=!0,S=!0,C?.detach();for(let e of b.values())clearTimeout(e);b.clear(),x.size>0&&await Promise.allSettled([...x]),await new Promise(e=>{_.close(()=>e())}),await f(),await shutdownTelemetry()}},lockDir:h,contentDir:e.contentDir,port:T,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}const SIDECAR_FILENAME=`skill-installed-version`,BUNDLED_SKILL_CANDIDATES=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;function resolveBundledSkillDir(){let e=[];for(let t of BUNDLED_SKILL_CANDIDATES){let n=fileURLToPath(new URL(t,import.meta.url));if(existsSync(n))return n;e.push(n)}throw Error(`Bundled skill asset directory not found. Tried: ${e.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.open-knowledge`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a)return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}export{commitWipFromTree as $,classifyEvents as A,AgentPresenceBroadcaster as At,writeTracker as B,getLogger as Bt,SeedPrerequisiteError as C,initTelemetry as Ct,starterFolderRule as D,withSpanSync as Dt,STARTER_FOLDERS as E,withSpan as Et,pathToDocName as F,AGENT_ID_RE as Ft,createPersistenceExtension as G,containsConflictMarkers as H,registerWrite as I,toBroadcasterKey as It,GIT_UPSTREAM_WRITER as J,safeContentPath as K,removeLastKnownHash as L,validateAgentId as Lt,evictStaleTrackerEntries as M,handleCollabSocketError as Mt,isSelfWrite as N,incrementCollabSocketFilteredError as Nt,rewriteMarkdownLinksForDocumentRename as O,CC1Broadcaster as Ot,lastKnownHash as P,incrementServerObserverFire as Pt,commitWip as Q,startWatcher as R,AgentFocusBroadcaster as Rt,SEED_CONFIG_FILENAME as S,getTracer as St,LOG_MD_TEMPLATE as T,shutdownTelemetry as Tt,reconcile as U,CONFLICT_MARKER_RE as V,loggerFactory as Vt,splitMarkdownBlocks as W,buildWipTree as X,SERVICE_WRITER as Y,commitUpstreamImport as Z,MANAGED_RENAME_ORIGIN as _,parseWriterId as _t,parseKeepaliveConnectionId as a,shadowGit as at,safeSubdir as b,applyAgentMarkdownWrite as bt,OBSERVER_SYNC_ORIGIN as c,UiLockCollisionError as ct,createLiveDerivedIndexExtension as d,releaseUiLock as dt,initShadowRepo as et,readBranchFromHead as f,updateUiLockPort as ft,attachIdleShutdown as g,getWipRefPattern as gt,createContentFilter as h,getShadowRepoPath as ht,bootServer as i,saveVersion as it,contentHash as j,getMetrics as jt,rewriteWikiLinksForDocumentRename as k,isSystemDoc as kt,isPairedWriteOrigin as l,acquireUiLock as lt,applyExternalChange as m,recordContributor as mt,ProjectGitInitError as n,safetyCheckpoint as nt,createServer$1 as o,BacklinkIndex as ot,FILE_WATCHER_ORIGIN as p,contributorCount as pt,FILE_SYSTEM_WRITER as q,ensureProjectGit as r,saveInMemoryCheckpoint as rt,createServerObserverExtension as s,extractWikiLinksFromMarkdown as st,installUserSkill as t,listRescueCheckpoints as tt,loadPrincipal as u,readUiLock as ut,ROLLBACK_ORIGIN as v,readContributors as vt,applySeed as w,setActiveSpanAttributes as wt,planSeed as x,getMeter as xt,createApiExtension as y,AgentSessionManager as yt,updateLastKnownHash as z,PinoLogger as zt};
136
- //# sourceMappingURL=src-DBQiBMMB.mjs.map
143
+ //# sourceMappingURL=src-C6N2KCTo.mjs.map