@undefineds.co/xpod 0.3.52 → 0.3.54

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 (119) hide show
  1. package/config/cli.json +72 -0
  2. package/config/components-ignore.json +21 -0
  3. package/config/extensions.local.initializer.json +77 -8
  4. package/config/resolver.json +72 -4
  5. package/dist/api/ApiServer.d.ts +12 -0
  6. package/dist/api/ApiServer.js +14 -3
  7. package/dist/api/ApiServer.js.map +1 -1
  8. package/dist/api/auth/NodeTokenAuthenticator.d.ts +0 -8
  9. package/dist/api/auth/NodeTokenAuthenticator.js +3 -46
  10. package/dist/api/auth/NodeTokenAuthenticator.js.map +1 -1
  11. package/dist/api/container/local.js +5 -36
  12. package/dist/api/container/local.js.map +1 -1
  13. package/dist/api/container/routes.js +6 -0
  14. package/dist/api/container/routes.js.map +1 -1
  15. package/dist/api/handlers/EdgeNodeSignalHandler.js +25 -3
  16. package/dist/api/handlers/EdgeNodeSignalHandler.js.map +1 -1
  17. package/dist/api/handlers/ReachabilityHandler.d.ts +13 -0
  18. package/dist/api/handlers/ReachabilityHandler.js +388 -0
  19. package/dist/api/handlers/ReachabilityHandler.js.map +1 -0
  20. package/dist/api/runs/InngestRunExecutionBackend.d.ts +2 -2
  21. package/dist/api/tasks/InngestTaskScheduler.d.ts +4 -4
  22. package/dist/cli/lib/oidc-auth.js +27 -3
  23. package/dist/cli/lib/oidc-auth.js.map +1 -1
  24. package/dist/components/components.jsonld +14 -2
  25. package/dist/components/context.jsonld +439 -3
  26. package/dist/edge/EdgeNodeAgent.d.ts +43 -0
  27. package/dist/edge/EdgeNodeAgent.js +208 -1
  28. package/dist/edge/EdgeNodeAgent.js.map +1 -1
  29. package/dist/edge/EdgeNodeAgent.jsonld +166 -0
  30. package/dist/edge/EdgeNodeAgentInitializer.d.ts +20 -2
  31. package/dist/edge/EdgeNodeAgentInitializer.js +53 -2
  32. package/dist/edge/EdgeNodeAgentInitializer.js.map +1 -1
  33. package/dist/edge/EdgeNodeAgentInitializer.jsonld +409 -0
  34. package/dist/edge/reachability/CanonicalFetch.d.ts +7 -0
  35. package/dist/edge/reachability/CanonicalFetch.js +49 -0
  36. package/dist/edge/reachability/CanonicalFetch.js.map +1 -0
  37. package/dist/edge/reachability/CanonicalFetch.jsonld +25 -0
  38. package/dist/edge/reachability/ManagedClientFetch.d.ts +26 -0
  39. package/dist/edge/reachability/ManagedClientFetch.js +155 -0
  40. package/dist/edge/reachability/ManagedClientFetch.js.map +1 -0
  41. package/dist/edge/reachability/ManagedClientFetch.jsonld +83 -0
  42. package/dist/edge/reachability/ManagedClientP2PSmoke.d.ts +16 -0
  43. package/dist/edge/reachability/ManagedClientP2PSmoke.js +31 -0
  44. package/dist/edge/reachability/ManagedClientP2PSmoke.js.map +1 -0
  45. package/dist/edge/reachability/ManagedClientP2PSmoke.jsonld +65 -0
  46. package/dist/edge/reachability/ManagedRouteSelector.d.ts +7 -0
  47. package/dist/edge/reachability/ManagedRouteSelector.js +43 -0
  48. package/dist/edge/reachability/ManagedRouteSelector.js.map +1 -0
  49. package/dist/edge/reachability/ManagedRouteSelector.jsonld +29 -0
  50. package/dist/edge/reachability/P2PDataPlane.d.ts +37 -0
  51. package/dist/edge/reachability/P2PDataPlane.js +160 -0
  52. package/dist/edge/reachability/P2PDataPlane.js.map +1 -0
  53. package/dist/edge/reachability/P2PDataPlane.jsonld +134 -0
  54. package/dist/edge/reachability/P2PRealnetAcceptance.d.ts +74 -0
  55. package/dist/edge/reachability/P2PRealnetAcceptance.js +240 -0
  56. package/dist/edge/reachability/P2PRealnetAcceptance.js.map +1 -0
  57. package/dist/edge/reachability/P2PRealnetAcceptance.jsonld +283 -0
  58. package/dist/edge/reachability/P2PSignalingClient.d.ts +24 -0
  59. package/dist/edge/reachability/P2PSignalingClient.js +138 -0
  60. package/dist/edge/reachability/P2PSignalingClient.js.map +1 -0
  61. package/dist/edge/reachability/P2PSignalingClient.jsonld +79 -0
  62. package/dist/edge/reachability/ReachabilitySessionService.d.ts +55 -0
  63. package/dist/edge/reachability/ReachabilitySessionService.js +439 -0
  64. package/dist/edge/reachability/ReachabilitySessionService.js.map +1 -0
  65. package/dist/edge/reachability/ReachabilitySessionService.jsonld +196 -0
  66. package/dist/edge/reachability/RouteSetBuilder.d.ts +2 -0
  67. package/dist/edge/reachability/RouteSetBuilder.js +205 -0
  68. package/dist/edge/reachability/RouteSetBuilder.js.map +1 -0
  69. package/dist/edge/reachability/TcpP2PDataPlaneTransport.d.ts +47 -0
  70. package/dist/edge/reachability/TcpP2PDataPlaneTransport.js +281 -0
  71. package/dist/edge/reachability/TcpP2PDataPlaneTransport.js.map +1 -0
  72. package/dist/edge/reachability/TcpP2PDataPlaneTransport.jsonld +183 -0
  73. package/dist/edge/reachability/TcpP2PSignalingSession.d.ts +149 -0
  74. package/dist/edge/reachability/TcpP2PSignalingSession.js +699 -0
  75. package/dist/edge/reachability/TcpP2PSignalingSession.js.map +1 -0
  76. package/dist/edge/reachability/TcpP2PSignalingSession.jsonld +474 -0
  77. package/dist/edge/reachability/index.d.ts +12 -0
  78. package/dist/edge/reachability/index.js +29 -0
  79. package/dist/edge/reachability/index.js.map +1 -0
  80. package/dist/edge/reachability/types.d.ts +114 -0
  81. package/dist/edge/reachability/types.js +3 -0
  82. package/dist/edge/reachability/types.js.map +1 -0
  83. package/dist/edge/reachability/types.jsonld +457 -0
  84. package/dist/http/EdgeNodeProxyHttpHandler.d.ts +2 -0
  85. package/dist/http/EdgeNodeProxyHttpHandler.js +19 -1
  86. package/dist/http/EdgeNodeProxyHttpHandler.js.map +1 -1
  87. package/dist/http/EdgeNodeProxyHttpHandler.jsonld +8 -0
  88. package/dist/identity/drizzle/EdgeNodeRepository.js +1 -1
  89. package/dist/identity/drizzle/EdgeNodeRepository.js.map +1 -1
  90. package/dist/index.d.ts +4 -1
  91. package/dist/index.js +5 -2
  92. package/dist/index.js.map +1 -1
  93. package/dist/runtime/bootstrap.js +8 -0
  94. package/dist/runtime/bootstrap.js.map +1 -1
  95. package/dist/service/EdgeNodeSignalClient.js +5 -1
  96. package/dist/service/EdgeNodeSignalClient.js.map +1 -1
  97. package/dist/storage/rdf/PostgresRdfEngine.d.ts +1 -0
  98. package/dist/storage/rdf/PostgresRdfEngine.js +53 -37
  99. package/dist/storage/rdf/PostgresRdfEngine.js.map +1 -1
  100. package/dist/storage/rdf/PostgresRdfEngine.jsonld +4 -0
  101. package/dist/test-utils/index.d.ts +2 -0
  102. package/dist/test-utils/index.js +3 -1
  103. package/dist/test-utils/index.js.map +1 -1
  104. package/dist/test-utils/local-managed-client-p2p-e2e-smoke.d.ts +63 -0
  105. package/dist/test-utils/local-managed-client-p2p-e2e-smoke.js +478 -0
  106. package/dist/test-utils/local-managed-client-p2p-e2e-smoke.js.map +1 -0
  107. package/package.json +11 -4
  108. package/static/app/assets/_commonjsHelpers-B-UnjaXt.js +1 -0
  109. package/static/app/assets/index-AaQ1qxhy.js +171 -0
  110. package/static/app/assets/inrupt-smoke.js +131 -0
  111. package/static/app/assets/main.css +1 -0
  112. package/static/app/assets/main.js +6 -6
  113. package/static/app/index.html +2 -1
  114. package/static/app/inrupt-smoke.html +14 -0
  115. package/static/app/reachability.html +221 -0
  116. package/static/app/reachability.svg +7 -0
  117. package/static/app/reachability.webmanifest +18 -0
  118. package/static/app/signal-pod.html +293 -0
  119. package/static/app/assets/index.css +0 -1
@@ -0,0 +1,171 @@
1
+ import{r as requireEvents,_ as __vitePreload,v as v4}from"./inrupt-smoke.js";import{g as getDefaultExportFromCjs}from"./_commonjsHelpers-B-UnjaXt.js";const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let r=0;r<n;r++)e+=urlAlphabet[t[r]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:r,query:i}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,r,i=!1){this[SubqueryConfig]={sql:e,selection:t,alias:r,isWith:i}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const i=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(i,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(is(i,SQL)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(i,Column)?this.config.alias?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(i.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[r,i])=>{if(typeof r!="string")return t;const s=e?[...e,r]:[r];return is(i,Column)||is(i,SQL)||is(i,SQL.Aliased)?t.push({path:s,field:i}):is(i,Table)?t.push(...orderSelectedFields(i[Table.Symbol.Columns],s)):t.push(...orderSelectedFields(i,s)),t},[])}function applyMixins(n,e){for(const t of e)for(const r of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,r){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=r}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:s,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a},this.isPartialSelect=r,this.session=i,this.dialect=s,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,r)=>{const i=this.tableName,s=getTableLikeName(t);if(typeof s=="string"&&this.config.joins?.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof s=="string"&&!is(t,SQL))){const o=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[s]=o}if(typeof r=="function"&&(r=r(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:r,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:r,dialect:i,joinsNotNullableMap:s}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const o=orderSelectedFields(r.fields),a=t.prepareQuery(i.sqlToQuery(this.getSQL()),o,e);return a.joinsNotNullableMap=s,a})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){const r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:i,escapeParam:s,prepareTyping:o,inlineParams:a,paramStartIndex:c}=r;return mergeQueries(e.map(l=>{if(is(l,StringChunk))return{sql:l.value.join(""),params:[]};if(is(l,Name))return{sql:i(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){const d=[new StringChunk("(")];for(const[f,u]of l.entries())d.push(u),f<l.length-1&&d.push(new StringChunk(", "));return d.push(new StringChunk(")")),this.buildQueryFromSourceParams(d,r)}if(is(l,SQL))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(is(l,Table)){const d=l[Table.Symbol.Schema],f=l[Table.Symbol.Name];return{sql:d===void 0?i(f):i(d)+"."+i(f),params:[]}}if(is(l,Column))return{sql:i(l.table[Table.Symbol.Name])+"."+i(l.name),params:[]};if(is(l,View)){const d=l[ViewBaseConfig].schema,f=l[ViewBaseConfig].name;return{sql:d===void 0?i(f):i(d)+"."+i(f),params:[]}}if(is(l,Param)){const d=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(is(d,SQL))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let f;return o!==void 0&&(f=[o(l.encoder)]),{sql:s(c.value++,d),params:[d],typings:f}}return is(l,Placeholder)?{sql:s(c.value++,l),params:[l]}:is(l,SQL.Aliased)&&l.fieldAlias!==void 0?{sql:i(l.fieldAlias),params:[]}:is(l,Subquery)?l[SubqueryConfig].isWith?{sql:i(l[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),l[SubqueryConfig].sql,new StringChunk(") "),new Name(l[SubqueryConfig].alias)],r):isSQLWrapper(l)?this.buildQueryFromSourceParams([new StringChunk("("),l.getSQL(),new StringChunk(")")],r):is(l,Relation)?this.buildQueryFromSourceParams([l.sourceTable,new StringChunk("."),sql.identifier(l.fieldName)],r):a?{sql:this.mapInlineParam(l,r),params:[]}:{sql:s(c.value++,l),params:[l]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const r=e.toString();return t(r==="[object Object]"?JSON.stringify(e):r)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[r,i]of e.entries())t.push(i,new StringChunk(n[r+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(c){return new SQL(c)}n.fromList=t;function r(c){return new SQL([new StringChunk(c)])}n.raw=r;function i(c,l){const d=[];for(const[f,u]of c.entries())f>0&&l!==void 0&&d.push(l),d.push(u);return new SQL(d)}n.join=i;function s(c){return new Name(c)}n.identifier=s;function o(c){return new Placeholder(c)}n.placeholder=o;function a(c,l){return new Param(c,l)}n.param=a})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(r,i){this.sql=r,this.fieldAlias=i}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const i=e[Table.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),s}const r=e[t];return is(r,Column)?new Proxy(r,new ColumnAliasProxyHandler(new Proxy(e,this))):r}}var _a$a;class ColumnBuilder{constructor(e,t,r={},i,s){this.name=e,this.dataType=t,this.options={...r},this._predicateUri=i,this.elementType=s??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,r={},i){this.name=e,this.dataType=t,this.options=r,this.tableName=i}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$a=entityKind;PodColumnBase[_a$a]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,r={}){super(e,"array",r),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function validateColumnOverride(n,e,t){const r=n.getPredicateUri?.()??n.options?.predicate,i=e.options?.predicate;if(r&&i&&r!==i)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${i}",子 schema 尝试改为 "${r}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[r,i]of Object.entries(n.columns))t[r]=i;for(const[r,i]of Object.entries(e)){const s=n.columns[r];if(s&&!(i instanceof PodColumnBase)){validateColumnOverride(i,s,r);const o=i;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:s.options?.predicate})}t[r]=i}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},r=resolveDate(t,e.now),i={yyyy:String(r.getUTCFullYear()),MM:String(r.getUTCMonth()+1).padStart(2,"0"),dd:String(r.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(s,o)=>{const a=o.trim();if(a==="key")return e.key;if(a==="yyyy")return i.yyyy;if(a==="MM")return i.MM;if(a==="dd")return i.dd;const c=resolveExpression(a,t,e);return c==null?"":String(c)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,r=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(r.getTime())?r:e}function resolveExpression(n,e,t){const r=parseExpression(n);let i=resolveTemplatePath(r.path,e,t);for(const s of r.transforms)i=applyTransform(i,s,r.path,t);return r.selector?applyPathSelector(i,r.selector):i}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[r,...i]=t.split("|").map(s=>s.trim()).filter(Boolean);return{path:r??n,transforms:i,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const r=n.split("."),i=r[0];return r.reduce((s,o,a)=>{if(typeof s=="string")return i?resolveResourceProperty(s,i,o,t):void 0;if(!(!s||typeof s!="object"))return i&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in s)?resolveResourceProperty(s,i,o,t):a>0&&o==="id"&&readRef(s)?extractResourceId(s,i??"",t):s[o]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,r){if(t==="id")return extractResourceId(n,e,r);const i=extractResourceId(n,e,r);if(i){if(t==="key"){const s=extractTemplateValuesForField(n,e,r);return s?.key??s?.id??deriveResourceKey(i)}if(t==="doc"||t==="document")return resourceDocument(i);if(t==="dir"||t==="owner")return deriveOwnerDir(i)}}function applyTransform(n,e,t,r){if(e==="slug")return slugifyValue(String(n??""));const i=extractResourceId(n,t,r);if(e==="resource")return i;if(e==="document")return i?resourceDocument(i):"";if(e==="owner")return i?deriveOwnerDir(i):"";const s=extractTemplateValuesForField(n,t,r);return e==="id"?s?.id??s?.key??i??"":s?.[e]??""}function extractResourceId(n,e,t){const r=readRef(n);if(!r)return null;const i=resolveLinkedResource(e,t);if(!i)return normalizePodDataResourceId$1(r);if(!isCompleteResourceId$1(r))return renderLinkedResourceId(i,r);const s=relativeSubjectFromRef$1(i,r);return normalizePodDataResourceId$1(s??r)}function extractTemplateValuesForField(n,e,t){const r=readRef(n);if(!r)return null;const i=resolveLinkedResource(e,t);if(!i)return null;const s=relativeSubjectFromRef$1(i,r)??(isCompleteResourceId$1(r)?null:renderLinkedResourceId(i,r));if(!s)return null;const o=resourceTemplate(i);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(s),o):{id:normalizePodDataResourceId$1(s)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const r=e.resource?.columns?.[n];return r?.getLinkTable?.()??r?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const r=n.columns?.id?.options?.defaultValue;return typeof r=="function"?String(r(e,{})):t.replace(/\{([^}]+)\}/g,(i,s)=>{const o=parseTemplateField(s);return o==="id"||o==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const r=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of r){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const r=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp$1(e.slice(s,a.index)));const c=`var${t++}`;r.set(c,parseTemplateField(a[1]??"")),i.push(`(?<${c}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp$1(e.slice(s)));const o=i.join("");try{const a=n.match(new RegExp(`^${o}$`));if(!a?.groups)return null;const c={};for(const[l,d]of Object.entries(a.groups)){const f=r.get(l);!f||d===void 0||(c[f]=decodeURIComponent(d))}return c}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(r=>r.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const r=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!r)throw new Error(`Invalid id default path selector [${e}]`);const i=r[1]===""?0:normalizeSliceIndex(Number(r[1]),t.length),s=r[2]===""?t.length:normalizeSliceIndex(Number(r[2]),t.length);return t.slice(i,s).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[r,i]=t.split("#"),s=(r??t).split("/").filter(Boolean);return i&&s.push(i),s}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,r=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${r}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),r=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):"",s=r.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];if(r==="task/index.ttl"&&i&&i!=="this")return`task/${i}`;const o=r.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const a=r.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];const c=r.split("/").filter(Boolean);return c.length>1?c.slice(0,-1).join("/"):r}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const a=e.slice(t+1);if(a&&a!=="this"&&a!=="me"&&a!=="it")return a}const r=resourceDocument(e).replace(/\/+$/u,""),i=r.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const s=r.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=r.split("/").filter(Boolean);return o.length>0?o[o.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(r=>r.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const r=e.indexOf("#");if(r>=0)return e.slice(r)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const r=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of r){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const r=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp(e.slice(s,a.index)));const c=`var${t++}`;r.set(c,parseTemplateVariableField$1(a[1]??"")),i.push(`(?<${c}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp(e.slice(s)));const o=`^${i.join("")}$`;try{const a=n.match(new RegExp(o));if(!a?.groups)return null;const c={};for(const[l,d]of Object.entries(a.groups)){const f=r.get(l);if(!f||d===void 0)continue;const u=decodeURIComponent(d);if(f in c&&c[f]!==u)return null;c[f]=u}return c}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const r=qualifyFragmentResourceId(n,t),i=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),s=i?extractTemplateValues(templateRelativeSubject(n,r),i):{id:decodeURIComponent(r)};return s?{resourceId:decodeURIComponent(r),templateValues:s}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,r=readPodUrl(t);if(r)return resolvePodBaseUrl(r);const i=typeof e.getSession=="function"?e.getSession():e.session,s=readPodUrl(i);if(s)return resolvePodBaseUrl(s);const o=readWebId(i);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,r=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${r}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const r=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!r)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(r)||isTemplateCompleteResourceId(n,r))return normalizePodDataResourceId(r);const i=resolveDefaultResourceId(n,r,e);if(i)return normalizePodDataResourceId(i);const s=podResourceSubjectTemplate(n);return normalizePodDataResourceId(s?renderSubjectTemplateResourceId(s,r,e):r)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const r=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(r.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const r=resolveKnownTargetIri(t);if(r)return r;const i=resolvePodRootTargetPath(t);if(i)return buildPodResourceIri(n,i);const s=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,s)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(s)}`:e.resolveUri?.(s)??`/.data/${normalizePodDataResourceId(s)}`;return buildPodResourceIri(n,o)}function buildPodResourceIriForDatabase(n,e,t){const r=resolvePodBaseUrlFromDatabase(n);if(!r)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(r,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,r=podResourceSubjectTemplate(n);if(t||r)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const r=n.columns?.id?.options?.defaultValue;if(r===void 0)return null;if(typeof r=="string")return renderDefaultIdTemplate(r,{key:e,row:t,resource:n});if(typeof r!="function")return String(r);const i=r;return i.length===0?String(i()):String(i(e,t))}function renderSubjectTemplateResourceId(n,e,t){const r=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(r,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$9;class PodTable{constructor(e,t,r){this.initialized=!1;const i=r.type;if(!i)throw new Error("podTable requires a type (RDF class) via options.type");const s=r.typeIndex,o=s==="private"||s==="public",a=this.resolveBase(r.base,e);this.resourcePath=a.resourcePath,this.containerPath=a.containerPath;const c=this.resolveSubjectTemplate(r.subjectTemplate,a.resourcePath,a.containerPath,e);this.subjectTemplate=c.template,this.hasCustomSubjectTemplate=c.isCustom,this.resourceMode=r.resourceMode??(r.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=r.sparqlEndpoint,this.registerTypeIndexEnabled=o&&r.autoRegister!==!1,this.config={name:e,base:a.resourcePath,type:resolveTermIri(i),namespace:r.namespace,typeIndex:o?s:void 0,saiRegistryPath:r.saiRegistryPath,autoRegister:r.autoRegister,containerPath:a.containerPath,hooks:r.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(r.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let l=0;for(const d of Object.values(t))if(d.options.primaryKey&&l++,d.table=this,d.tableName=e,!d.options.predicate&&!d._virtualId&&!r.namespace)throw new Error(`Column "${d.name}" in table "${e}" is missing a predicate.`);if(l!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${l}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const r=t.replace(/\{id\}/g,e);return r.startsWith("#")?`${this.resourcePath}${r}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${r}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const r=this.normalizeBaseInput(e),i=this.normalizeResourcePath(r);if(i.endsWith("/")){const o=this.ensureTrailingSlash(i);return{resourcePath:o,containerPath:o}}const s=this.ensureTrailingSlash(this.deriveContainerPath(i));return{resourcePath:i,containerPath:s}}normalizeBaseInput(e){const t=e.trim(),r=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(r){const[,i,s]=r,o=i.toLowerCase(),a=s.trim();return o==="http"||o==="https"?`${o}://${a}`:a.startsWith("/")?a:`/${a}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const r=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return r.startsWith("/")?r:`/${r}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,r=t.lastIndexOf("/");return r===-1?"/":t.slice(0,r+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,r,i){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const r=(Array.isArray(e)?e:[e]).map(i=>resolveTermIri(i)).filter(i=>i&&i.length>0);return Array.from(new Set(r))}}_a$9=entityKind;PodTable[_a$9]="PodTable";function podTable(n,e,t){const r={};for(const[i,s]of Object.entries(e)){if(s instanceof PodColumnBase){r[i]=s;continue}let o;switch(s.dataType){case"integer":o=new PodIntegerColumn(s.name,s.options);break;case"datetime":o=new PodDateTimeColumn(s.name,s.options);break;case"boolean":o=new PodBooleanColumn(s.name,s.options);break;case"json":o=new PodJsonColumn(s.name,s.options);break;case"object":o=new PodObjectColumn(s.name,s.options);break;case"array":{const c=s.elementType??s.options.baseType??"string";o=new PodArrayColumn(s.name,c,s.options);break}case"uri":o=new PodUriColumn(s.name,s.options);break;default:o=new PodStringColumn(s.name,s.options);break}const a=s.getPredicateUri?.();a&&o.predicate(a),r[i]=o}return new PodTable(n,r,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const r=mergeSchemaColumns(this,e),i=[this.type];return this.subClassOf&&i.push(...this.subClassOf),solidSchema(r,{...t,subClassOf:i})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[r,i]of Object.entries(n)){if(i instanceof PodColumnBase){t[r]=i;continue}let s;switch(i.dataType){case"integer":s=new PodIntegerColumn(i.name,i.options);break;case"datetime":s=new PodDateTimeColumn(i.name,i.options);break;case"boolean":s=new PodBooleanColumn(i.name,i.options);break;case"json":s=new PodJsonColumn(i.name,i.options);break;case"object":s=new PodObjectColumn(i.name,i.options);break;case"array":{const a=i.elementType??i.options.baseType??"string";s=new PodArrayColumn(i.name,a,i.options);break}case"uri":s=new PodUriColumn(i.name,i.options);break;default:s=new PodStringColumn(i.name,i.options);break}const o=i.getPredicateUri?.();o&&s.predicate(o),t[r]=s}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,mergeSchemaColumns,object:object$1,podTable,resolveTermIri,solidSchema,string:string$2,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$7="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const i=e.getMapping()?.columns?.[n.name];if(i?.predicate)return i.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,r){return Array.isArray(n)?n.map(i=>formatSingleValue(i,e,t,r)):formatSingleValue(n,e,t,r)}function formatSingleValue(n,e,t,r){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const i=String(n);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);return t&&!t.isAbsoluteUri(s)?`<${t.resolveLink(s,e,r)}>`:i}return t?`<${t.resolveLink(i,e,r)}>`:i.startsWith("<")?i:`<${i}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$7}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$7}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$7}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const r=t.resolveSubject(e,n);if(!r)throw new Error("Failed to generate subject URI");return r}var _a$8;class SPARQLExpression{constructor(){this[_a$8]="SPARQLExpression"}}_a$8=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,r){super(),this.left=e,this.operator=t,this.right=r,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,r=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!r.ok)throw new Error(`SSE connection failed: ${r.status} ${r.statusText}`);if(!r.body)throw new Error("SSE response has no body");this.contentType=r.headers.get("content-type")||"",this._connected=!0,this.reader=r.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:r,value:i}=await this.reader.read();if(r){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const s=e.decode(i,{stream:!0});t+=s,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(r){r.name!=="AbortError"&&this.handleError(r)}}processTurtleBuffer(e){const t=e.split(`
2
+ `);let r="";for(let i=0;i<t.length;i++){const s=t[i];r+=s+`
3
+ `,s.trim().endsWith(".")&&(this.parseTurtleNotification(r.trim()),r="")}return r}processSSEBuffer(e){const t=e.split(`
4
+
5
+ `),r=t.pop()||"";for(const i of t)i.trim()&&this.parseSSEMessage(i);return r}parseTurtleNotification(e){try{const t=e.match(/<https:\/\/www\.w3\.org\/ns\/activitystreams#object>\s*<([^>]+)>/),r=e.match(/a\s*<https:\/\/www\.w3\.org\/ns\/activitystreams#(\w+)>/),i=e.match(/<https:\/\/www\.w3\.org\/ns\/activitystreams#published>\s*"([^"]+)"/),s=e.match(/<http:\/\/www\.w3\.org\/ns\/solid\/notifications#state>\s*"([^"]+)"/),o=e.match(/^<([^>]+)>/);if(!t||!r)return;const a={id:o?.[1]||`urn:notification:${Date.now()}`,type:r[1],object:t[1],published:i?.[1]||new Date().toISOString(),state:s?.[1]};this.handleMessage(JSON.stringify(a))}catch(t){console.warn("[SSE] Failed to parse Turtle notification:",t)}}parseNotification(e){e.startsWith("{")?this.handleMessage(e):e.includes("activitystreams")&&this.parseTurtleNotification(e)}parseSSEMessage(e){const t=e.split(`
6
+ `);let r="",i="message";for(const s of t)s.startsWith("data:")?r+=s.slice(5).trim():s.startsWith("event:")&&(i=s.slice(6).trim());r&&i==="message"&&this.handleMessage(r)}}const getWebSocket=()=>{if(typeof WebSocket<"u")return WebSocket;try{return require("ws")}catch{throw new Error('WebSocket is not available. Install "ws" package for Node.js support.')}};class WebSocketChannel extends BaseChannel{constructor(e){super(e),this.ws=null,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.reconnectDelay=1e3}async connect(){if(!this._connected)return new Promise((e,t)=>{try{const r=getWebSocket();this.ws=new r(this.config.receiveFrom),this.ws.onopen=()=>{this._connected=!0,this.reconnectAttempts=0,e()},this.ws.onmessage=i=>{const s=typeof i.data=="string"?i.data:i.data?.toString?.()||"";this.handleMessage(s)},this.ws.onerror=()=>{const i=new Error("WebSocket error");this.handleError(i),this._connected||t(i)},this.ws.onclose=i=>{this._connected=!1,!i.wasClean&&this.reconnectAttempts<this.maxReconnectAttempts?(this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{})},this.reconnectDelay*this.reconnectAttempts)):this.handleClose()}}catch(r){t(r)}})}disconnect(){this.reconnectAttempts=this.maxReconnectAttempts,this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this._connected=!1}}const CHANNEL_TYPE_URI={"streaming-http":"http://www.w3.org/ns/solid/notifications#StreamingHTTPChannel2023",websocket:"http://www.w3.org/ns/solid/notifications#WebSocketChannel2023"},CHANNEL_NAMES={"streaming-http":"StreamingHTTPChannel2023",websocket:"WebSocketChannel2023"};class NotificationsClient{constructor(e,t){this.subscriptions=new Map,this.fetch=e,this.preferredChannels=t?.preferredChannels??["streaming-http","websocket"]}async subscribe(e,t){const r=await this.discoverNotificationService(e),s=(t.channel?[t.channel,...this.preferredChannels.filter(a=>a!==t.channel)]:this.preferredChannels).filter(a=>r.supportedChannels.includes(a));if(s.length===0)throw new Error(`No supported notification channels found for ${e}. Server supports: ${r.supportedChannels.join(", ")}`);let o=null;for(const a of s)try{return await this.connectChannel(a,e,r,t)}catch(c){console.log(`[Notifications] Channel "${a}" failed, trying next...`),o=c}throw o??new Error(`Failed to connect to any notification channel for ${e}`)}async resubscribe(e,t,r,i){let s;if(t==="streaming-http")s=this.buildSSEDirectUrl(r.baseEndpoint,e),console.log(`[Notifications] SSE reconnect to: ${s}`);else{const c=`${r.baseEndpoint}${CHANNEL_NAMES[t]}/`;s=(await this.createSubscription(c,e,t,i.features)).receiveFrom,console.log(`[Notifications] WebSocket resubscription created, receiveFrom: ${s}`)}const o=this.subscriptions.get(e),a=this.createChannelWithReconnect(t,s,i,o);return await a.connect(),a}async connectChannel(e,t,r,i){let s;if(e==="streaming-http")s=this.buildSSEDirectUrl(r.baseEndpoint,t),console.log(`[Notifications] SSE direct connect to: ${s}`);else{const c=`${r.baseEndpoint}${CHANNEL_NAMES[e]}/`;s=(await this.createSubscription(c,t,e,i.features)).receiveFrom,console.log(`[Notifications] WebSocket subscription created, receiveFrom: ${s}`)}const o=new SubscriptionImpl(t,e,null,()=>this.subscriptions.delete(t),this,i,r),a=this.createChannelWithReconnect(e,s,i,o);return await a.connect(),o.setChannel(a),this.subscriptions.set(t,o),o}buildSSEDirectUrl(e,t){return`${e.endsWith("/")?e:`${e}/`}StreamingHTTPChannel2023/${encodeURIComponent(t)}`}unsubscribeAll(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear()}async discoverNotificationService(e){const t=await this.discoverFromLinkHeader(e);if(t)return t;const r=new URL(e),i=`${r.origin}/.well-known/solid`;try{return await this.fetchStorageDescription(i,r.origin)}catch{return{baseEndpoint:`${r.origin}/.notifications/`,supportedChannels:["websocket","streaming-http"]}}}async discoverFromLinkHeader(e){try{const r=(await this.fetch(e,{method:"HEAD"})).headers.get("Link");if(!r)return null;const i=new URL(e),s=[],o=r.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/solid\/terms#updatesViaStreamingHttp2023"?/);o&&s.push("streaming-http");const a=r.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/solid\/terms#updatesViaWebSocketChannel2023"?/);if(a&&s.push("websocket"),o){const c=o[1],l=new URL(c),d=l.pathname.split("/"),f=d.findIndex(u=>u===".notifications");if(f!==-1){const u=d.slice(0,f+1).join("/")+"/";return s.includes("websocket")||s.push("websocket"),{baseEndpoint:`${l.origin}${u}`,supportedChannels:s}}}return a&&s.length>0?{baseEndpoint:`${i.origin}/.notifications/`,supportedChannels:s}:null}catch{return null}}async findStorageRoot(e){try{const s=(await this.fetch(e,{method:"HEAD"})).headers.get("Link");if(s){const o=s.match(/<([^>]+)>;\s*rel="?http:\/\/www\.w3\.org\/ns\/pim\/space#storage"?/);if(o)return o[1]}}catch{}const t=new URL(e),r=t.pathname.split("/").filter(Boolean);return r.length>0?`${t.origin}/${r[0]}/`:`${t.origin}/`}async fetchStorageDescription(e,t){const r=await this.fetch(e,{headers:{Accept:"text/turtle, application/ld+json"}});if(!r.ok)throw new Error(`Failed to fetch storage description: ${r.status}`);const i=await r.text(),s=[],o=/<http:\/\/www\.w3\.org\/ns\/solid\/notifications#subscription>\s+<([^>]+)>/g,a=/notify:subscription[>\s]+<([^>]+)>/g;let c;const l=[];for(;(c=o.exec(i))!==null;)l.push(c[1]);for(;(c=a.exec(i))!==null;)l.push(c[1]);for(const f of l)f.includes("WebSocketChannel2023")&&!s.includes("websocket")&&s.push("websocket"),f.includes("StreamingHTTPChannel2023")&&!s.includes("streaming-http")&&s.push("streaming-http");return s.length===0&&(i.includes("WebSocketChannel2023")&&s.push("websocket"),i.includes("StreamingHTTPChannel2023")&&s.push("streaming-http")),{baseEndpoint:`${new URL(t).origin}/.notifications/`,supportedChannels:s.length>0?s:["websocket"]}}async createSubscription(e,t,r,i){const s={"@context":["https://www.w3.org/ns/solid/notification/v1"],type:CHANNEL_TYPE_URI[r],topic:t,...i&&i.length>0?{features:i}:{}},o=`notify-sub-${Date.now()}`,a=await this.fetch(e,{method:"POST",headers:{"Content-Type":"application/ld+json",Accept:"application/ld+json","X-Request-ID":o},body:JSON.stringify(s)});if(!a.ok){const c=await a.text();throw new Error(`Failed to create subscription: ${a.status} ${a.statusText} - ${c}`)}return a.json()}createChannel(e,t,r){const i={receiveFrom:t,onNotification:r.onNotification,onError:r.onError,onClose:r.onClose,fetch:this.fetch};switch(e){case"streaming-http":return new SSEChannel(i);case"websocket":return new WebSocketChannel(i);default:throw new Error(`Unsupported channel type: ${e}`)}}createChannelWithReconnect(e,t,r,i){const s={receiveFrom:t,onNotification:r.onNotification,onError:r.onError,onClose:()=>{i?i.handleDisconnect():r.onClose?.()},fetch:this.fetch};switch(e){case"streaming-http":return new SSEChannel(s);case"websocket":return new WebSocketChannel(s);default:throw new Error(`Unsupported channel type: ${e}`)}}}class SubscriptionImpl{constructor(e,t,r,i,s,o,a){this._active=!0,this.reconnectAttempts=0,this.reconnectTimer=null,this.isReconnecting=!1,this._topic=e,this._channel=t,this.notificationChannel=r,this.onUnsubscribe=i,this.client=s,this.options=o,this.discovery=a}setChannel(e){this.notificationChannel=e}get active(){return this._active&&(this.notificationChannel?.connected||this.isReconnecting)}get channel(){return this._channel}get topic(){return this._topic}handleDisconnect(){if(!this._active)return;const e=this.options.autoReconnect!==!1,t=this.options.maxReconnectAttempts??5;if(!e){this.options.onClose?.();return}if(t>0&&this.reconnectAttempts>=t){console.log(`[Notifications] Max reconnect attempts (${t}) reached for ${this._topic}`),this.options.onClose?.();return}this.isReconnecting=!0,this.reconnectAttempts++;const r=this.options.reconnectDelayMs??1e3,i=Math.min(r*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[Notifications] Connection lost for ${this._topic}, reconnecting in ${i}ms (attempt ${this.reconnectAttempts})`),this.options.onReconnect?.(this.reconnectAttempts),this.reconnectTimer=setTimeout(async()=>{try{const s=await this.client.resubscribe(this._topic,this._channel,this.discovery,this.options);this.notificationChannel=s,this.reconnectAttempts=0,this.isReconnecting=!1,console.log(`[Notifications] Reconnected successfully for ${this._topic}`)}catch(s){console.error(`[Notifications] Reconnect failed for ${this._topic}:`,s),this.isReconnecting=!1,this.handleDisconnect()}},i)}unsubscribe(){this._active&&(this._active=!1,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.notificationChannel?.disconnect(),this.onUnsubscribe())}}const SOLID={typeIndex:"http://www.w3.org/ns/solid/terms#publicTypeIndex",privateTypeIndex:"http://www.w3.org/ns/solid/terms#privateTypeIndex",oidcIssuer:"http://www.w3.org/ns/solid/terms#oidcIssuer"},INTEROP$1={hasRegistrySet:"http://www.w3.org/ns/solid/interop#hasRegistrySet"};class ProviderCache{constructor(e){this.cache=new Map,this.ttl=e?.ttl??1440*60*1e3,this.fetchFn=e?.fetch??fetch}async getWellKnown(e){const t=this.extractProvider(e),r=this.cache.get(t);if(r&&Date.now()<r.expiresAt)return this.applyToPod(r.paths,e);const i=await this.fetchWellKnown(e),s=this.extractPaths(i,e);return this.cache.set(t,{paths:s,expiresAt:Date.now()+this.ttl}),i}async discover(e,t,r,i){const s=await this.getWellKnown(e);if(s.registrySet){const o=await r(s.registrySet,t);if(o)return o}return s.typeIndex?i(s.typeIndex,t):null}setTTL(e){this.ttl=e}clear(){this.cache.clear()}clearProvider(e){this.cache.delete(e)}extractProvider(e){const t=new URL(e).host,r=t.split(".");return r.length>=2?r.slice(-2).join("."):t}async fetchWellKnown(e){const t=e.endsWith("/")?e:`${e}/`,r=`${t}.well-known/solid`;try{const i=await this.fetchFn(r,{headers:{Accept:"text/turtle, application/ld+json"}});if(!i.ok)return{};const s=i.headers.get("content-type")||"",o=await i.text();return s.includes("turtle")||s.includes("n3")?this.parseTurtle(o,t):s.includes("json")?this.parseJsonLd(o):this.parseTurtle(o,t)}catch{return{}}}parseTurtle(e,t){const r={raw:{}},i=e.split(/\s*;\s*|\s*\.\s*(?=\n|$)|\n/).map(s=>s.trim()).filter(Boolean);for(const s of i){if(s.includes("publicTypeIndex")||s.includes(SOLID.typeIndex)){const o=this.extractUrl(s);o&&(r.typeIndex=this.resolveUrl(o,t))}if(s.includes("privateTypeIndex")||s.includes(SOLID.privateTypeIndex)){const o=this.extractUrl(s);o&&(r.privateTypeIndex=this.resolveUrl(o,t))}if(s.includes("hasRegistrySet")||s.includes(INTEROP$1.hasRegistrySet)){const o=this.extractUrl(s);o&&(r.registrySet=this.resolveUrl(o,t))}if(s.includes("oidcIssuer")||s.includes(SOLID.oidcIssuer)){const o=this.extractUrl(s);o&&(r.oidcIssuer=this.resolveUrl(o,t))}}return r}extractUrl(e){const t=e.match(/<([^>]+)>/g);return t&&t.length>0?t[t.length-1].slice(1,-1):null}parseJsonLd(e){try{const t=JSON.parse(e),r={raw:{}},i=t["@graph"]||[t];for(const s of i)(s[SOLID.typeIndex]||s["solid:publicTypeIndex"])&&(r.typeIndex=this.extractJsonLdValue(s[SOLID.typeIndex]||s["solid:publicTypeIndex"])),(s[SOLID.privateTypeIndex]||s["solid:privateTypeIndex"])&&(r.privateTypeIndex=this.extractJsonLdValue(s[SOLID.privateTypeIndex]||s["solid:privateTypeIndex"])),(s[INTEROP$1.hasRegistrySet]||s["interop:hasRegistrySet"])&&(r.registrySet=this.extractJsonLdValue(s[INTEROP$1.hasRegistrySet]||s["interop:hasRegistrySet"])),(s[SOLID.oidcIssuer]||s["solid:oidcIssuer"])&&(r.oidcIssuer=this.extractJsonLdValue(s[SOLID.oidcIssuer]||s["solid:oidcIssuer"]));return r}catch{return{}}}extractJsonLdValue(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)return e["@id"]}resolveUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:new URL(e,t).toString()}extractPaths(e,t){const r=t.endsWith("/")?t:`${t}/`,i={};return e.typeIndex&&(i.typeIndex=this.toRelativePath(e.typeIndex,r)),e.privateTypeIndex&&(i.privateTypeIndex=this.toRelativePath(e.privateTypeIndex,r)),e.registrySet&&(i.registrySet=this.toRelativePath(e.registrySet,r)),e.oidcIssuer&&(i.oidcIssuer=e.oidcIssuer),i}toRelativePath(e,t){return e.startsWith(t)?e.slice(t.length-1):e}applyToPod(e,t){const r=t.endsWith("/")?t:`${t}/`,i={};return e.typeIndex&&(i.typeIndex=this.toAbsoluteUrl(e.typeIndex,r)),e.privateTypeIndex&&(i.privateTypeIndex=this.toAbsoluteUrl(e.privateTypeIndex,r)),e.registrySet&&(i.registrySet=this.toAbsoluteUrl(e.registrySet,r)),e.oidcIssuer&&(i.oidcIssuer=e.oidcIssuer),i}toAbsoluteUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/")?`${t.slice(0,-1)}${e}`:`${t}${e}`}}class FederatedQueryExecutor{constructor(e){this.providerCache=e?.providerCache??new ProviderCache,this.fetchFn=e?.fetch??fetch,this.defaultTimeout=e?.timeout??3e4}async execute(e,t,r){const i=[],s=[...e];if(!t.isFederated||!t.discover)return{data:s};const o=t.table,a=t.discover,c=t.relationName??"items",l=o.type,d=[];for(let p=0;p<e.length;p++){const g=e[p],y=a(g);if(!y){s[p][c]=[];continue}const _=(Array.isArray(y)?y:[y]).filter(R=>typeof R=="string"&&R.length>0);if(_.length===0){s[p][c]=[];continue}d.push({index:p,webIds:_})}const f=r?.parallel??!0,u=r?.maxConcurrency??5;return f?await this.executeParallel(s,d,l,c,i,u,r?.timeout??this.defaultTimeout):await this.executeSequential(s,d,l,c,i,r?.timeout??this.defaultTimeout),{data:s,errors:i.length>0?i:void 0}}async executeParallel(e,t,r,i,s,o,a){for(let c=0;c<t.length;c+=o){const l=t.slice(c,c+o);await Promise.all(l.map(async d=>{try{const f=await this.discoverAndQuery(d.webIds,r,a);e[d.index][i]=f}catch(f){e[d.index][i]=[],s.push(this.createError([d.index,i],f,d.webIds[0]))}}))}}async executeSequential(e,t,r,i,s,o){for(const a of t)try{const c=await this.discoverAndQuery(a.webIds,r,o);e[a.index][i]=c}catch(c){e[a.index][i]=[],s.push(this.createError([a.index,i],c,a.webIds[0]))}}async discoverAndQuery(e,t,r){const i=[];for(const s of e){const o=this.extractPodUrl(s);if(!o)continue;const a=await this.providerCache.getWellKnown(o),c=await this.discoverContainer(o,a,t);if(!c)continue;const l=await this.queryContainer(c,t,r);i.push(...l)}return i}extractPodUrl(e){try{const t=new URL(e);return`${t.protocol}//${t.host}/`}catch{return null}}async discoverContainer(e,t,r){if(t.registrySet){const i=await this.discoverFromSAI(t.registrySet,r);if(i)return i}if(t.typeIndex){const i=await this.discoverFromTypeIndex(t.typeIndex,r);if(i)return i}return null}async discoverFromSAI(e,t){try{const r=await this.fetchFn(e,{headers:{Accept:"text/turtle"}});if(!r.ok)return null;const s=(await r.text()).match(/hasDataRegistry>\s*<([^>]+)>/);if(!s)return null;const o=this.resolveUrl(s[1],e),a=await this.fetchFn(o,{headers:{Accept:"text/turtle"}});if(!a.ok)return null;const l=(await a.text()).matchAll(/hasDataRegistration>\s*<([^>]+)>/g);for(const d of l){const f=this.resolveUrl(d[1],o),u=await this.fetchFn(f,{headers:{Accept:"text/turtle"}});if(!u.ok)continue;const g=(await u.text()).match(/registeredShapeTree>\s*<([^>]+)>/);if(!g)continue;const y=this.resolveUrl(g[1],f),w=await this.fetchFn(y,{headers:{Accept:"text/turtle"}});if(!w.ok)continue;if((await w.text()).includes(t))return f.endsWith("/")?f:f+"/"}return null}catch{return null}}resolveUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:new URL(e,t).toString()}async discoverFromTypeIndex(e,t){try{const r=await this.fetchFn(e,{headers:{Accept:"text/turtle"}});if(!r.ok)return null;const s=(await r.text()).split(/\s*[;.]\s*|\n/).map(c=>c.trim()).filter(Boolean);let o=!1,a=null;for(const c of s)if(c.includes("forClass")&&c.includes(t)&&(o=!0),o){if(c.includes("instance")&&!c.includes("instanceContainer")){const l=c.match(/<([^>]+)>/);if(l){a=l[1];break}}if(c.includes("instanceContainer")){const l=c.match(/<([^>]+)>/);if(l){a=l[1];break}}}return a}catch{return null}}async queryContainer(e,t,r){try{const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.fetchFn(e,{headers:{Accept:"text/turtle"},signal:i.signal});if(clearTimeout(s),!o.ok){if(o.status===403)throw new Error(`403 Forbidden: ${e}`);if(o.status===404)throw new Error(`404 Not Found: ${e}`);return[]}const a=await o.text();return this.parseTurtleResources(a,e,t)}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error(`Timeout: ${e}`):i}}parseTurtleResources(e,t,r){const i=[],s={},o=/@prefix\s+(\w+):\s*<([^>]+)>\s*\./g;let a;for(;(a=o.exec(e))!==null;)s[a[1]]=a[2];const c=new RegExp(`<([^>]+)>\\s+(?:a|rdf:type|<http://www\\.w3\\.org/1999/02/22-rdf-syntax-ns#type>)\\s+<${this.escapeRegex(r)}>`,"g"),l=[];for(;(a=c.exec(e))!==null;)l.push(a[1]);for(const d of l){const f=this.extractResourceProperties(e,d,s,t);f&&i.push(f)}return i}extractResourceProperties(e,t,r,i){const s={"@id":t,id:this.extractIdFromUri(t)},o=this.escapeRegex(t),a=new RegExp(`<${o}>\\s+<([^>]+)>\\s+<([^>]+)>`,"g");let c;for(;(c=a.exec(e))!==null;){const d=c[1],f=c[2],u=this.extractLocalName(d);d.includes("22-rdf-syntax-ns#type")||(s[u]=f)}const l=new RegExp(`<${o}>\\s+<([^>]+)>\\s+"([^"]*)"`,"g");for(;(c=l.exec(e))!==null;){const d=c[1],f=c[2],u=this.extractLocalName(d);s[u]=f}return s}extractIdFromUri(e){const t=e.indexOf("#");if(t!==-1)return e.slice(t);const r=e.lastIndexOf("/");return r!==-1?e.slice(r+1):e}extractLocalName(e){return e.includes("#")?e.split("#").pop()??e:e.split("/").pop()??e}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}createError(e,t,r){const i=t instanceof Error?t.message:String(t);let s="NETWORK_ERROR";return i.includes("403")||i.includes("Forbidden")?s="FORBIDDEN":i.includes("404")||i.includes("Not Found")?s="NOT_FOUND":i.includes("timeout")||i.includes("Timeout")?s="TIMEOUT":i.includes("discover")&&(s="DISCOVERY_FAILED"),{path:e,code:s,message:i,url:r}}}new FederatedQueryExecutor;var buffer={},base64Js={},hasRequiredBase64Js;function requireBase64Js(){if(hasRequiredBase64Js)return base64Js;hasRequiredBase64Js=1,base64Js.byteLength=a,base64Js.toByteArray=l,base64Js.fromByteArray=u;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=r.length;i<s;++i)n[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function o(p){var g=p.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=p.indexOf("=");y===-1&&(y=g);var w=y===g?0:4-y%4;return[y,w]}function a(p){var g=o(p),y=g[0],w=g[1];return(y+w)*3/4-w}function c(p,g,y){return(g+y)*3/4-y}function l(p){var g,y=o(p),w=y[0],_=y[1],R=new t(c(p,w,_)),b=0,C=_>0?w-4:w,P;for(P=0;P<C;P+=4)g=e[p.charCodeAt(P)]<<18|e[p.charCodeAt(P+1)]<<12|e[p.charCodeAt(P+2)]<<6|e[p.charCodeAt(P+3)],R[b++]=g>>16&255,R[b++]=g>>8&255,R[b++]=g&255;return _===2&&(g=e[p.charCodeAt(P)]<<2|e[p.charCodeAt(P+1)]>>4,R[b++]=g&255),_===1&&(g=e[p.charCodeAt(P)]<<10|e[p.charCodeAt(P+1)]<<4|e[p.charCodeAt(P+2)]>>2,R[b++]=g>>8&255,R[b++]=g&255),R}function d(p){return n[p>>18&63]+n[p>>12&63]+n[p>>6&63]+n[p&63]}function f(p,g,y){for(var w,_=[],R=g;R<y;R+=3)w=(p[R]<<16&16711680)+(p[R+1]<<8&65280)+(p[R+2]&255),_.push(d(w));return _.join("")}function u(p){for(var g,y=p.length,w=y%3,_=[],R=16383,b=0,C=y-w;b<C;b+=R)_.push(f(p,b,b+R>C?C:b+R));return w===1?(g=p[y-1],_.push(n[g>>2]+n[g<<4&63]+"==")):w===2&&(g=(p[y-2]<<8)+p[y-1],_.push(n[g>>10]+n[g>>4&63]+n[g<<2&63]+"=")),_.join("")}return base64Js}var ieee754={};var hasRequiredIeee754;function requireIeee754(){return hasRequiredIeee754||(hasRequiredIeee754=1,ieee754.read=function(n,e,t,r,i){var s,o,a=i*8-r-1,c=(1<<a)-1,l=c>>1,d=-7,f=t?i-1:0,u=t?-1:1,p=n[e+f];for(f+=u,s=p&(1<<-d)-1,p>>=-d,d+=a;d>0;s=s*256+n[e+f],f+=u,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=o*256+n[e+f],f+=u,d-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-l}return(p?-1:1)*o*Math.pow(2,s-r)},ieee754.write=function(n,e,t,r,i,s){var o,a,c,l=s*8-i-1,d=(1<<l)-1,f=d>>1,u=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:s-1,g=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+f>=1?e+=u/c:e+=u*Math.pow(2,1-f),e*c>=2&&(o++,c/=2),o+f>=d?(a=0,o=d):o+f>=1?(a=(e*c-1)*Math.pow(2,i),o=o+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;n[t+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;n[t+p]=o&255,p+=g,o/=256,l-=8);n[t+p-g]|=y*128}),ieee754}var hasRequiredBuffer;function requireBuffer(){return hasRequiredBuffer||(hasRequiredBuffer=1,(function(n){const e=requireBase64Js(),t=requireIeee754(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;n.Buffer=a,n.SlowBuffer=R,n.INSPECT_MAX_BYTES=50;const i=2147483647;n.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const S=new Uint8Array(1),h={foo:function(){return 42}};return Object.setPrototypeOf(h,Uint8Array.prototype),Object.setPrototypeOf(S,h),S.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(S){if(S>i)throw new RangeError('The value "'+S+'" is invalid for option "size"');const h=new Uint8Array(S);return Object.setPrototypeOf(h,a.prototype),h}function a(S,h,m){if(typeof S=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(S)}return c(S,h,m)}a.poolSize=8192;function c(S,h,m){if(typeof S=="string")return u(S,h);if(ArrayBuffer.isView(S))return g(S);if(S==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof S);if(j(S,ArrayBuffer)||S&&j(S.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(j(S,SharedArrayBuffer)||S&&j(S.buffer,SharedArrayBuffer)))return y(S,h,m);if(typeof S=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const I=S.valueOf&&S.valueOf();if(I!=null&&I!==S)return a.from(I,h,m);const $=w(S);if($)return $;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof S[Symbol.toPrimitive]=="function")return a.from(S[Symbol.toPrimitive]("string"),h,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof S)}a.from=function(S,h,m){return c(S,h,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function l(S){if(typeof S!="number")throw new TypeError('"size" argument must be of type number');if(S<0)throw new RangeError('The value "'+S+'" is invalid for option "size"')}function d(S,h,m){return l(S),S<=0?o(S):h!==void 0?typeof m=="string"?o(S).fill(h,m):o(S).fill(h):o(S)}a.alloc=function(S,h,m){return d(S,h,m)};function f(S){return l(S),o(S<0?0:_(S)|0)}a.allocUnsafe=function(S){return f(S)},a.allocUnsafeSlow=function(S){return f(S)};function u(S,h){if((typeof h!="string"||h==="")&&(h="utf8"),!a.isEncoding(h))throw new TypeError("Unknown encoding: "+h);const m=b(S,h)|0;let I=o(m);const $=I.write(S,h);return $!==m&&(I=I.slice(0,$)),I}function p(S){const h=S.length<0?0:_(S.length)|0,m=o(h);for(let I=0;I<h;I+=1)m[I]=S[I]&255;return m}function g(S){if(j(S,Uint8Array)){const h=new Uint8Array(S);return y(h.buffer,h.byteOffset,h.byteLength)}return p(S)}function y(S,h,m){if(h<0||S.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(S.byteLength<h+(m||0))throw new RangeError('"length" is outside of buffer bounds');let I;return h===void 0&&m===void 0?I=new Uint8Array(S):m===void 0?I=new Uint8Array(S,h):I=new Uint8Array(S,h,m),Object.setPrototypeOf(I,a.prototype),I}function w(S){if(a.isBuffer(S)){const h=_(S.length)|0,m=o(h);return m.length===0||S.copy(m,0,0,h),m}if(S.length!==void 0)return typeof S.length!="number"||we(S.length)?o(0):p(S);if(S.type==="Buffer"&&Array.isArray(S.data))return p(S.data)}function _(S){if(S>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return S|0}function R(S){return+S!=S&&(S=0),a.alloc(+S)}a.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==a.prototype},a.compare=function(h,m){if(j(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),j(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(h)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===m)return 0;let I=h.length,$=m.length;for(let L=0,W=Math.min(I,$);L<W;++L)if(h[L]!==m[L]){I=h[L],$=m[L];break}return I<$?-1:$<I?1:0},a.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(h,m){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return a.alloc(0);let I;if(m===void 0)for(m=0,I=0;I<h.length;++I)m+=h[I].length;const $=a.allocUnsafe(m);let L=0;for(I=0;I<h.length;++I){let W=h[I];if(j(W,Uint8Array))L+W.length>$.length?(a.isBuffer(W)||(W=a.from(W)),W.copy($,L)):Uint8Array.prototype.set.call($,W,L);else if(a.isBuffer(W))W.copy($,L);else throw new TypeError('"list" argument must be an Array of Buffers');L+=W.length}return $};function b(S,h){if(a.isBuffer(S))return S.length;if(ArrayBuffer.isView(S)||j(S,ArrayBuffer))return S.byteLength;if(typeof S!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof S);const m=S.length,I=arguments.length>2&&arguments[2]===!0;if(!I&&m===0)return 0;let $=!1;for(;;)switch(h){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return J(S).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return z(S).length;default:if($)return I?-1:J(S).length;h=(""+h).toLowerCase(),$=!0}}a.byteLength=b;function C(S,h,m){let I=!1;if((h===void 0||h<0)&&(h=0),h>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,h>>>=0,m<=h))return"";for(S||(S="utf8");;)switch(S){case"hex":return ae(this,h,m);case"utf8":case"utf-8":return ce(this,h,m);case"ascii":return Ne(this,h,m);case"latin1":case"binary":return te(this,h,m);case"base64":return U(this,h,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,h,m);default:if(I)throw new TypeError("Unknown encoding: "+S);S=(S+"").toLowerCase(),I=!0}}a.prototype._isBuffer=!0;function P(S,h,m){const I=S[h];S[h]=S[m],S[m]=I}a.prototype.swap16=function(){const h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<h;m+=2)P(this,m,m+1);return this},a.prototype.swap32=function(){const h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<h;m+=4)P(this,m,m+3),P(this,m+1,m+2);return this},a.prototype.swap64=function(){const h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<h;m+=8)P(this,m,m+7),P(this,m+1,m+6),P(this,m+2,m+5),P(this,m+3,m+4);return this},a.prototype.toString=function(){const h=this.length;return h===0?"":arguments.length===0?ce(this,0,h):C.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(h){if(!a.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:a.compare(this,h)===0},a.prototype.inspect=function(){let h="";const m=n.INSPECT_MAX_BYTES;return h=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(h+=" ... "),"<Buffer "+h+">"},r&&(a.prototype[r]=a.prototype.inspect),a.prototype.compare=function(h,m,I,$,L){if(j(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(m===void 0&&(m=0),I===void 0&&(I=h?h.length:0),$===void 0&&($=0),L===void 0&&(L=this.length),m<0||I>h.length||$<0||L>this.length)throw new RangeError("out of range index");if($>=L&&m>=I)return 0;if($>=L)return-1;if(m>=I)return 1;if(m>>>=0,I>>>=0,$>>>=0,L>>>=0,this===h)return 0;let W=L-$,Te=I-m;const xe=Math.min(W,Te),Fe=this.slice($,L),je=h.slice(m,I);for(let Le=0;Le<xe;++Le)if(Fe[Le]!==je[Le]){W=Fe[Le],Te=je[Le];break}return W<Te?-1:Te<W?1:0};function H(S,h,m,I,$){if(S.length===0)return-1;if(typeof m=="string"?(I=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,we(m)&&(m=$?0:S.length-1),m<0&&(m=S.length+m),m>=S.length){if($)return-1;m=S.length-1}else if(m<0)if($)m=0;else return-1;if(typeof h=="string"&&(h=a.from(h,I)),a.isBuffer(h))return h.length===0?-1:M(S,h,m,I,$);if(typeof h=="number")return h=h&255,typeof Uint8Array.prototype.indexOf=="function"?$?Uint8Array.prototype.indexOf.call(S,h,m):Uint8Array.prototype.lastIndexOf.call(S,h,m):M(S,[h],m,I,$);throw new TypeError("val must be string, number or Buffer")}function M(S,h,m,I,$){let L=1,W=S.length,Te=h.length;if(I!==void 0&&(I=String(I).toLowerCase(),I==="ucs2"||I==="ucs-2"||I==="utf16le"||I==="utf-16le")){if(S.length<2||h.length<2)return-1;L=2,W/=2,Te/=2,m/=2}function xe(je,Le){return L===1?je[Le]:je.readUInt16BE(Le*L)}let Fe;if($){let je=-1;for(Fe=m;Fe<W;Fe++)if(xe(S,Fe)===xe(h,je===-1?0:Fe-je)){if(je===-1&&(je=Fe),Fe-je+1===Te)return je*L}else je!==-1&&(Fe-=Fe-je),je=-1}else for(m+Te>W&&(m=W-Te),Fe=m;Fe>=0;Fe--){let je=!0;for(let Le=0;Le<Te;Le++)if(xe(S,Fe+Le)!==xe(h,Le)){je=!1;break}if(je)return Fe}return-1}a.prototype.includes=function(h,m,I){return this.indexOf(h,m,I)!==-1},a.prototype.indexOf=function(h,m,I){return H(this,h,m,I,!0)},a.prototype.lastIndexOf=function(h,m,I){return H(this,h,m,I,!1)};function re(S,h,m,I){m=Number(m)||0;const $=S.length-m;I?(I=Number(I),I>$&&(I=$)):I=$;const L=h.length;I>L/2&&(I=L/2);let W;for(W=0;W<I;++W){const Te=parseInt(h.substr(W*2,2),16);if(we(Te))return W;S[m+W]=Te}return W}function he(S,h,m,I){return K(J(h,S.length-m),S,m,I)}function V(S,h,m,I){return K(X(h),S,m,I)}function q(S,h,m,I){return K(z(h),S,m,I)}function ie(S,h,m,I){return K(N(h,S.length-m),S,m,I)}a.prototype.write=function(h,m,I,$){if(m===void 0)$="utf8",I=this.length,m=0;else if(I===void 0&&typeof m=="string")$=m,I=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(I)?(I=I>>>0,$===void 0&&($="utf8")):($=I,I=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const L=this.length-m;if((I===void 0||I>L)&&(I=L),h.length>0&&(I<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");$||($="utf8");let W=!1;for(;;)switch($){case"hex":return re(this,h,m,I);case"utf8":case"utf-8":return he(this,h,m,I);case"ascii":case"latin1":case"binary":return V(this,h,m,I);case"base64":return q(this,h,m,I);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ie(this,h,m,I);default:if(W)throw new TypeError("Unknown encoding: "+$);$=(""+$).toLowerCase(),W=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(S,h,m){return h===0&&m===S.length?e.fromByteArray(S):e.fromByteArray(S.slice(h,m))}function ce(S,h,m){m=Math.min(S.length,m);const I=[];let $=h;for(;$<m;){const L=S[$];let W=null,Te=L>239?4:L>223?3:L>191?2:1;if($+Te<=m){let xe,Fe,je,Le;switch(Te){case 1:L<128&&(W=L);break;case 2:xe=S[$+1],(xe&192)===128&&(Le=(L&31)<<6|xe&63,Le>127&&(W=Le));break;case 3:xe=S[$+1],Fe=S[$+2],(xe&192)===128&&(Fe&192)===128&&(Le=(L&15)<<12|(xe&63)<<6|Fe&63,Le>2047&&(Le<55296||Le>57343)&&(W=Le));break;case 4:xe=S[$+1],Fe=S[$+2],je=S[$+3],(xe&192)===128&&(Fe&192)===128&&(je&192)===128&&(Le=(L&15)<<18|(xe&63)<<12|(Fe&63)<<6|je&63,Le>65535&&Le<1114112&&(W=Le))}}W===null?(W=65533,Te=1):W>65535&&(W-=65536,I.push(W>>>10&1023|55296),W=56320|W&1023),I.push(W),$+=Te}return me(I)}const Se=4096;function me(S){const h=S.length;if(h<=Se)return String.fromCharCode.apply(String,S);let m="",I=0;for(;I<h;)m+=String.fromCharCode.apply(String,S.slice(I,I+=Se));return m}function Ne(S,h,m){let I="";m=Math.min(S.length,m);for(let $=h;$<m;++$)I+=String.fromCharCode(S[$]&127);return I}function te(S,h,m){let I="";m=Math.min(S.length,m);for(let $=h;$<m;++$)I+=String.fromCharCode(S[$]);return I}function ae(S,h,m){const I=S.length;(!h||h<0)&&(h=0),(!m||m<0||m>I)&&(m=I);let $="";for(let L=h;L<m;++L)$+=Ee[S[L]];return $}function x(S,h,m){const I=S.slice(h,m);let $="";for(let L=0;L<I.length-1;L+=2)$+=String.fromCharCode(I[L]+I[L+1]*256);return $}a.prototype.slice=function(h,m){const I=this.length;h=~~h,m=m===void 0?I:~~m,h<0?(h+=I,h<0&&(h=0)):h>I&&(h=I),m<0?(m+=I,m<0&&(m=0)):m>I&&(m=I),m<h&&(m=h);const $=this.subarray(h,m);return Object.setPrototypeOf($,a.prototype),$};function O(S,h,m){if(S%1!==0||S<0)throw new RangeError("offset is not uint");if(S+h>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(h,m,I){h=h>>>0,m=m>>>0,I||O(h,m,this.length);let $=this[h],L=1,W=0;for(;++W<m&&(L*=256);)$+=this[h+W]*L;return $},a.prototype.readUintBE=a.prototype.readUIntBE=function(h,m,I){h=h>>>0,m=m>>>0,I||O(h,m,this.length);let $=this[h+--m],L=1;for(;m>0&&(L*=256);)$+=this[h+--m]*L;return $},a.prototype.readUint8=a.prototype.readUInt8=function(h,m){return h=h>>>0,m||O(h,1,this.length),this[h]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(h,m){return h=h>>>0,m||O(h,2,this.length),this[h]|this[h+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(h,m){return h=h>>>0,m||O(h,2,this.length),this[h]<<8|this[h+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(h,m){return h=h>>>0,m||O(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(h,m){return h=h>>>0,m||O(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},a.prototype.readBigUInt64LE=be(function(h){h=h>>>0,D(h,"offset");const m=this[h],I=this[h+7];(m===void 0||I===void 0)&&F(h,this.length-8);const $=m+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,L=this[++h]+this[++h]*2**8+this[++h]*2**16+I*2**24;return BigInt($)+(BigInt(L)<<BigInt(32))}),a.prototype.readBigUInt64BE=be(function(h){h=h>>>0,D(h,"offset");const m=this[h],I=this[h+7];(m===void 0||I===void 0)&&F(h,this.length-8);const $=m*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],L=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+I;return(BigInt($)<<BigInt(32))+BigInt(L)}),a.prototype.readIntLE=function(h,m,I){h=h>>>0,m=m>>>0,I||O(h,m,this.length);let $=this[h],L=1,W=0;for(;++W<m&&(L*=256);)$+=this[h+W]*L;return L*=128,$>=L&&($-=Math.pow(2,8*m)),$},a.prototype.readIntBE=function(h,m,I){h=h>>>0,m=m>>>0,I||O(h,m,this.length);let $=m,L=1,W=this[h+--$];for(;$>0&&(L*=256);)W+=this[h+--$]*L;return L*=128,W>=L&&(W-=Math.pow(2,8*m)),W},a.prototype.readInt8=function(h,m){return h=h>>>0,m||O(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},a.prototype.readInt16LE=function(h,m){h=h>>>0,m||O(h,2,this.length);const I=this[h]|this[h+1]<<8;return I&32768?I|4294901760:I},a.prototype.readInt16BE=function(h,m){h=h>>>0,m||O(h,2,this.length);const I=this[h+1]|this[h]<<8;return I&32768?I|4294901760:I},a.prototype.readInt32LE=function(h,m){return h=h>>>0,m||O(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},a.prototype.readInt32BE=function(h,m){return h=h>>>0,m||O(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},a.prototype.readBigInt64LE=be(function(h){h=h>>>0,D(h,"offset");const m=this[h],I=this[h+7];(m===void 0||I===void 0)&&F(h,this.length-8);const $=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(I<<24);return(BigInt($)<<BigInt(32))+BigInt(m+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),a.prototype.readBigInt64BE=be(function(h){h=h>>>0,D(h,"offset");const m=this[h],I=this[h+7];(m===void 0||I===void 0)&&F(h,this.length-8);const $=(m<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt($)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+I)}),a.prototype.readFloatLE=function(h,m){return h=h>>>0,m||O(h,4,this.length),t.read(this,h,!0,23,4)},a.prototype.readFloatBE=function(h,m){return h=h>>>0,m||O(h,4,this.length),t.read(this,h,!1,23,4)},a.prototype.readDoubleLE=function(h,m){return h=h>>>0,m||O(h,8,this.length),t.read(this,h,!0,52,8)},a.prototype.readDoubleBE=function(h,m){return h=h>>>0,m||O(h,8,this.length),t.read(this,h,!1,52,8)};function se(S,h,m,I,$,L){if(!a.isBuffer(S))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>$||h<L)throw new RangeError('"value" argument is out of bounds');if(m+I>S.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(h,m,I,$){if(h=+h,m=m>>>0,I=I>>>0,!$){const Te=Math.pow(2,8*I)-1;se(this,h,m,I,Te,0)}let L=1,W=0;for(this[m]=h&255;++W<I&&(L*=256);)this[m+W]=h/L&255;return m+I},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(h,m,I,$){if(h=+h,m=m>>>0,I=I>>>0,!$){const Te=Math.pow(2,8*I)-1;se(this,h,m,I,Te,0)}let L=I-1,W=1;for(this[m+L]=h&255;--L>=0&&(W*=256);)this[m+L]=h/W&255;return m+I},a.prototype.writeUint8=a.prototype.writeUInt8=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,1,255,0),this[m]=h&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,2,65535,0),this[m]=h&255,this[m+1]=h>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,2,65535,0),this[m]=h>>>8,this[m+1]=h&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,4,4294967295,0),this[m+3]=h>>>24,this[m+2]=h>>>16,this[m+1]=h>>>8,this[m]=h&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,4,4294967295,0),this[m]=h>>>24,this[m+1]=h>>>16,this[m+2]=h>>>8,this[m+3]=h&255,m+4};function G(S,h,m,I,$){ge(h,I,$,S,m,7);let L=Number(h&BigInt(4294967295));S[m++]=L,L=L>>8,S[m++]=L,L=L>>8,S[m++]=L,L=L>>8,S[m++]=L;let W=Number(h>>BigInt(32)&BigInt(4294967295));return S[m++]=W,W=W>>8,S[m++]=W,W=W>>8,S[m++]=W,W=W>>8,S[m++]=W,m}function le(S,h,m,I,$){ge(h,I,$,S,m,7);let L=Number(h&BigInt(4294967295));S[m+7]=L,L=L>>8,S[m+6]=L,L=L>>8,S[m+5]=L,L=L>>8,S[m+4]=L;let W=Number(h>>BigInt(32)&BigInt(4294967295));return S[m+3]=W,W=W>>8,S[m+2]=W,W=W>>8,S[m+1]=W,W=W>>8,S[m]=W,m+8}a.prototype.writeBigUInt64LE=be(function(h,m=0){return G(this,h,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=be(function(h,m=0){return le(this,h,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(h,m,I,$){if(h=+h,m=m>>>0,!$){const xe=Math.pow(2,8*I-1);se(this,h,m,I,xe-1,-xe)}let L=0,W=1,Te=0;for(this[m]=h&255;++L<I&&(W*=256);)h<0&&Te===0&&this[m+L-1]!==0&&(Te=1),this[m+L]=(h/W>>0)-Te&255;return m+I},a.prototype.writeIntBE=function(h,m,I,$){if(h=+h,m=m>>>0,!$){const xe=Math.pow(2,8*I-1);se(this,h,m,I,xe-1,-xe)}let L=I-1,W=1,Te=0;for(this[m+L]=h&255;--L>=0&&(W*=256);)h<0&&Te===0&&this[m+L+1]!==0&&(Te=1),this[m+L]=(h/W>>0)-Te&255;return m+I},a.prototype.writeInt8=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,1,127,-128),h<0&&(h=255+h+1),this[m]=h&255,m+1},a.prototype.writeInt16LE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,2,32767,-32768),this[m]=h&255,this[m+1]=h>>>8,m+2},a.prototype.writeInt16BE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,2,32767,-32768),this[m]=h>>>8,this[m+1]=h&255,m+2},a.prototype.writeInt32LE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,4,2147483647,-2147483648),this[m]=h&255,this[m+1]=h>>>8,this[m+2]=h>>>16,this[m+3]=h>>>24,m+4},a.prototype.writeInt32BE=function(h,m,I){return h=+h,m=m>>>0,I||se(this,h,m,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[m]=h>>>24,this[m+1]=h>>>16,this[m+2]=h>>>8,this[m+3]=h&255,m+4},a.prototype.writeBigInt64LE=be(function(h,m=0){return G(this,h,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=be(function(h,m=0){return le(this,h,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function pe(S,h,m,I,$,L){if(m+I>S.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function Re(S,h,m,I,$){return h=+h,m=m>>>0,$||pe(S,h,m,4),t.write(S,h,m,I,23,4),m+4}a.prototype.writeFloatLE=function(h,m,I){return Re(this,h,m,!0,I)},a.prototype.writeFloatBE=function(h,m,I){return Re(this,h,m,!1,I)};function _e(S,h,m,I,$){return h=+h,m=m>>>0,$||pe(S,h,m,8),t.write(S,h,m,I,52,8),m+8}a.prototype.writeDoubleLE=function(h,m,I){return _e(this,h,m,!0,I)},a.prototype.writeDoubleBE=function(h,m,I){return _e(this,h,m,!1,I)},a.prototype.copy=function(h,m,I,$){if(!a.isBuffer(h))throw new TypeError("argument should be a Buffer");if(I||(I=0),!$&&$!==0&&($=this.length),m>=h.length&&(m=h.length),m||(m=0),$>0&&$<I&&($=I),$===I||h.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(I<0||I>=this.length)throw new RangeError("Index out of range");if($<0)throw new RangeError("sourceEnd out of bounds");$>this.length&&($=this.length),h.length-m<$-I&&($=h.length-m+I);const L=$-I;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,I,$):Uint8Array.prototype.set.call(h,this.subarray(I,$),m),L},a.prototype.fill=function(h,m,I,$){if(typeof h=="string"){if(typeof m=="string"?($=m,m=0,I=this.length):typeof I=="string"&&($=I,I=this.length),$!==void 0&&typeof $!="string")throw new TypeError("encoding must be a string");if(typeof $=="string"&&!a.isEncoding($))throw new TypeError("Unknown encoding: "+$);if(h.length===1){const W=h.charCodeAt(0);($==="utf8"&&W<128||$==="latin1")&&(h=W)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(m<0||this.length<m||this.length<I)throw new RangeError("Out of range index");if(I<=m)return this;m=m>>>0,I=I===void 0?this.length:I>>>0,h||(h=0);let L;if(typeof h=="number")for(L=m;L<I;++L)this[L]=h;else{const W=a.isBuffer(h)?h:a.from(h,$),Te=W.length;if(Te===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(L=0;L<I-m;++L)this[L+m]=W[L%Te]}return this};const B={};function Z(S,h,m){B[S]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:h.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${S}]`,this.stack,delete this.name}get code(){return S}set code($){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:$,writable:!0})}toString(){return`${this.name} [${S}]: ${this.message}`}}}Z("ERR_BUFFER_OUT_OF_BOUNDS",function(S){return S?`${S} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Z("ERR_INVALID_ARG_TYPE",function(S,h){return`The "${S}" argument must be of type number. Received type ${typeof h}`},TypeError),Z("ERR_OUT_OF_RANGE",function(S,h,m){let I=`The value of "${S}" is out of range.`,$=m;return Number.isInteger(m)&&Math.abs(m)>2**32?$=oe(String(m)):typeof m=="bigint"&&($=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&($=oe($)),$+="n"),I+=` It must be ${h}. Received ${$}`,I},RangeError);function oe(S){let h="",m=S.length;const I=S[0]==="-"?1:0;for(;m>=I+4;m-=3)h=`_${S.slice(m-3,m)}${h}`;return`${S.slice(0,m)}${h}`}function ye(S,h,m){D(h,"offset"),(S[h]===void 0||S[h+m]===void 0)&&F(h,S.length-(m+1))}function ge(S,h,m,I,$,L){if(S>m||S<h){const W=typeof h=="bigint"?"n":"";let Te;throw h===0||h===BigInt(0)?Te=`>= 0${W} and < 2${W} ** ${(L+1)*8}${W}`:Te=`>= -(2${W} ** ${(L+1)*8-1}${W}) and < 2 ** ${(L+1)*8-1}${W}`,new B.ERR_OUT_OF_RANGE("value",Te,S)}ye(I,$,L)}function D(S,h){if(typeof S!="number")throw new B.ERR_INVALID_ARG_TYPE(h,"number",S)}function F(S,h,m){throw Math.floor(S)!==S?(D(S,m),new B.ERR_OUT_OF_RANGE("offset","an integer",S)):h<0?new B.ERR_BUFFER_OUT_OF_BOUNDS:new B.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${h}`,S)}const k=/[^+/0-9A-Za-z-_]/g;function ee(S){if(S=S.split("=")[0],S=S.trim().replace(k,""),S.length<2)return"";for(;S.length%4!==0;)S=S+"=";return S}function J(S,h){h=h||1/0;let m;const I=S.length;let $=null;const L=[];for(let W=0;W<I;++W){if(m=S.charCodeAt(W),m>55295&&m<57344){if(!$){if(m>56319){(h-=3)>-1&&L.push(239,191,189);continue}else if(W+1===I){(h-=3)>-1&&L.push(239,191,189);continue}$=m;continue}if(m<56320){(h-=3)>-1&&L.push(239,191,189),$=m;continue}m=($-55296<<10|m-56320)+65536}else $&&(h-=3)>-1&&L.push(239,191,189);if($=null,m<128){if((h-=1)<0)break;L.push(m)}else if(m<2048){if((h-=2)<0)break;L.push(m>>6|192,m&63|128)}else if(m<65536){if((h-=3)<0)break;L.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((h-=4)<0)break;L.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return L}function X(S){const h=[];for(let m=0;m<S.length;++m)h.push(S.charCodeAt(m)&255);return h}function N(S,h){let m,I,$;const L=[];for(let W=0;W<S.length&&!((h-=2)<0);++W)m=S.charCodeAt(W),I=m>>8,$=m%256,L.push($),L.push(I);return L}function z(S){return e.toByteArray(ee(S))}function K(S,h,m,I){let $;for($=0;$<I&&!($+m>=h.length||$>=S.length);++$)h[$+m]=S[$];return $}function j(S,h){return S instanceof h||S!=null&&S.constructor!=null&&S.constructor.name!=null&&S.constructor.name===h.name}function we(S){return S!==S}const Ee=(function(){const S="0123456789abcdef",h=new Array(256);for(let m=0;m<16;++m){const I=m*16;for(let $=0;$<16;++$)h[I+$]=S[m]+S[$]}return h})();function be(S){return typeof BigInt>"u"?Ie:S}function Ie(){throw new Error("BigInt not supported")}})(buffer)),buffer}var bufferExports=requireBuffer();const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD$6="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD$6}decimal`,boolean:`${XSD$6}boolean`,double:`${XSD$6}double`,integer:`${XSD$6}integer`,string:`${XSD$6}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$2}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
7
+ `,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,i=r.length;for(;;){let a,c;for(;a=this._newline.exec(r);)this.comments&&(c=this._comment.exec(a[0]))&&s("comment",c[1],"",this._line,a[0].length),r=r.substr(a[0].length,r.length),i=r.length,this._line++;if(!a&&(a=this._whitespace.exec(r))&&(r=r.substr(a[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(c=this._comment.exec(r))&&s("comment",c[1],"",this._line,r.length),r=null,s("eof","","",this._line,0)),this._input=r;const l=this._line,d=r[0];let f="",u="",p="",g=null,y=0,w=!1;switch(d){case"^":if(r.length<3)break;if(r[1]==="^"){if(this._previousMarker="^^",r=r.substr(2),r[0]!=="<"){w=!0;break}}else{this._n3Mode&&(y=1,f="^");break}case"<":if(g=this._unescapedIri.exec(r))f="IRI",u=g[1];else if(g=this._iri.exec(r)){if(u=this._unescape(g[1]),u===null||illegalIriChars.test(u))return o(this);f="IRI"}else r.length>1&&r[1]==="<"?(f="<<",y=2):this._n3Mode&&r.length>1&&r[1]==="="&&(y=2,this._isImpliedBy?(f="abbreviation",u="<"):(f="inverse",u=">"));break;case">":r.length>1&&r[1]===">"&&(f=">>",y=2);break;case"_":((g=this._blank.exec(r))||t&&(g=this._blank.exec(`${r} `)))&&(f="blank",p="_",u=g[1]);break;case'"':if(g=this._simpleQuotedString.exec(r))u=g[1];else if({value:u,matchLength:y}=this._parseLiteral(r),u===null)return o(this);(g!==null||y!==0)&&(f="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(g=this._simpleApostropheString.exec(r))u=g[1];else if({value:u,matchLength:y}=this._parseLiteral(r),u===null)return o(this);(g!==null||y!==0)&&(f="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(g=this._variable.exec(r))&&(f="var",u=g[0]);break;case"@":this._previousMarker==="literal"&&(g=this._langcode.exec(r))?(f="langcode",u=g[1]):(g=this._keyword.exec(r))&&(f=g[0]);break;case".":if(r.length===1?t:r[1]<"0"||r[1]>"9"){f=".",y=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(g=this._number.exec(r)||t&&(g=this._number.exec(`${r} `)))&&(f="literal",u=g[0],p=typeof g[1]=="string"?xsd$2.double:typeof g[2]=="string"?xsd$2.decimal:xsd$2.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(g=this._sparqlKeyword.exec(r))?f=g[0].toUpperCase():w=!0;break;case"f":case"t":(g=this._boolean.exec(r))?(f="literal",u=g[0],p=xsd$2.boolean):w=!0;break;case"a":(g=this._shortPredicates.exec(r))?(f="abbreviation",u="a"):w=!0;break;case"=":this._n3Mode&&r.length>1&&(f="abbreviation",r[1]!==">"?(y=1,u="="):(y=2,u=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(y=1,f=d);break;case"{":!this._lineMode&&r.length>=2&&(r[1]==="|"?(f="{|",y=2):(f=d,y=1));break;case"|":r.length>=2&&r[1]==="}"&&(f="|}",y=2);break;default:w=!0}if(w&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(g=this._prefix.exec(r))?(f="prefix",u=g[1]||""):((g=this._prefixed.exec(r))||t&&(g=this._prefixed.exec(`${r} `)))&&(f="prefixed",p=g[1]||"",u=this._unescape(g[2]))),this._previousMarker==="^^")switch(f){case"prefixed":f="type";break;case"IRI":f="typeIRI";break;default:f=""}if(!f)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?o(this):this._input=r;const _=y||g[0].length,R=s(f,u,p,l,_);this.previousToken=R,this._previousMarker=f,r=r.substr(_,r.length)}function s(a,c,l,d,f){const u=r?i-r.length:i,p=u+f,g={type:a,value:c,prefix:l,line:d,start:u,end:p};return e(null,g),g}function o(a){e(a._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1;const r=e.replace(escapeSequence,(i,s,o,a)=>{if(typeof s=="string")return String.fromCharCode(Number.parseInt(s,16));if(typeof o=="string"){let c=Number.parseInt(o,16);return c<=65535?String.fromCharCode(Number.parseInt(o,16)):String.fromCharCode(55296+((c-=65536)>>10),56320+(c&1023))}return a in escapeReplacements?escapeReplacements[a]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length;let i=Math.max(this._literalClosingPos,r);for(;(i=e.indexOf(t,i))>0;){let s=0;for(;e[i-s-1]==="\\";)s++;if(s%2===0){const o=e.substring(r,i),a=o.split(/\r\n|\r|\n/).length-1,c=i+r;if(r===1&&a!==0||r===3&&this._lineMode)break;return this._line+=a,{value:this._unescape(o),matchLength:c}}i++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const r=[];let i;if(this._tokenizeToEnd((s,o)=>s?i=s:r.push(o),!0),i)throw i;return r}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",r=>{this._input!==null&&r.length!==0&&(this._pendingBuffer&&(r=bufferExports.Buffer.concat([this._pendingBuffer,r]),this._pendingBuffer=null),r[r.length-1]&128?this._pendingBuffer=r:(typeof this._input>"u"?this._input=this._readStartingBom(typeof r=="string"?r:r.toString()):this._input+=r,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:rdf$1,xsd:xsd$1}=namespaces;let DEFAULTGRAPH$1,_blankNodeCounter=0;const DataFactory$1={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}let NamedNode$1=class extends Term{get termType(){return"NamedNode"}},Literal$1=class xn extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode$1(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return r==="^"?e.substr(t+2):r!=="@"?xsd$1.string:rdf$1.langString}equals(e){return e instanceof xn?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}},BlankNode$1=class extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}},Variable$1=class extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}},DefaultGraph$1=class extends Term{constructor(){return super(""),DEFAULTGRAPH$1||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};DEFAULTGRAPH$1=new DefaultGraph$1;function termFromId(n,e,t){if(e=e||DataFactory$1,!n)return e.defaultGraph();switch(n[0]){case"?":return e.variable(n.substr(1));case"_":return e.blankNode(n.substr(2));case'"':if(e===DataFactory$1)return new Literal$1(n);if(n[n.length-1]==='"')return e.literal(n.substr(1,n.length-2));const r=n.lastIndexOf('"',n.length-1);return e.literal(n.substr(1,r-1),n[r+1]==="@"?n.substr(r+2):e.namedNode(n.substr(r+3)));case"[":n=JSON.parse(n);break;default:if(!t||!Array.isArray(n))return e.namedNode(n)}return e.quad(termFromId(n[0],e,!0),termFromId(n[1],e,!0),termFromId(n[2],e,!0),n[3]&&termFromId(n[3],e,!0))}function termToId(n,e){if(typeof n=="string")return n;if(n instanceof Term&&n.termType!=="Quad")return n.id;if(!n)return DEFAULTGRAPH$1.id;switch(n.termType){case"NamedNode":return n.value;case"BlankNode":return`_:${n.value}`;case"Variable":return`?${n.value}`;case"DefaultGraph":return"";case"Literal":return`"${n.value}"${n.language?`@${n.language}`:n.datatype&&n.datatype.value!==xsd$1.string?`^^${n.datatype.value}`:""}`;case"Quad":const t=[termToId(n.subject,!0),termToId(n.predicate,!0),termToId(n.object,!0)];return n.graph&&n.graph.termType!=="DefaultGraph"&&t.push(termToId(n.graph,!0)),e?t:JSON.stringify(t);default:throw new Error(`Unexpected termType: ${n.termType}`)}}let Quad$1=class extends Term{constructor(e,t,r,i){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=i||DEFAULTGRAPH$1}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}};function namedNode(n){return new NamedNode$1(n)}function blankNode(n){return new BlankNode$1(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal$1(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd$1.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd$1.integer:xsd$1.double:(t=xsd$1.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd$1.string?new Literal$1(`"${n}"`):new Literal$1(`"${n}"^^${t}`)}function variable(n){return new Variable$1(n)}function defaultGraph(){return DEFAULTGRAPH$1}function quad(n,e,t,r){return new Quad$1(n,e,t,r)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH$1;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad$1)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),i=/trig/.test(t),s=/triple/.test(t),o=/quad/.test(t),a=this._n3Mode=/n3/.test(t),c=s||o;(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||i||s||a),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),c&&(this._resolveRelativeIRI=l=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:c,n3:a,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,r,i,s){const o=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:i,object:s,graph:t,inverse:o?this._inversePredicate:!1,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":const i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);r=this._factory.namedNode(i);break;case"type":case"prefixed":const s=this._prefixes[e.prefix];if(s===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(s+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,i=this._readListItem;const s=this._subject,o=this._contextStack,a=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),o.length!==0&&o[o.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;r=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(r===null&&(this._subject=r=this._factory.blankNode()),s===null?a.predicate===null?a.subject=r:a.object=r:this._emit(s,this.RDF_REST,r,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return i}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const r=this._readEntity(e);if(r===void 0)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),r.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph;const i=this._subject,s=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,s&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const o=this._predicate,a=this._object;this._subject=this._factory.quad(i,o,a,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(r=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){const o=this._predicate,a=this._object;s?this._emit(a,o,i,r):this._emit(i,o,a,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,r=t.length&&t[t.length-1];if(r&&r.type==="item"){const i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r;const i=this._factory.blankNode();if((r=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,r,i,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let r,i;if((r=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,r,i,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,i){this._callback(null,this._factory.quad(e,t,r,i||this.DEFAULTGRAPH))}_error(e,t){const r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let r="",i=-1,s=-1,o=0,a="/";for(;i<t;){switch(a){case":":if(s<0&&e[++i]==="/"&&e[++i]==="/")for(;(s=i+1)<t&&e[s]!=="/";)i=s;break;case"?":case"#":i=t;break;case"/":if(e[i+1]===".")switch(a=e[++i+1],a){case"/":r+=e.substring(o,i-1),o=i+1;break;case void 0:case"?":case"#":return r+e.substring(o,i)+e.substr(i+1);case".":if(a=e[++i+1],a===void 0||a==="/"||a==="?"||a==="#"){if(r+=e.substring(o,i-2),(o=r.lastIndexOf("/"))>=s&&(r=r.substr(0,o)),a!=="/")return`${r}/${e.substr(i+1)}`;o=i+1}}}a=e[++i]}return r+e.substring(o)}parse(e,t,r){let i,s,o;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,s=t.onPrefix,o=t.onComment):(i=t,s=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=s||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!i){const c=[];let l;if(this._callback=(d,f)=>{d?l=d:f&&c.push(f)},this._lexer.tokenize(e).every(d=>this._readCallback=this._readCallback(d)),l)throw l;return c}let a=(c,l)=>{c!==null?(this._callback(c),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(l))};o&&(this._lexer.comments=!0,a=(c,l)=>{c!==null?(this._callback(c),this._callback=noop):this._readCallback&&(l.type==="comment"?o(l.value):this._readCallback=this._readCallback(l))}),this._callback=i,this._lexer.tokenize(e,a)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory$1);function isDefaultGraph(n){return!!n&&n.termType==="DefaultGraph"}function escapeRegex$1(n){return n.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const BASE_UNSUPPORTED=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,SUFFIX_SUPPORTED=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,CURRENT="./",PARENT="../",QUERY="?",FRAGMENT="#";class BaseIRI{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!BASE_UNSUPPORTED.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",escapeRegex$1(e)],r=[],i=[],s=/[^/?#]*([/?#])/y;let o,a=0,c=0,l=s.lastIndex=e.length;for(;!a&&!c&&(o=s.exec(this.base));)o[1]===FRAGMENT?c=s.lastIndex-1:(t.push(escapeRegex$1(o[0]),"(?:"),r.push(")?"),o[1]!==QUERY?i.push(l=s.lastIndex):(a=l=s.lastIndex,c=this.base.indexOf(FRAGMENT,a),this._pathReplacements[a]=QUERY));for(let d=0;d<i.length;d++)this._pathReplacements[i[d]]=PARENT.repeat(i.length-d-1);return this._pathReplacements[i[i.length-1]]=CURRENT,this._baseLength=c>0?c:this.base.length,t.push(escapeRegex$1(this.base.substring(l,this._baseLength)),a?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...r].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const r=t[0].length;if(r===this._baseLength&&r===e.length)return"";const i=this._pathReplacements[r];if(i){const s=e.substring(r);return i!==QUERY&&!SUFFIX_SUPPORTED.test(s)?e:i===CURRENT&&/^[^?#]/.test(s)?s:i+s}return e.substring(r-1)}}const DEFAULTGRAPH=DataFactory$1.defaultGraph(),{rdf,xsd}=namespaces,escape=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,escapeAll=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,escapedCharacters={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class SerializedTerm extends Term{equals(e){return e===this}}class N3Writer{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let r="";this._outputStream={write(i,s,o){r+=i,o&&o()},end:i=>{i&&i(null,r)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=DEFAULTGRAPH,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new BaseIRI(t.baseIRI)))}get _inDefaultGraph(){return DEFAULTGRAPH.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,r,i,s){try{i.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`.
8
+ `:`
9
+ }
10
+ `)+(DEFAULTGRAPH.equals(i)?"":`${this._encodeIriOrBlank(i)} {
11
+ `)),this._graph=i,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(r)}`,s):this._write(`;
12
+ ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s):this._write(`${(this._subject===null?"":`.
13
+ `)+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(r)}`,s)}catch(o){s&&s(o)}}_writeQuadLine(e,t,r,i,s){delete this._prefixMatch,this._write(this.quadToString(e,t,r,i),s)}quadToString(e,t,r,i){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(r)}${i&&i.value?` ${this._encodeIriOrBlank(i)} .
14
+ `:` .
15
+ `}`}quadsToString(e){let t="";for(const r of e)t+=this.quadToString(r.subject,r.predicate,r.object,r.graph);return t}_encodeSubject(e){return e.termType==="Quad"?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if(e.termType!=="NamedNode")return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),escape.test(t)&&(t=t.replace(escapeAll,characterReplacer));const r=this._prefixRegex.exec(t);return r?r[1]?this._prefixIRIs[r[1]]+r[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(escape.test(t)&&(t=t.replace(escapeAll,characterReplacer)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===xsd.string)return`"${t}"`}else switch(e.datatype.value){case xsd.string:return`"${t}"`;case xsd.boolean:if(t==="true"||t==="false")return t;break;case xsd.integer:if(/^[+-]?\d+$/.test(t))return t;break;case xsd.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case xsd.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t;break}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===rdf.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:r,graph:i}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(r)}${isDefaultGraph(i)?"":` ${this._encodeIriOrBlank(i)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,r,i,s){r===void 0?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):typeof i=="function"?this._writeQuad(e,t,r,DEFAULTGRAPH,i):this._writeQuad(e,t,r,i||DEFAULTGRAPH,s)}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}addPrefix(e,t,r){const i={};i[e]=t,this.addPrefixes(i,r)}addPrefixes(e,t){if(!this._prefixIRIs)return t&&t();let r=!1;for(let i in e){let s=e[i];typeof s!="string"&&(s=s.value),r=!0,this._subject!==null&&(this._write(this._inDefaultGraph?`.
16
+ `:`
17
+ }
18
+ `),this._subject=null,this._graph=""),this._prefixIRIs[s]=i+=":",this._write(`@prefix ${i} <${s}>.
19
+ `)}if(r){let i="",s="";for(const o in this._prefixIRIs)i+=i?`|${o}`:o,s+=(s?"|":"")+this._prefixIRIs[o];i=escapeRegex$1(i),this._prefixRegex=new RegExp(`^(?:${s})[^/]*$|^(${i})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(r?`
20
+ `:"",t)}blank(e,t){let r=e,i,s;switch(e===void 0?r=[]:e.termType?r=[{predicate:e,object:t}]:"length"in e||(r=[e]),s=r.length){case 0:return new SerializedTerm("[]");case 1:if(i=r[0],!(i.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)} ]`);default:let o="[";for(let a=0;a<s;a++)i=r[a],i.predicate.equals(e)?o+=`, ${this._encodeObject(i.object)}`:(o+=`${(a?`;
21
+ `:`
22
+ `)+this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)}`,e=i.predicate);return new SerializedTerm(`${o}
23
+ ]`)}}list(e){const t=e&&e.length||0,r=new Array(t);for(let i=0;i<t;i++)r[i]=this._encodeObject(e[i]);return new SerializedTerm(`(${r.join(" ")})`)}end(e){this._subject!==null&&(this._write(this._inDefaultGraph?`.
24
+ `:`
25
+ }
26
+ `),this._subject=null),this._write=this._blockedWrite;let t=e&&((r,i)=>{t=null,e(r,i)});if(this._endStream)try{return this._outputStream.end(t)}catch{}t&&t()}}function characterReplacer(n){let e=escapedCharacters[n];return e===void 0&&(n.length===1?(e=n.charCodeAt(0).toString(16),e="\\u0000".substr(0,6-e.length)+e):(e=((n.charCodeAt(0)-55296)*1024+n.charCodeAt(1)+9216).toString(16),e="\\U00000000".substr(0,10-e.length)+e)),e}var browser$2={exports:{}},stream={exports:{}},primordials,hasRequiredPrimordials;function requirePrimordials(){if(hasRequiredPrimordials)return primordials;hasRequiredPrimordials=1;class n extends Error{constructor(t){if(!Array.isArray(t))throw new TypeError(`Expected input to be an Array, got ${typeof t}`);let r="";for(let i=0;i<t.length;i++)r+=` ${t[i].stack}
27
+ `;super(r),this.name="AggregateError",this.errors=t}}return primordials={AggregateError:n,ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean,Uint8Array},primordials}var util={exports:{}},inspect,hasRequiredInspect;function requireInspect(){return hasRequiredInspect||(hasRequiredInspect=1,inspect={format(n,...e){return n.replace(/%([sdifj])/g,function(...[t,r]){const i=e.shift();return r==="f"?i.toFixed(6):r==="j"?JSON.stringify(i):r==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(n){switch(typeof n){case"string":if(n.includes("'"))if(n.includes('"')){if(!n.includes("`")&&!n.includes("${"))return`\`${n}\``}else return`"${n}"`;return`'${n}'`;case"number":return isNaN(n)?"NaN":Object.is(n,-0)?String(n):n;case"bigint":return`${String(n)}n`;case"boolean":case"undefined":return String(n);case"object":return"{}"}}}),inspect}var errors,hasRequiredErrors;function requireErrors(){if(hasRequiredErrors)return errors;hasRequiredErrors=1;const{format:n,inspect:e}=requireInspect(),{AggregateError:t}=requirePrimordials(),r=globalThis.AggregateError||t,i=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o=/^([A-Z][a-z0-9]*)+$/,a="__node_internal_",c={};function l(w,_){if(!w)throw new c.ERR_INTERNAL_ASSERTION(_)}function d(w){let _="",R=w.length;const b=w[0]==="-"?1:0;for(;R>=b+4;R-=3)_=`_${w.slice(R-3,R)}${_}`;return`${w.slice(0,R)}${_}`}function f(w,_,R){if(typeof _=="function")return l(_.length<=R.length,`Code: ${w}; The provided arguments length (${R.length}) does not match the required ones (${_.length}).`),_(...R);const b=(_.match(/%[dfijoOs]/g)||[]).length;return l(b===R.length,`Code: ${w}; The provided arguments length (${R.length}) does not match the required ones (${b}).`),R.length===0?_:n(_,...R)}function u(w,_,R){R||(R=Error);class b extends R{constructor(...P){super(f(w,_,P))}toString(){return`${this.name} [${w}]: ${this.message}`}}Object.defineProperties(b.prototype,{name:{value:R.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${w}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),b.prototype.code=w,b.prototype[i]=!0,c[w]=b}function p(w){const _=a+w.name;return Object.defineProperty(w,"name",{value:_}),w}function g(w,_){if(w&&_&&w!==_){if(Array.isArray(_.errors))return _.errors.push(w),_;const R=new r([_,w],_.message);return R.code=_.code,R}return w||_}class y extends Error{constructor(_="The operation was aborted",R=void 0){if(R!==void 0&&typeof R!="object")throw new c.ERR_INVALID_ARG_TYPE("options","Object",R);super(_,R),this.code="ABORT_ERR",this.name="AbortError"}}return u("ERR_ASSERTION","%s",Error),u("ERR_INVALID_ARG_TYPE",(w,_,R)=>{l(typeof w=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let b="The ";w.endsWith(" argument")?b+=`${w} `:b+=`"${w}" ${w.includes(".")?"property":"argument"} `,b+="must be ";const C=[],P=[],H=[];for(const re of _)l(typeof re=="string","All expected entries have to be of type string"),s.includes(re)?C.push(re.toLowerCase()):o.test(re)?P.push(re):(l(re!=="object",'The value "object" should be written as "Object"'),H.push(re));if(P.length>0){const re=C.indexOf("object");re!==-1&&(C.splice(C,re,1),P.push("Object"))}if(C.length>0){switch(C.length){case 1:b+=`of type ${C[0]}`;break;case 2:b+=`one of type ${C[0]} or ${C[1]}`;break;default:{const re=C.pop();b+=`one of type ${C.join(", ")}, or ${re}`}}(P.length>0||H.length>0)&&(b+=" or ")}if(P.length>0){switch(P.length){case 1:b+=`an instance of ${P[0]}`;break;case 2:b+=`an instance of ${P[0]} or ${P[1]}`;break;default:{const re=P.pop();b+=`an instance of ${P.join(", ")}, or ${re}`}}H.length>0&&(b+=" or ")}switch(H.length){case 0:break;case 1:H[0].toLowerCase()!==H[0]&&(b+="an "),b+=`${H[0]}`;break;case 2:b+=`one of ${H[0]} or ${H[1]}`;break;default:{const re=H.pop();b+=`one of ${H.join(", ")}, or ${re}`}}if(R==null)b+=`. Received ${R}`;else if(typeof R=="function"&&R.name)b+=`. Received function ${R.name}`;else if(typeof R=="object"){var M;if((M=R.constructor)!==null&&M!==void 0&&M.name)b+=`. Received an instance of ${R.constructor.name}`;else{const re=e(R,{depth:-1});b+=`. Received ${re}`}}else{let re=e(R,{colors:!1});re.length>25&&(re=`${re.slice(0,25)}...`),b+=`. Received type ${typeof R} (${re})`}return b},TypeError),u("ERR_INVALID_ARG_VALUE",(w,_,R="is invalid")=>{let b=e(_);return b.length>128&&(b=b.slice(0,128)+"..."),`The ${w.includes(".")?"property":"argument"} '${w}' ${R}. Received ${b}`},TypeError),u("ERR_INVALID_RETURN_VALUE",(w,_,R)=>{var b;const C=R!=null&&(b=R.constructor)!==null&&b!==void 0&&b.name?`instance of ${R.constructor.name}`:`type ${typeof R}`;return`Expected ${w} to be returned from the "${_}" function but got ${C}.`},TypeError),u("ERR_MISSING_ARGS",(...w)=>{l(w.length>0,"At least one arg needs to be specified");let _;const R=w.length;switch(w=(Array.isArray(w)?w:[w]).map(b=>`"${b}"`).join(" or "),R){case 1:_+=`The ${w[0]} argument`;break;case 2:_+=`The ${w[0]} and ${w[1]} arguments`;break;default:{const b=w.pop();_+=`The ${w.join(", ")}, and ${b} arguments`}break}return`${_} must be specified`},TypeError),u("ERR_OUT_OF_RANGE",(w,_,R)=>{l(_,'Missing "range" argument');let b;if(Number.isInteger(R)&&Math.abs(R)>2**32)b=d(String(R));else if(typeof R=="bigint"){b=String(R);const C=BigInt(2)**BigInt(32);(R>C||R<-C)&&(b=d(b)),b+="n"}else b=e(R);return`The value of "${w}" is out of range. It must be ${_}. Received ${b}`},RangeError),u("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),u("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),u("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),u("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),u("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),u("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),u("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),u("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),u("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),u("ERR_STREAM_WRITE_AFTER_END","write after end",Error),u("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),errors={AbortError:y,aggregateTwoErrors:p(g),hideStackFrames:p,codes:c},errors}var browser$1={exports:{}},hasRequiredBrowser$2;function requireBrowser$2(){if(hasRequiredBrowser$2)return browser$1.exports;hasRequiredBrowser$2=1;const{AbortController:n,AbortSignal:e}=typeof self<"u"?self:typeof window<"u"?window:void 0;return browser$1.exports=n,browser$1.exports.AbortSignal=e,browser$1.exports.default=n,browser$1.exports}var hasRequiredUtil;function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,(function(n){const e=requireBuffer(),{format:t,inspect:r}=requireInspect(),{codes:{ERR_INVALID_ARG_TYPE:i}}=requireErrors(),{kResistStopPropagation:s,AggregateError:o,SymbolDispose:a}=requirePrimordials(),c=globalThis.AbortSignal||requireBrowser$2().AbortSignal,l=globalThis.AbortController||requireBrowser$2().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||e.Blob,u=typeof f<"u"?function(w){return w instanceof f}:function(w){return!1},p=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new i(w,"AbortSignal",y)},g=(y,w)=>{if(typeof y!="function")throw new i(w,"Function",y)};n.exports={AggregateError:o,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(..._){w||(w=!0,y.apply(this,_))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((R,b)=>{y=R,w=b}),resolve:y,reject:w}},promisify(y){return new Promise((w,_)=>{y((R,...b)=>R?_(R):w(...b))})},debuglog(){return function(){}},format:t,inspect:r,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:u,deprecate(y,w){return y},addAbortListener:requireEvents().addAbortListener||function(w,_){if(w===void 0)throw new i("signal","AbortSignal",w);p(w,"signal"),g(_,"listener");let R;return w.aborted?queueMicrotask(()=>_()):(w.addEventListener("abort",_,{__proto__:null,once:!0,[s]:!0}),R=()=>{w.removeEventListener("abort",_)}),{__proto__:null,[a](){var b;(b=R)===null||b===void 0||b()}}},AbortSignalAny:c.any||function(w){if(w.length===1)return w[0];const _=new l,R=()=>_.abort();return w.forEach(b=>{p(b,"signals"),b.addEventListener("abort",R,{once:!0})}),_.signal.addEventListener("abort",()=>{w.forEach(b=>b.removeEventListener("abort",R))},{once:!0}),_.signal}},n.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")})(util)),util.exports}var operators={},validators,hasRequiredValidators;function requireValidators(){if(hasRequiredValidators)return validators;hasRequiredValidators=1;const{ArrayIsArray:n,ArrayPrototypeIncludes:e,ArrayPrototypeJoin:t,ArrayPrototypeMap:r,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:o,NumberMIN_SAFE_INTEGER:a,NumberParseInt:c,ObjectPrototypeHasOwnProperty:l,RegExpPrototypeExec:d,String:f,StringPrototypeToUpperCase:u,StringPrototypeTrim:p}=requirePrimordials(),{hideStackFrames:g,codes:{ERR_SOCKET_BAD_PORT:y,ERR_INVALID_ARG_TYPE:w,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:R,ERR_UNKNOWN_SIGNAL:b}}=requireErrors(),{normalizeEncoding:C}=requireUtil(),{isAsyncFunction:P,isArrayBufferView:H}=requireUtil().types,M={};function re(N){return N===(N|0)}function he(N){return N===N>>>0}const V=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function ie(N,z,K){if(typeof N>"u"&&(N=K),typeof N=="string"){if(d(V,N)===null)throw new _(z,N,q);N=c(N,8)}return Se(N,z),N}const U=g((N,z,K=a,j=o)=>{if(typeof N!="number")throw new w(z,"number",N);if(!i(N))throw new R(z,"an integer",N);if(N<K||N>j)throw new R(z,`>= ${K} && <= ${j}`,N)}),ce=g((N,z,K=-2147483648,j=2147483647)=>{if(typeof N!="number")throw new w(z,"number",N);if(!i(N))throw new R(z,"an integer",N);if(N<K||N>j)throw new R(z,`>= ${K} && <= ${j}`,N)}),Se=g((N,z,K=!1)=>{if(typeof N!="number")throw new w(z,"number",N);if(!i(N))throw new R(z,"an integer",N);const j=K?1:0,we=4294967295;if(N<j||N>we)throw new R(z,`>= ${j} && <= ${we}`,N)});function me(N,z){if(typeof N!="string")throw new w(z,"string",N)}function Ne(N,z,K=void 0,j){if(typeof N!="number")throw new w(z,"number",N);if(K!=null&&N<K||j!=null&&N>j||(K!=null||j!=null)&&s(N))throw new R(z,`${K!=null?`>= ${K}`:""}${K!=null&&j!=null?" && ":""}${j!=null?`<= ${j}`:""}`,N)}const te=g((N,z,K)=>{if(!e(K,N)){const we="must be one of: "+t(r(K,Ee=>typeof Ee=="string"?`'${Ee}'`:f(Ee)),", ");throw new _(z,N,we)}});function ae(N,z){if(typeof N!="boolean")throw new w(z,"boolean",N)}function x(N,z,K){return N==null||!l(N,z)?K:N[z]}const O=g((N,z,K=null)=>{const j=x(K,"allowArray",!1),we=x(K,"allowFunction",!1);if(!x(K,"nullable",!1)&&N===null||!j&&n(N)||typeof N!="object"&&(!we||typeof N!="function"))throw new w(z,"Object",N)}),se=g((N,z)=>{if(N!=null&&typeof N!="object"&&typeof N!="function")throw new w(z,"a dictionary",N)}),G=g((N,z,K=0)=>{if(!n(N))throw new w(z,"Array",N);if(N.length<K){const j=`must be longer than ${K}`;throw new _(z,N,j)}});function le(N,z){G(N,z);for(let K=0;K<N.length;K++)me(N[K],`${z}[${K}]`)}function pe(N,z){G(N,z);for(let K=0;K<N.length;K++)ae(N[K],`${z}[${K}]`)}function Re(N,z){G(N,z);for(let K=0;K<N.length;K++){const j=N[K],we=`${z}[${K}]`;if(j==null)throw new w(we,"AbortSignal",j);ye(j,we)}}function _e(N,z="signal"){if(me(N,z),M[N]===void 0)throw M[u(N)]!==void 0?new b(N+" (signals must use all capital letters)"):new b(N)}const B=g((N,z="buffer")=>{if(!H(N))throw new w(z,["Buffer","TypedArray","DataView"],N)});function Z(N,z){const K=C(z),j=N.length;if(K==="hex"&&j%2!==0)throw new _("encoding",z,`is invalid for data of length ${j}`)}function oe(N,z="Port",K=!0){if(typeof N!="number"&&typeof N!="string"||typeof N=="string"&&p(N).length===0||+N!==+N>>>0||N>65535||N===0&&!K)throw new y(z,N,K);return N|0}const ye=g((N,z)=>{if(N!==void 0&&(N===null||typeof N!="object"||!("aborted"in N)))throw new w(z,"AbortSignal",N)}),ge=g((N,z)=>{if(typeof N!="function")throw new w(z,"Function",N)}),D=g((N,z)=>{if(typeof N!="function"||P(N))throw new w(z,"Function",N)}),F=g((N,z)=>{if(N!==void 0)throw new w(z,"undefined",N)});function k(N,z,K){if(!e(K,N))throw new w(z,`('${t(K,"|")}')`,N)}const ee=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function J(N,z){if(typeof N>"u"||!d(ee,N))throw new _(z,N,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function X(N){if(typeof N=="string")return J(N,"hints"),N;if(n(N)){const z=N.length;let K="";if(z===0)return K;for(let j=0;j<z;j++){const we=N[j];J(we,"hints"),K+=we,j!==z-1&&(K+=", ")}return K}throw new _("hints",N,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}return validators={isInt32:re,isUint32:he,parseFileMode:ie,validateArray:G,validateStringArray:le,validateBooleanArray:pe,validateAbortSignalArray:Re,validateBoolean:ae,validateBuffer:B,validateDictionary:se,validateEncoding:Z,validateFunction:ge,validateInt32:ce,validateInteger:U,validateNumber:Ne,validateObject:O,validateOneOf:te,validatePlainFunction:D,validatePort:oe,validateSignalName:_e,validateString:me,validateUint32:Se,validateUndefined:F,validateUnion:k,validateAbortSignal:ye,validateLinkHeaderValue:X},validators}var endOfStream={exports:{}},browser={exports:{}},hasRequiredBrowser$1;function requireBrowser$1(){if(hasRequiredBrowser$1)return browser.exports;hasRequiredBrowser$1=1;var n=browser.exports={},e,t;function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?e=setTimeout:e=r}catch{e=r}try{typeof clearTimeout=="function"?t=clearTimeout:t=i}catch{t=i}})();function s(y){if(e===setTimeout)return setTimeout(y,0);if((e===r||!e)&&setTimeout)return e=setTimeout,setTimeout(y,0);try{return e(y,0)}catch{try{return e.call(null,y,0)}catch{return e.call(this,y,0)}}}function o(y){if(t===clearTimeout)return clearTimeout(y);if((t===i||!t)&&clearTimeout)return t=clearTimeout,clearTimeout(y);try{return t(y)}catch{try{return t.call(null,y)}catch{return t.call(this,y)}}}var a=[],c=!1,l,d=-1;function f(){!c||!l||(c=!1,l.length?a=l.concat(a):d=-1,a.length&&u())}function u(){if(!c){var y=s(f);c=!0;for(var w=a.length;w;){for(l=a,a=[];++d<w;)l&&l[d].run();d=-1,w=a.length}l=null,c=!1,o(y)}}n.nextTick=function(y){var w=new Array(arguments.length-1);if(arguments.length>1)for(var _=1;_<arguments.length;_++)w[_-1]=arguments[_];a.push(new p(y,w)),a.length===1&&!c&&s(u)};function p(y,w){this.fun=y,this.array=w}p.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={};function g(){}return n.on=g,n.addListener=g,n.once=g,n.off=g,n.removeListener=g,n.removeAllListeners=g,n.emit=g,n.prependListener=g,n.prependOnceListener=g,n.listeners=function(y){return[]},n.binding=function(y){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(y){throw new Error("process.chdir is not supported")},n.umask=function(){return 0},browser.exports}var utils,hasRequiredUtils;function requireUtils(){if(hasRequiredUtils)return utils;hasRequiredUtils=1;const{SymbolAsyncIterator:n,SymbolIterator:e,SymbolFor:t}=requirePrimordials(),r=t("nodejs.stream.destroyed"),i=t("nodejs.stream.errored"),s=t("nodejs.stream.readable"),o=t("nodejs.stream.writable"),a=t("nodejs.stream.disturbed"),c=t("nodejs.webstream.isClosedPromise"),l=t("nodejs.webstream.controllerErrorFunction");function d(x,O=!1){var se;return!!(x&&typeof x.pipe=="function"&&typeof x.on=="function"&&(!O||typeof x.pause=="function"&&typeof x.resume=="function")&&(!x._writableState||((se=x._readableState)===null||se===void 0?void 0:se.readable)!==!1)&&(!x._writableState||x._readableState))}function f(x){var O;return!!(x&&typeof x.write=="function"&&typeof x.on=="function"&&(!x._readableState||((O=x._writableState)===null||O===void 0?void 0:O.writable)!==!1))}function u(x){return!!(x&&typeof x.pipe=="function"&&x._readableState&&typeof x.on=="function"&&typeof x.write=="function")}function p(x){return x&&(x._readableState||x._writableState||typeof x.write=="function"&&typeof x.on=="function"||typeof x.pipe=="function"&&typeof x.on=="function")}function g(x){return!!(x&&!p(x)&&typeof x.pipeThrough=="function"&&typeof x.getReader=="function"&&typeof x.cancel=="function")}function y(x){return!!(x&&!p(x)&&typeof x.getWriter=="function"&&typeof x.abort=="function")}function w(x){return!!(x&&!p(x)&&typeof x.readable=="object"&&typeof x.writable=="object")}function _(x){return g(x)||y(x)||w(x)}function R(x,O){return x==null?!1:O===!0?typeof x[n]=="function":O===!1?typeof x[e]=="function":typeof x[n]=="function"||typeof x[e]=="function"}function b(x){if(!p(x))return null;const O=x._writableState,se=x._readableState,G=O||se;return!!(x.destroyed||x[r]||G!=null&&G.destroyed)}function C(x){if(!f(x))return null;if(x.writableEnded===!0)return!0;const O=x._writableState;return O!=null&&O.errored?!1:typeof O?.ended!="boolean"?null:O.ended}function P(x,O){if(!f(x))return null;if(x.writableFinished===!0)return!0;const se=x._writableState;return se!=null&&se.errored?!1:typeof se?.finished!="boolean"?null:!!(se.finished||O===!1&&se.ended===!0&&se.length===0)}function H(x){if(!d(x))return null;if(x.readableEnded===!0)return!0;const O=x._readableState;return!O||O.errored?!1:typeof O?.ended!="boolean"?null:O.ended}function M(x,O){if(!d(x))return null;const se=x._readableState;return se!=null&&se.errored?!1:typeof se?.endEmitted!="boolean"?null:!!(se.endEmitted||O===!1&&se.ended===!0&&se.length===0)}function re(x){return x&&x[s]!=null?x[s]:typeof x?.readable!="boolean"?null:b(x)?!1:d(x)&&x.readable&&!M(x)}function he(x){return x&&x[o]!=null?x[o]:typeof x?.writable!="boolean"?null:b(x)?!1:f(x)&&x.writable&&!C(x)}function V(x,O){return p(x)?b(x)?!0:!(O?.readable!==!1&&re(x)||O?.writable!==!1&&he(x)):null}function q(x){var O,se;return p(x)?x.writableErrored?x.writableErrored:(O=(se=x._writableState)===null||se===void 0?void 0:se.errored)!==null&&O!==void 0?O:null:null}function ie(x){var O,se;return p(x)?x.readableErrored?x.readableErrored:(O=(se=x._readableState)===null||se===void 0?void 0:se.errored)!==null&&O!==void 0?O:null:null}function U(x){if(!p(x))return null;if(typeof x.closed=="boolean")return x.closed;const O=x._writableState,se=x._readableState;return typeof O?.closed=="boolean"||typeof se?.closed=="boolean"?O?.closed||se?.closed:typeof x._closed=="boolean"&&ce(x)?x._closed:null}function ce(x){return typeof x._closed=="boolean"&&typeof x._defaultKeepAlive=="boolean"&&typeof x._removedConnection=="boolean"&&typeof x._removedContLen=="boolean"}function Se(x){return typeof x._sent100=="boolean"&&ce(x)}function me(x){var O;return typeof x._consuming=="boolean"&&typeof x._dumped=="boolean"&&((O=x.req)===null||O===void 0?void 0:O.upgradeOrConnect)===void 0}function Ne(x){if(!p(x))return null;const O=x._writableState,se=x._readableState,G=O||se;return!G&&Se(x)||!!(G&&G.autoDestroy&&G.emitClose&&G.closed===!1)}function te(x){var O;return!!(x&&((O=x[a])!==null&&O!==void 0?O:x.readableDidRead||x.readableAborted))}function ae(x){var O,se,G,le,pe,Re,_e,B,Z,oe;return!!(x&&((O=(se=(G=(le=(pe=(Re=x[i])!==null&&Re!==void 0?Re:x.readableErrored)!==null&&pe!==void 0?pe:x.writableErrored)!==null&&le!==void 0?le:(_e=x._readableState)===null||_e===void 0?void 0:_e.errorEmitted)!==null&&G!==void 0?G:(B=x._writableState)===null||B===void 0?void 0:B.errorEmitted)!==null&&se!==void 0?se:(Z=x._readableState)===null||Z===void 0?void 0:Z.errored)!==null&&O!==void 0?O:!((oe=x._writableState)===null||oe===void 0)&&oe.errored))}return utils={isDestroyed:b,kIsDestroyed:r,isDisturbed:te,kIsDisturbed:a,isErrored:ae,kIsErrored:i,isReadable:re,kIsReadable:s,kIsClosedPromise:c,kControllerErrorFunction:l,kIsWritable:o,isClosed:U,isDuplexNodeStream:u,isFinished:V,isIterable:R,isReadableNodeStream:d,isReadableStream:g,isReadableEnded:H,isReadableFinished:M,isReadableErrored:ie,isNodeStream:p,isWebStream:_,isWritable:he,isWritableNodeStream:f,isWritableStream:y,isWritableEnded:C,isWritableFinished:P,isWritableErrored:q,isServerRequest:me,isServerResponse:Se,willEmitClose:Ne,isTransformStream:w},utils}var hasRequiredEndOfStream;function requireEndOfStream(){if(hasRequiredEndOfStream)return endOfStream.exports;hasRequiredEndOfStream=1;const n=requireBrowser$1(),{AbortError:e,codes:t}=requireErrors(),{ERR_INVALID_ARG_TYPE:r,ERR_STREAM_PREMATURE_CLOSE:i}=t,{kEmptyObject:s,once:o}=requireUtil(),{validateAbortSignal:a,validateFunction:c,validateObject:l,validateBoolean:d}=requireValidators(),{Promise:f,PromisePrototypeThen:u,SymbolDispose:p}=requirePrimordials(),{isClosed:g,isReadable:y,isReadableNodeStream:w,isReadableStream:_,isReadableFinished:R,isReadableErrored:b,isWritable:C,isWritableNodeStream:P,isWritableStream:H,isWritableFinished:M,isWritableErrored:re,isNodeStream:he,willEmitClose:V,kIsClosedPromise:q}=requireUtils();let ie;function U(te){return te.setHeader&&typeof te.abort=="function"}const ce=()=>{};function Se(te,ae,x){var O,se;if(arguments.length===2?(x=ae,ae=s):ae==null?ae=s:l(ae,"options"),c(x,"callback"),a(ae.signal,"options.signal"),x=o(x),_(te)||H(te))return me(te,ae,x);if(!he(te))throw new r("stream",["ReadableStream","WritableStream","Stream"],te);const G=(O=ae.readable)!==null&&O!==void 0?O:w(te),le=(se=ae.writable)!==null&&se!==void 0?se:P(te),pe=te._writableState,Re=te._readableState,_e=()=>{te.writable||oe()};let B=V(te)&&w(te)===G&&P(te)===le,Z=M(te,!1);const oe=()=>{Z=!0,te.destroyed&&(B=!1),!(B&&(!te.readable||G))&&(!G||ye)&&x.call(te)};let ye=R(te,!1);const ge=()=>{ye=!0,te.destroyed&&(B=!1),!(B&&(!te.writable||le))&&(!le||Z)&&x.call(te)},D=N=>{x.call(te,N)};let F=g(te);const k=()=>{F=!0;const N=re(te)||b(te);if(N&&typeof N!="boolean")return x.call(te,N);if(G&&!ye&&w(te,!0)&&!R(te,!1))return x.call(te,new i);if(le&&!Z&&!M(te,!1))return x.call(te,new i);x.call(te)},ee=()=>{F=!0;const N=re(te)||b(te);if(N&&typeof N!="boolean")return x.call(te,N);x.call(te)},J=()=>{te.req.on("finish",oe)};U(te)?(te.on("complete",oe),B||te.on("abort",k),te.req?J():te.on("request",J)):le&&!pe&&(te.on("end",_e),te.on("close",_e)),!B&&typeof te.aborted=="boolean"&&te.on("aborted",k),te.on("end",ge),te.on("finish",oe),ae.error!==!1&&te.on("error",D),te.on("close",k),F?n.nextTick(k):pe!=null&&pe.errorEmitted||Re!=null&&Re.errorEmitted?B||n.nextTick(ee):(!G&&(!B||y(te))&&(Z||C(te)===!1)||!le&&(!B||C(te))&&(ye||y(te)===!1)||Re&&te.req&&te.aborted)&&n.nextTick(ee);const X=()=>{x=ce,te.removeListener("aborted",k),te.removeListener("complete",oe),te.removeListener("abort",k),te.removeListener("request",J),te.req&&te.req.removeListener("finish",oe),te.removeListener("end",_e),te.removeListener("close",_e),te.removeListener("finish",oe),te.removeListener("end",ge),te.removeListener("error",D),te.removeListener("close",k)};if(ae.signal&&!F){const N=()=>{const z=x;X(),z.call(te,new e(void 0,{cause:ae.signal.reason}))};if(ae.signal.aborted)n.nextTick(N);else{ie=ie||requireUtil().addAbortListener;const z=ie(ae.signal,N),K=x;x=o((...j)=>{z[p](),K.apply(te,j)})}}return X}function me(te,ae,x){let O=!1,se=ce;if(ae.signal)if(se=()=>{O=!0,x.call(te,new e(void 0,{cause:ae.signal.reason}))},ae.signal.aborted)n.nextTick(se);else{ie=ie||requireUtil().addAbortListener;const le=ie(ae.signal,se),pe=x;x=o((...Re)=>{le[p](),pe.apply(te,Re)})}const G=(...le)=>{O||n.nextTick(()=>x.apply(te,le))};return u(te[q].promise,G,G),ce}function Ne(te,ae){var x;let O=!1;return ae===null&&(ae=s),(x=ae)!==null&&x!==void 0&&x.cleanup&&(d(ae.cleanup,"cleanup"),O=ae.cleanup),new f((se,G)=>{const le=Se(te,ae,pe=>{O&&le(),pe?G(pe):se()})})}return endOfStream.exports=Se,endOfStream.exports.finished=Ne,endOfStream.exports}var destroy_1,hasRequiredDestroy;function requireDestroy(){if(hasRequiredDestroy)return destroy_1;hasRequiredDestroy=1;const n=requireBrowser$1(),{aggregateTwoErrors:e,codes:{ERR_MULTIPLE_CALLBACK:t},AbortError:r}=requireErrors(),{Symbol:i}=requirePrimordials(),{kIsDestroyed:s,isDestroyed:o,isFinished:a,isServerRequest:c}=requireUtils(),l=i("kDestroy"),d=i("kConstruct");function f(V,q,ie){V&&(V.stack,q&&!q.errored&&(q.errored=V),ie&&!ie.errored&&(ie.errored=V))}function u(V,q){const ie=this._readableState,U=this._writableState,ce=U||ie;return U!=null&&U.destroyed||ie!=null&&ie.destroyed?(typeof q=="function"&&q(),this):(f(V,U,ie),U&&(U.destroyed=!0),ie&&(ie.destroyed=!0),ce.constructed?p(this,V,q):this.once(l,function(Se){p(this,e(Se,V),q)}),this)}function p(V,q,ie){let U=!1;function ce(Se){if(U)return;U=!0;const me=V._readableState,Ne=V._writableState;f(Se,Ne,me),Ne&&(Ne.closed=!0),me&&(me.closed=!0),typeof ie=="function"&&ie(Se),Se?n.nextTick(g,V,Se):n.nextTick(y,V)}try{V._destroy(q||null,ce)}catch(Se){ce(Se)}}function g(V,q){w(V,q),y(V)}function y(V){const q=V._readableState,ie=V._writableState;ie&&(ie.closeEmitted=!0),q&&(q.closeEmitted=!0),(ie!=null&&ie.emitClose||q!=null&&q.emitClose)&&V.emit("close")}function w(V,q){const ie=V._readableState,U=V._writableState;U!=null&&U.errorEmitted||ie!=null&&ie.errorEmitted||(U&&(U.errorEmitted=!0),ie&&(ie.errorEmitted=!0),V.emit("error",q))}function _(){const V=this._readableState,q=this._writableState;V&&(V.constructed=!0,V.closed=!1,V.closeEmitted=!1,V.destroyed=!1,V.errored=null,V.errorEmitted=!1,V.reading=!1,V.ended=V.readable===!1,V.endEmitted=V.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function R(V,q,ie){const U=V._readableState,ce=V._writableState;if(ce!=null&&ce.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||ce!=null&&ce.autoDestroy?V.destroy(q):q&&(q.stack,ce&&!ce.errored&&(ce.errored=q),U&&!U.errored&&(U.errored=q),ie?n.nextTick(w,V,q):w(V,q))}function b(V,q){if(typeof V._construct!="function")return;const ie=V._readableState,U=V._writableState;ie&&(ie.constructed=!1),U&&(U.constructed=!1),V.once(d,q),!(V.listenerCount(d)>1)&&n.nextTick(C,V)}function C(V){let q=!1;function ie(U){if(q){R(V,U??new t);return}q=!0;const ce=V._readableState,Se=V._writableState,me=Se||ce;ce&&(ce.constructed=!0),Se&&(Se.constructed=!0),me.destroyed?V.emit(l,U):U?R(V,U,!0):n.nextTick(P,V)}try{V._construct(U=>{n.nextTick(ie,U)})}catch(U){n.nextTick(ie,U)}}function P(V){V.emit(d)}function H(V){return V?.setHeader&&typeof V.abort=="function"}function M(V){V.emit("close")}function re(V,q){V.emit("error",q),n.nextTick(M,V)}function he(V,q){!V||o(V)||(!q&&!a(V)&&(q=new r),c(V)?(V.socket=null,V.destroy(q)):H(V)?V.abort():H(V.req)?V.req.abort():typeof V.destroy=="function"?V.destroy(q):typeof V.close=="function"?V.close():q?n.nextTick(re,V,q):n.nextTick(M,V),V.destroyed||(V[s]=!0))}return destroy_1={construct:b,destroyer:he,destroy:u,undestroy:_,errorOrDestroy:R},destroy_1}var legacy,hasRequiredLegacy;function requireLegacy(){if(hasRequiredLegacy)return legacy;hasRequiredLegacy=1;const{ArrayIsArray:n,ObjectSetPrototypeOf:e}=requirePrimordials(),{EventEmitter:t}=requireEvents();function r(s){t.call(this,s)}e(r.prototype,t.prototype),e(r,t),r.prototype.pipe=function(s,o){const a=this;function c(y){s.writable&&s.write(y)===!1&&a.pause&&a.pause()}a.on("data",c);function l(){a.readable&&a.resume&&a.resume()}s.on("drain",l),!s._isStdio&&(!o||o.end!==!1)&&(a.on("end",f),a.on("close",u));let d=!1;function f(){d||(d=!0,s.end())}function u(){d||(d=!0,typeof s.destroy=="function"&&s.destroy())}function p(y){g(),t.listenerCount(this,"error")===0&&this.emit("error",y)}i(a,"error",p),i(s,"error",p);function g(){a.removeListener("data",c),s.removeListener("drain",l),a.removeListener("end",f),a.removeListener("close",u),a.removeListener("error",p),s.removeListener("error",p),a.removeListener("end",g),a.removeListener("close",g),s.removeListener("close",g)}return a.on("end",g),a.on("close",g),s.on("close",g),s.emit("pipe",a),s};function i(s,o,a){if(typeof s.prependListener=="function")return s.prependListener(o,a);!s._events||!s._events[o]?s.on(o,a):n(s._events[o])?s._events[o].unshift(a):s._events[o]=[a,s._events[o]]}return legacy={Stream:r,prependListener:i},legacy}var addAbortSignal={exports:{}},hasRequiredAddAbortSignal;function requireAddAbortSignal(){return hasRequiredAddAbortSignal||(hasRequiredAddAbortSignal=1,(function(n){const{SymbolDispose:e}=requirePrimordials(),{AbortError:t,codes:r}=requireErrors(),{isNodeStream:i,isWebStream:s,kControllerErrorFunction:o}=requireUtils(),a=requireEndOfStream(),{ERR_INVALID_ARG_TYPE:c}=r;let l;const d=(f,u)=>{if(typeof f!="object"||!("aborted"in f))throw new c(u,"AbortSignal",f)};n.exports.addAbortSignal=function(u,p){if(d(u,"signal"),!i(p)&&!s(p))throw new c("stream",["ReadableStream","WritableStream","Stream"],p);return n.exports.addAbortSignalNoValidate(u,p)},n.exports.addAbortSignalNoValidate=function(f,u){if(typeof f!="object"||!("aborted"in f))return u;const p=i(u)?()=>{u.destroy(new t(void 0,{cause:f.reason}))}:()=>{u[o](new t(void 0,{cause:f.reason}))};if(f.aborted)p();else{l=l||requireUtil().addAbortListener;const g=l(f,p);a(u,g[e])}return u}})(addAbortSignal)),addAbortSignal.exports}var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;const{StringPrototypeSlice:n,SymbolIterator:e,TypedArrayPrototypeSet:t,Uint8Array:r}=requirePrimordials(),{Buffer:i}=requireBuffer(),{inspect:s}=requireUtil();return buffer_list=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){const c={data:a,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(a){const c={data:a,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;const a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let c=this.head,l=""+c.data;for(;(c=c.next)!==null;)l+=a+c.data;return l}concat(a){if(this.length===0)return i.alloc(0);const c=i.allocUnsafe(a>>>0);let l=this.head,d=0;for(;l;)t(c,l.data,d),d+=l.data.length,l=l.next;return c}consume(a,c){const l=this.head.data;if(a<l.length){const d=l.slice(0,a);return this.head.data=l.slice(a),d}return a===l.length?this.shift():c?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[e](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let c="",l=this.head,d=0;do{const f=l.data;if(a>f.length)c+=f,a-=f.length;else{a===f.length?(c+=f,++d,l.next?this.head=l.next:this.head=this.tail=null):(c+=n(f,0,a),this.head=l,l.data=n(f,a));break}++d}while((l=l.next)!==null);return this.length-=d,c}_getBuffer(a){const c=i.allocUnsafe(a),l=a;let d=this.head,f=0;do{const u=d.data;if(a>u.length)t(c,u,l-a),a-=u.length;else{a===u.length?(t(c,u,l-a),++f,d.next?this.head=d.next:this.head=this.tail=null):(t(c,new r(u.buffer,u.byteOffset,a),l-a),this.head=d,d.data=u.slice(a));break}++f}while((d=d.next)!==null);return this.length-=f,c}[Symbol.for("nodejs.util.inspect.custom")](a,c){return s(this,{...c,depth:0,customInspect:!1})}},buffer_list}var state,hasRequiredState;function requireState(){if(hasRequiredState)return state;hasRequiredState=1;const{MathFloor:n,NumberIsInteger:e}=requirePrimordials(),{validateInteger:t}=requireValidators(),{ERR_INVALID_ARG_VALUE:r}=requireErrors().codes;let i=16*1024,s=16;function o(d,f,u){return d.highWaterMark!=null?d.highWaterMark:f?d[u]:null}function a(d){return d?s:i}function c(d,f){t(f,"value",0),d?s=f:i=f}function l(d,f,u,p){const g=o(f,p,u);if(g!=null){if(!e(g)||g<0){const y=p?`options.${u}`:"options.highWaterMark";throw new r(y,g)}return n(g)}return a(d.objectMode)}return state={getHighWaterMark:l,getDefaultHighWaterMark:a,setDefaultHighWaterMark:c},state}var string_decoder={},safeBuffer={exports:{}};var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,(function(n,e){var t=requireBuffer(),r=t.Buffer;function i(o,a){for(var c in o)a[c]=o[c]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?n.exports=t:(i(t,e),e.Buffer=s);function s(o,a,c){return r(o,a,c)}s.prototype=Object.create(r.prototype),i(r,s),s.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,a,c)},s.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var l=r(o);return a!==void 0?typeof c=="string"?l.fill(a,c):l.fill(a):l.fill(0),l},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}})(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var n=requireSafeBuffer().Buffer,e=n.isEncoding||function(_){switch(_=""+_,_&&_.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function t(_){if(!_)return"utf8";for(var R;;)switch(_){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return _;default:if(R)return;_=(""+_).toLowerCase(),R=!0}}function r(_){var R=t(_);if(typeof R!="string"&&(n.isEncoding===e||!e(_)))throw new Error("Unknown encoding: "+_);return R||_}string_decoder.StringDecoder=i;function i(_){this.encoding=r(_);var R;switch(this.encoding){case"utf16le":this.text=f,this.end=u,R=4;break;case"utf8":this.fillLast=c,R=4;break;case"base64":this.text=p,this.end=g,R=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(R)}i.prototype.write=function(_){if(_.length===0)return"";var R,b;if(this.lastNeed){if(R=this.fillLast(_),R===void 0)return"";b=this.lastNeed,this.lastNeed=0}else b=0;return b<_.length?R?R+this.text(_,b):this.text(_,b):R||""},i.prototype.end=d,i.prototype.text=l,i.prototype.fillLast=function(_){if(this.lastNeed<=_.length)return _.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,this.lastTotal-this.lastNeed,0,_.length),this.lastNeed-=_.length};function s(_){return _<=127?0:_>>5===6?2:_>>4===14?3:_>>3===30?4:_>>6===2?-1:-2}function o(_,R,b){var C=R.length-1;if(C<b)return 0;var P=s(R[C]);return P>=0?(P>0&&(_.lastNeed=P-1),P):--C<b||P===-2?0:(P=s(R[C]),P>=0?(P>0&&(_.lastNeed=P-2),P):--C<b||P===-2?0:(P=s(R[C]),P>=0?(P>0&&(P===2?P=0:_.lastNeed=P-3),P):0))}function a(_,R,b){if((R[0]&192)!==128)return _.lastNeed=0,"�";if(_.lastNeed>1&&R.length>1){if((R[1]&192)!==128)return _.lastNeed=1,"�";if(_.lastNeed>2&&R.length>2&&(R[2]&192)!==128)return _.lastNeed=2,"�"}}function c(_){var R=this.lastTotal-this.lastNeed,b=a(this,_);if(b!==void 0)return b;if(this.lastNeed<=_.length)return _.copy(this.lastChar,R,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);_.copy(this.lastChar,R,0,_.length),this.lastNeed-=_.length}function l(_,R){var b=o(this,_,R);if(!this.lastNeed)return _.toString("utf8",R);this.lastTotal=b;var C=_.length-(b-this.lastNeed);return _.copy(this.lastChar,0,C),_.toString("utf8",R,C)}function d(_){var R=_&&_.length?this.write(_):"";return this.lastNeed?R+"�":R}function f(_,R){if((_.length-R)%2===0){var b=_.toString("utf16le",R);if(b){var C=b.charCodeAt(b.length-1);if(C>=55296&&C<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=_[_.length-2],this.lastChar[1]=_[_.length-1],b.slice(0,-1)}return b}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=_[_.length-1],_.toString("utf16le",R,_.length-1)}function u(_){var R=_&&_.length?this.write(_):"";if(this.lastNeed){var b=this.lastTotal-this.lastNeed;return R+this.lastChar.toString("utf16le",0,b)}return R}function p(_,R){var b=(_.length-R)%3;return b===0?_.toString("base64",R):(this.lastNeed=3-b,this.lastTotal=3,b===1?this.lastChar[0]=_[_.length-1]:(this.lastChar[0]=_[_.length-2],this.lastChar[1]=_[_.length-1]),_.toString("base64",R,_.length-b))}function g(_){var R=_&&_.length?this.write(_):"";return this.lastNeed?R+this.lastChar.toString("base64",0,3-this.lastNeed):R}function y(_){return _.toString(this.encoding)}function w(_){return _&&_.length?this.write(_):""}return string_decoder}var from_1,hasRequiredFrom;function requireFrom(){if(hasRequiredFrom)return from_1;hasRequiredFrom=1;const n=requireBrowser$1(),{PromisePrototypeThen:e,SymbolAsyncIterator:t,SymbolIterator:r}=requirePrimordials(),{Buffer:i}=requireBuffer(),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=requireErrors().codes;function a(c,l,d){let f;if(typeof l=="string"||l instanceof i)return new c({objectMode:!0,...d,read(){this.push(l),this.push(null)}});let u;if(l&&l[t])u=!0,f=l[t]();else if(l&&l[r])u=!1,f=l[r]();else throw new s("iterable",["Iterable"],l);const p=new c({objectMode:!0,highWaterMark:1,...d});let g=!1;p._read=function(){g||(g=!0,w())},p._destroy=function(_,R){e(y(_),()=>n.nextTick(R,_),b=>n.nextTick(R,b||_))};async function y(_){const R=_!=null,b=typeof f.throw=="function";if(R&&b){const{value:C,done:P}=await f.throw(_);if(await C,P)return}if(typeof f.return=="function"){const{value:C}=await f.return();await C}}async function w(){for(;;){try{const{value:_,done:R}=u?await f.next():f.next();if(R)p.push(null);else{const b=_&&typeof _.then=="function"?await _:_;if(b===null)throw g=!1,new o;if(p.push(b))continue;g=!1}}catch(_){p.destroy(_)}break}}return p}return from_1=a,from_1}var readable,hasRequiredReadable;function requireReadable(){if(hasRequiredReadable)return readable;hasRequiredReadable=1;const n=requireBrowser$1(),{ArrayPrototypeIndexOf:e,NumberIsInteger:t,NumberIsNaN:r,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:a,Promise:c,SafeSet:l,SymbolAsyncDispose:d,SymbolAsyncIterator:f,Symbol:u}=requirePrimordials();readable=j,j.ReadableState=K;const{EventEmitter:p}=requireEvents(),{Stream:g,prependListener:y}=requireLegacy(),{Buffer:w}=requireBuffer(),{addAbortSignal:_}=requireAddAbortSignal(),R=requireEndOfStream();let b=requireUtil().debuglog("stream",v=>{b=v});const C=requireBuffer_list(),P=requireDestroy(),{getHighWaterMark:H,getDefaultHighWaterMark:M}=requireState(),{aggregateTwoErrors:re,codes:{ERR_INVALID_ARG_TYPE:he,ERR_METHOD_NOT_IMPLEMENTED:V,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:ie,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ce}=requireErrors(),{validateObject:Se}=requireValidators(),me=u("kPaused"),{StringDecoder:Ne}=requireString_decoder(),te=requireFrom();a(j.prototype,g.prototype),a(j,g);const ae=()=>{},{errorOrDestroy:x}=P,O=1,se=2,G=4,le=8,pe=16,Re=32,_e=64,B=128,Z=256,oe=512,ye=1024,ge=2048,D=4096,F=8192,k=16384,ee=32768,J=65536,X=1<<17,N=1<<18;function z(v){return{enumerable:!1,get(){return(this.state&v)!==0},set(A){A?this.state|=v:this.state&=~v}}}s(K.prototype,{objectMode:z(O),ended:z(se),endEmitted:z(G),reading:z(le),constructed:z(pe),sync:z(Re),needReadable:z(_e),emittedReadable:z(B),readableListening:z(Z),resumeScheduled:z(oe),errorEmitted:z(ye),emitClose:z(ge),autoDestroy:z(D),destroyed:z(F),closed:z(k),closeEmitted:z(ee),multiAwaitDrain:z(J),readingMore:z(X),dataEmitted:z(N)});function K(v,A,de){typeof de!="boolean"&&(de=A instanceof requireDuplex()),this.state=ge|D|pe|Re,v&&v.objectMode&&(this.state|=O),de&&v&&v.readableObjectMode&&(this.state|=O),this.highWaterMark=v?H(this,v,"readableHighWaterMark",de):M(!1),this.buffer=new C,this.length=0,this.pipes=[],this.flowing=null,this[me]=null,v&&v.emitClose===!1&&(this.state&=~ge),v&&v.autoDestroy===!1&&(this.state&=~D),this.errored=null,this.defaultEncoding=v&&v.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,v&&v.encoding&&(this.decoder=new Ne(v.encoding),this.encoding=v.encoding)}function j(v){if(!(this instanceof j))return new j(v);const A=this instanceof requireDuplex();this._readableState=new K(v,this,A),v&&(typeof v.read=="function"&&(this._read=v.read),typeof v.destroy=="function"&&(this._destroy=v.destroy),typeof v.construct=="function"&&(this._construct=v.construct),v.signal&&!A&&_(v.signal,this)),g.call(this,v),P.construct(this,()=>{this._readableState.needReadable&&$(this,this._readableState)})}j.prototype.destroy=P.destroy,j.prototype._undestroy=P.undestroy,j.prototype._destroy=function(v,A){A(v)},j.prototype[p.captureRejectionSymbol]=function(v){this.destroy(v)},j.prototype[d]=function(){let v;return this.destroyed||(v=this.readableEnded?null:new ce,this.destroy(v)),new c((A,de)=>R(this,ue=>ue&&ue!==v?de(ue):A(null)))},j.prototype.push=function(v,A){return we(this,v,A,!1)},j.prototype.unshift=function(v,A){return we(this,v,A,!0)};function we(v,A,de,ue){b("readableAddChunk",A);const ve=v._readableState;let Me;if((ve.state&O)===0&&(typeof A=="string"?(de=de||ve.defaultEncoding,ve.encoding!==de&&(ue&&ve.encoding?A=w.from(A,de).toString(ve.encoding):(A=w.from(A,de),de=""))):A instanceof w?de="":g._isUint8Array(A)?(A=g._uint8ArrayToBuffer(A),de=""):A!=null&&(Me=new he("chunk",["string","Buffer","Uint8Array"],A))),Me)x(v,Me);else if(A===null)ve.state&=~le,h(v,ve);else if((ve.state&O)!==0||A&&A.length>0)if(ue)if((ve.state&G)!==0)x(v,new U);else{if(ve.destroyed||ve.errored)return!1;Ee(v,ve,A,!0)}else if(ve.ended)x(v,new ie);else{if(ve.destroyed||ve.errored)return!1;ve.state&=~le,ve.decoder&&!de?(A=ve.decoder.write(A),ve.objectMode||A.length!==0?Ee(v,ve,A,!1):$(v,ve)):Ee(v,ve,A,!1)}else ue||(ve.state&=~le,$(v,ve));return!ve.ended&&(ve.length<ve.highWaterMark||ve.length===0)}function Ee(v,A,de,ue){A.flowing&&A.length===0&&!A.sync&&v.listenerCount("data")>0?((A.state&J)!==0?A.awaitDrainWriters.clear():A.awaitDrainWriters=null,A.dataEmitted=!0,v.emit("data",de)):(A.length+=A.objectMode?1:de.length,ue?A.buffer.unshift(de):A.buffer.push(de),(A.state&_e)!==0&&m(v)),$(v,A)}j.prototype.isPaused=function(){const v=this._readableState;return v[me]===!0||v.flowing===!1},j.prototype.setEncoding=function(v){const A=new Ne(v);this._readableState.decoder=A,this._readableState.encoding=this._readableState.decoder.encoding;const de=this._readableState.buffer;let ue="";for(const ve of de)ue+=A.write(ve);return de.clear(),ue!==""&&de.push(ue),this._readableState.length=ue.length,this};const be=1073741824;function Ie(v){if(v>be)throw new q("size","<= 1GiB",v);return v--,v|=v>>>1,v|=v>>>2,v|=v>>>4,v|=v>>>8,v|=v>>>16,v++,v}function S(v,A){return v<=0||A.length===0&&A.ended?0:(A.state&O)!==0?1:r(v)?A.flowing&&A.length?A.buffer.first().length:A.length:v<=A.length?v:A.ended?A.length:0}j.prototype.read=function(v){b("read",v),v===void 0?v=NaN:t(v)||(v=i(v,10));const A=this._readableState,de=v;if(v>A.highWaterMark&&(A.highWaterMark=Ie(v)),v!==0&&(A.state&=~B),v===0&&A.needReadable&&((A.highWaterMark!==0?A.length>=A.highWaterMark:A.length>0)||A.ended))return b("read: emitReadable",A.length,A.ended),A.length===0&&A.ended?Xe(this):m(this),null;if(v=S(v,A),v===0&&A.ended)return A.length===0&&Xe(this),null;let ue=(A.state&_e)!==0;if(b("need readable",ue),(A.length===0||A.length-v<A.highWaterMark)&&(ue=!0,b("length less than watermark",ue)),A.ended||A.reading||A.destroyed||A.errored||!A.constructed)ue=!1,b("reading, ended or constructing",ue);else if(ue){b("do read"),A.state|=le|Re,A.length===0&&(A.state|=_e);try{this._read(A.highWaterMark)}catch(Me){x(this,Me)}A.state&=~Re,A.reading||(v=S(de,A))}let ve;return v>0?ve=rt(v,A):ve=null,ve===null?(A.needReadable=A.length<=A.highWaterMark,v=0):(A.length-=v,A.multiAwaitDrain?A.awaitDrainWriters.clear():A.awaitDrainWriters=null),A.length===0&&(A.ended||(A.needReadable=!0),de!==v&&A.ended&&Xe(this)),ve!==null&&!A.errorEmitted&&!A.closeEmitted&&(A.dataEmitted=!0,this.emit("data",ve)),ve};function h(v,A){if(b("onEofChunk"),!A.ended){if(A.decoder){const de=A.decoder.end();de&&de.length&&(A.buffer.push(de),A.length+=A.objectMode?1:de.length)}A.ended=!0,A.sync?m(v):(A.needReadable=!1,A.emittedReadable=!0,I(v))}}function m(v){const A=v._readableState;b("emitReadable",A.needReadable,A.emittedReadable),A.needReadable=!1,A.emittedReadable||(b("emitReadable",A.flowing),A.emittedReadable=!0,n.nextTick(I,v))}function I(v){const A=v._readableState;b("emitReadable_",A.destroyed,A.length,A.ended),!A.destroyed&&!A.errored&&(A.length||A.ended)&&(v.emit("readable"),A.emittedReadable=!1),A.needReadable=!A.flowing&&!A.ended&&A.length<=A.highWaterMark,Le(v)}function $(v,A){!A.readingMore&&A.constructed&&(A.readingMore=!0,n.nextTick(L,v,A))}function L(v,A){for(;!A.reading&&!A.ended&&(A.length<A.highWaterMark||A.flowing&&A.length===0);){const de=A.length;if(b("maybeReadMore read 0"),v.read(0),de===A.length)break}A.readingMore=!1}j.prototype._read=function(v){throw new V("_read()")},j.prototype.pipe=function(v,A){const de=this,ue=this._readableState;ue.pipes.length===1&&(ue.multiAwaitDrain||(ue.multiAwaitDrain=!0,ue.awaitDrainWriters=new l(ue.awaitDrainWriters?[ue.awaitDrainWriters]:[]))),ue.pipes.push(v),b("pipe count=%d opts=%j",ue.pipes.length,A);const Me=(!A||A.end!==!1)&&v!==n.stdout&&v!==n.stderr?Gt:et;ue.endEmitted?n.nextTick(Me):de.once("end",Me),v.on("unpipe",Ge);function Ge(ke,tt){b("onunpipe"),ke===de&&tt&&tt.hasUnpiped===!1&&(tt.hasUnpiped=!0,Lt())}function Gt(){b("onend"),v.end()}let it,ze=!1;function Lt(){b("cleanup"),v.removeListener("close",_t),v.removeListener("finish",st),it&&v.removeListener("drain",it),v.removeListener("error",jt),v.removeListener("unpipe",Ge),de.removeListener("end",Gt),de.removeListener("end",et),de.removeListener("data",nt),ze=!0,it&&ue.awaitDrainWriters&&(!v._writableState||v._writableState.needDrain)&&it()}function Ht(){ze||(ue.pipes.length===1&&ue.pipes[0]===v?(b("false write response, pause",0),ue.awaitDrainWriters=v,ue.multiAwaitDrain=!1):ue.pipes.length>1&&ue.pipes.includes(v)&&(b("false write response, pause",ue.awaitDrainWriters.size),ue.awaitDrainWriters.add(v)),de.pause()),it||(it=W(de,v),v.on("drain",it))}de.on("data",nt);function nt(ke){b("ondata");const tt=v.write(ke);b("dest.write",tt),tt===!1&&Ht()}function jt(ke){if(b("onerror",ke),et(),v.removeListener("error",jt),v.listenerCount("error")===0){const tt=v._writableState||v._readableState;tt&&!tt.errorEmitted?x(v,ke):v.emit("error",ke)}}y(v,"error",jt);function _t(){v.removeListener("finish",st),et()}v.once("close",_t);function st(){b("onfinish"),v.removeListener("close",_t),et()}v.once("finish",st);function et(){b("unpipe"),de.unpipe(v)}return v.emit("pipe",de),v.writableNeedDrain===!0?Ht():ue.flowing||(b("pipe resume"),de.resume()),v};function W(v,A){return function(){const ue=v._readableState;ue.awaitDrainWriters===A?(b("pipeOnDrain",1),ue.awaitDrainWriters=null):ue.multiAwaitDrain&&(b("pipeOnDrain",ue.awaitDrainWriters.size),ue.awaitDrainWriters.delete(A)),(!ue.awaitDrainWriters||ue.awaitDrainWriters.size===0)&&v.listenerCount("data")&&v.resume()}}j.prototype.unpipe=function(v){const A=this._readableState,de={hasUnpiped:!1};if(A.pipes.length===0)return this;if(!v){const ve=A.pipes;A.pipes=[],this.pause();for(let Me=0;Me<ve.length;Me++)ve[Me].emit("unpipe",this,{hasUnpiped:!1});return this}const ue=e(A.pipes,v);return ue===-1?this:(A.pipes.splice(ue,1),A.pipes.length===0&&this.pause(),v.emit("unpipe",this,de),this)},j.prototype.on=function(v,A){const de=g.prototype.on.call(this,v,A),ue=this._readableState;return v==="data"?(ue.readableListening=this.listenerCount("readable")>0,ue.flowing!==!1&&this.resume()):v==="readable"&&!ue.endEmitted&&!ue.readableListening&&(ue.readableListening=ue.needReadable=!0,ue.flowing=!1,ue.emittedReadable=!1,b("on readable",ue.length,ue.reading),ue.length?m(this):ue.reading||n.nextTick(xe,this)),de},j.prototype.addListener=j.prototype.on,j.prototype.removeListener=function(v,A){const de=g.prototype.removeListener.call(this,v,A);return v==="readable"&&n.nextTick(Te,this),de},j.prototype.off=j.prototype.removeListener,j.prototype.removeAllListeners=function(v){const A=g.prototype.removeAllListeners.apply(this,arguments);return(v==="readable"||v===void 0)&&n.nextTick(Te,this),A};function Te(v){const A=v._readableState;A.readableListening=v.listenerCount("readable")>0,A.resumeScheduled&&A[me]===!1?A.flowing=!0:v.listenerCount("data")>0?v.resume():A.readableListening||(A.flowing=null)}function xe(v){b("readable nexttick read 0"),v.read(0)}j.prototype.resume=function(){const v=this._readableState;return v.flowing||(b("resume"),v.flowing=!v.readableListening,Fe(this,v)),v[me]=!1,this};function Fe(v,A){A.resumeScheduled||(A.resumeScheduled=!0,n.nextTick(je,v,A))}function je(v,A){b("resume",A.reading),A.reading||v.read(0),A.resumeScheduled=!1,v.emit("resume"),Le(v),A.flowing&&!A.reading&&v.read(0)}j.prototype.pause=function(){return b("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(b("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[me]=!0,this};function Le(v){const A=v._readableState;for(b("flow",A.flowing);A.flowing&&v.read()!==null;);}j.prototype.wrap=function(v){let A=!1;v.on("data",ue=>{!this.push(ue)&&v.pause&&(A=!0,v.pause())}),v.on("end",()=>{this.push(null)}),v.on("error",ue=>{x(this,ue)}),v.on("close",()=>{this.destroy()}),v.on("destroy",()=>{this.destroy()}),this._read=()=>{A&&v.resume&&(A=!1,v.resume())};const de=o(v);for(let ue=1;ue<de.length;ue++){const ve=de[ue];this[ve]===void 0&&typeof v[ve]=="function"&&(this[ve]=v[ve].bind(v))}return this},j.prototype[f]=function(){return Ft(this)},j.prototype.iterator=function(v){return v!==void 0&&Se(v,"options"),Ft(this,v)};function Ft(v,A){typeof v.read!="function"&&(v=j.wrap(v,{objectMode:!0}));const de=Qt(v,A);return de.stream=v,de}async function*Qt(v,A){let de=ae;function ue(Ge){this===v?(de(),de=ae):de=Ge}v.on("readable",ue);let ve;const Me=R(v,{writable:!1},Ge=>{ve=Ge?re(ve,Ge):null,de(),de=ae});try{for(;;){const Ge=v.destroyed?null:v.read();if(Ge!==null)yield Ge;else{if(ve)throw ve;if(ve===null)return;await new c(ue)}}}catch(Ge){throw ve=re(ve,Ge),ve}finally{(ve||A?.destroyOnReturn!==!1)&&(ve===void 0||v._readableState.autoDestroy)?P.destroyer(v,null):(v.off("readable",ue),Me())}}s(j.prototype,{readable:{__proto__:null,get(){const v=this._readableState;return!!v&&v.readable!==!1&&!v.destroyed&&!v.errorEmitted&&!v.endEmitted},set(v){this._readableState&&(this._readableState.readable=!!v)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(v){this._readableState&&(this._readableState.flowing=v)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(v){this._readableState&&(this._readableState.destroyed=v)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(K.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[me]!==!1},set(v){this[me]=!!v}}}),j._fromList=rt;function rt(v,A){if(A.length===0)return null;let de;return A.objectMode?de=A.buffer.shift():!v||v>=A.length?(A.decoder?de=A.buffer.join(""):A.buffer.length===1?de=A.buffer.first():de=A.buffer.concat(A.length),A.buffer.clear()):de=A.buffer.consume(v,A.decoder),de}function Xe(v){const A=v._readableState;b("endReadable",A.endEmitted),A.endEmitted||(A.ended=!0,n.nextTick(bt,A,v))}function bt(v,A){if(b("endReadableNT",v.endEmitted,v.length),!v.errored&&!v.closeEmitted&&!v.endEmitted&&v.length===0){if(v.endEmitted=!0,A.emit("end"),A.writable&&A.allowHalfOpen===!1)n.nextTick(wt,A);else if(v.autoDestroy){const de=A._writableState;(!de||de.autoDestroy&&(de.finished||de.writable===!1))&&A.destroy()}}}function wt(v){v.writable&&!v.writableEnded&&!v.destroyed&&v.end()}j.from=function(v,A){return te(j,v,A)};let ut;function Ye(){return ut===void 0&&(ut={}),ut}return j.fromWeb=function(v,A){return Ye().newStreamReadableFromReadableStream(v,A)},j.toWeb=function(v,A){return Ye().newReadableStreamFromStreamReadable(v,A)},j.wrap=function(v,A){var de,ue;return new j({objectMode:(de=(ue=v.readableObjectMode)!==null&&ue!==void 0?ue:v.objectMode)!==null&&de!==void 0?de:!0,...A,destroy(ve,Me){P.destroyer(v,ve),Me(ve)}}).wrap(v)},readable}var writable,hasRequiredWritable;function requireWritable(){if(hasRequiredWritable)return writable;hasRequiredWritable=1;const n=requireBrowser$1(),{ArrayPrototypeSlice:e,Error:t,FunctionPrototypeSymbolHasInstance:r,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:a,Symbol:c,SymbolHasInstance:l}=requirePrimordials();writable=Se,Se.WritableState=U;const{EventEmitter:d}=requireEvents(),f=requireLegacy().Stream,{Buffer:u}=requireBuffer(),p=requireDestroy(),{addAbortSignal:g}=requireAddAbortSignal(),{getHighWaterMark:y,getDefaultHighWaterMark:w}=requireState(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:R,ERR_MULTIPLE_CALLBACK:b,ERR_STREAM_CANNOT_PIPE:C,ERR_STREAM_DESTROYED:P,ERR_STREAM_ALREADY_FINISHED:H,ERR_STREAM_NULL_VALUES:M,ERR_STREAM_WRITE_AFTER_END:re,ERR_UNKNOWN_ENCODING:he}=requireErrors().codes,{errorOrDestroy:V}=p;o(Se.prototype,f.prototype),o(Se,f);function q(){}const ie=c("kOnFinished");function U(D,F,k){typeof k!="boolean"&&(k=F instanceof requireDuplex()),this.objectMode=!!(D&&D.objectMode),k&&(this.objectMode=this.objectMode||!!(D&&D.writableObjectMode)),this.highWaterMark=D?y(this,D,"writableHighWaterMark",k):w(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const ee=!!(D&&D.decodeStrings===!1);this.decodeStrings=!ee,this.defaultEncoding=D&&D.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=x.bind(void 0,F),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ce(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!D||D.emitClose!==!1,this.autoDestroy=!D||D.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[ie]=[]}function ce(D){D.buffered=[],D.bufferedIndex=0,D.allBuffers=!0,D.allNoop=!0}U.prototype.getBuffer=function(){return e(this.buffered,this.bufferedIndex)},i(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Se(D){const F=this instanceof requireDuplex();if(!F&&!r(Se,this))return new Se(D);this._writableState=new U(D,this,F),D&&(typeof D.write=="function"&&(this._write=D.write),typeof D.writev=="function"&&(this._writev=D.writev),typeof D.destroy=="function"&&(this._destroy=D.destroy),typeof D.final=="function"&&(this._final=D.final),typeof D.construct=="function"&&(this._construct=D.construct),D.signal&&g(D.signal,this)),f.call(this,D),p.construct(this,()=>{const k=this._writableState;k.writing||le(this,k),B(this,k)})}i(Se,l,{__proto__:null,value:function(D){return r(this,D)?!0:this!==Se?!1:D&&D._writableState instanceof U}}),Se.prototype.pipe=function(){V(this,new C)};function me(D,F,k,ee){const J=D._writableState;if(typeof k=="function")ee=k,k=J.defaultEncoding;else{if(!k)k=J.defaultEncoding;else if(k!=="buffer"&&!u.isEncoding(k))throw new he(k);typeof ee!="function"&&(ee=q)}if(F===null)throw new M;if(!J.objectMode)if(typeof F=="string")J.decodeStrings!==!1&&(F=u.from(F,k),k="buffer");else if(F instanceof u)k="buffer";else if(f._isUint8Array(F))F=f._uint8ArrayToBuffer(F),k="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],F);let X;return J.ending?X=new re:J.destroyed&&(X=new P("write")),X?(n.nextTick(ee,X),V(D,X,!0),X):(J.pendingcb++,Ne(D,J,F,k,ee))}Se.prototype.write=function(D,F,k){return me(this,D,F,k)===!0},Se.prototype.cork=function(){this._writableState.corked++},Se.prototype.uncork=function(){const D=this._writableState;D.corked&&(D.corked--,D.writing||le(this,D))},Se.prototype.setDefaultEncoding=function(F){if(typeof F=="string"&&(F=a(F)),!u.isEncoding(F))throw new he(F);return this._writableState.defaultEncoding=F,this};function Ne(D,F,k,ee,J){const X=F.objectMode?1:k.length;F.length+=X;const N=F.length<F.highWaterMark;return N||(F.needDrain=!0),F.writing||F.corked||F.errored||!F.constructed?(F.buffered.push({chunk:k,encoding:ee,callback:J}),F.allBuffers&&ee!=="buffer"&&(F.allBuffers=!1),F.allNoop&&J!==q&&(F.allNoop=!1)):(F.writelen=X,F.writecb=J,F.writing=!0,F.sync=!0,D._write(k,ee,F.onwrite),F.sync=!1),N&&!F.errored&&!F.destroyed}function te(D,F,k,ee,J,X,N){F.writelen=ee,F.writecb=N,F.writing=!0,F.sync=!0,F.destroyed?F.onwrite(new P("write")):k?D._writev(J,F.onwrite):D._write(J,X,F.onwrite),F.sync=!1}function ae(D,F,k,ee){--F.pendingcb,ee(k),G(F),V(D,k)}function x(D,F){const k=D._writableState,ee=k.sync,J=k.writecb;if(typeof J!="function"){V(D,new b);return}k.writing=!1,k.writecb=null,k.length-=k.writelen,k.writelen=0,F?(F.stack,k.errored||(k.errored=F),D._readableState&&!D._readableState.errored&&(D._readableState.errored=F),ee?n.nextTick(ae,D,k,F,J):ae(D,k,F,J)):(k.buffered.length>k.bufferedIndex&&le(D,k),ee?k.afterWriteTickInfo!==null&&k.afterWriteTickInfo.cb===J?k.afterWriteTickInfo.count++:(k.afterWriteTickInfo={count:1,cb:J,stream:D,state:k},n.nextTick(O,k.afterWriteTickInfo)):se(D,k,1,J))}function O({stream:D,state:F,count:k,cb:ee}){return F.afterWriteTickInfo=null,se(D,F,k,ee)}function se(D,F,k,ee){for(!F.ending&&!D.destroyed&&F.length===0&&F.needDrain&&(F.needDrain=!1,D.emit("drain"));k-- >0;)F.pendingcb--,ee();F.destroyed&&G(F),B(D,F)}function G(D){if(D.writing)return;for(let J=D.bufferedIndex;J<D.buffered.length;++J){var F;const{chunk:X,callback:N}=D.buffered[J],z=D.objectMode?1:X.length;D.length-=z,N((F=D.errored)!==null&&F!==void 0?F:new P("write"))}const k=D[ie].splice(0);for(let J=0;J<k.length;J++){var ee;k[J]((ee=D.errored)!==null&&ee!==void 0?ee:new P("end"))}ce(D)}function le(D,F){if(F.corked||F.bufferProcessing||F.destroyed||!F.constructed)return;const{buffered:k,bufferedIndex:ee,objectMode:J}=F,X=k.length-ee;if(!X)return;let N=ee;if(F.bufferProcessing=!0,X>1&&D._writev){F.pendingcb-=X-1;const z=F.allNoop?q:j=>{for(let we=N;we<k.length;++we)k[we].callback(j)},K=F.allNoop&&N===0?k:e(k,N);K.allBuffers=F.allBuffers,te(D,F,!0,F.length,K,"",z),ce(F)}else{do{const{chunk:z,encoding:K,callback:j}=k[N];k[N++]=null;const we=J?1:z.length;te(D,F,!1,we,z,K,j)}while(N<k.length&&!F.writing);N===k.length?ce(F):N>256?(k.splice(0,N),F.bufferedIndex=0):F.bufferedIndex=N}F.bufferProcessing=!1}Se.prototype._write=function(D,F,k){if(this._writev)this._writev([{chunk:D,encoding:F}],k);else throw new R("_write()")},Se.prototype._writev=null,Se.prototype.end=function(D,F,k){const ee=this._writableState;typeof D=="function"?(k=D,D=null,F=null):typeof F=="function"&&(k=F,F=null);let J;if(D!=null){const X=me(this,D,F);X instanceof t&&(J=X)}return ee.corked&&(ee.corked=1,this.uncork()),J||(!ee.errored&&!ee.ending?(ee.ending=!0,B(this,ee,!0),ee.ended=!0):ee.finished?J=new H("end"):ee.destroyed&&(J=new P("end"))),typeof k=="function"&&(J||ee.finished?n.nextTick(k,J):ee[ie].push(k)),this};function pe(D){return D.ending&&!D.destroyed&&D.constructed&&D.length===0&&!D.errored&&D.buffered.length===0&&!D.finished&&!D.writing&&!D.errorEmitted&&!D.closeEmitted}function Re(D,F){let k=!1;function ee(J){if(k){V(D,J??b());return}if(k=!0,F.pendingcb--,J){const X=F[ie].splice(0);for(let N=0;N<X.length;N++)X[N](J);V(D,J,F.sync)}else pe(F)&&(F.prefinished=!0,D.emit("prefinish"),F.pendingcb++,n.nextTick(Z,D,F))}F.sync=!0,F.pendingcb++;try{D._final(ee)}catch(J){ee(J)}F.sync=!1}function _e(D,F){!F.prefinished&&!F.finalCalled&&(typeof D._final=="function"&&!F.destroyed?(F.finalCalled=!0,Re(D,F)):(F.prefinished=!0,D.emit("prefinish")))}function B(D,F,k){pe(F)&&(_e(D,F),F.pendingcb===0&&(k?(F.pendingcb++,n.nextTick((ee,J)=>{pe(J)?Z(ee,J):J.pendingcb--},D,F)):pe(F)&&(F.pendingcb++,Z(D,F))))}function Z(D,F){F.pendingcb--,F.finished=!0;const k=F[ie].splice(0);for(let ee=0;ee<k.length;ee++)k[ee]();if(D.emit("finish"),F.autoDestroy){const ee=D._readableState;(!ee||ee.autoDestroy&&(ee.endEmitted||ee.readable===!1))&&D.destroy()}}s(Se.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(D){this._writableState&&(this._writableState.destroyed=D)}},writable:{__proto__:null,get(){const D=this._writableState;return!!D&&D.writable!==!1&&!D.destroyed&&!D.errored&&!D.ending&&!D.ended},set(D){this._writableState&&(this._writableState.writable=!!D)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){const D=this._writableState;return D?!D.destroyed&&!D.ending&&D.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});const oe=p.destroy;Se.prototype.destroy=function(D,F){const k=this._writableState;return!k.destroyed&&(k.bufferedIndex<k.buffered.length||k[ie].length)&&n.nextTick(G,k),oe.call(this,D,F),this},Se.prototype._undestroy=p.undestroy,Se.prototype._destroy=function(D,F){F(D)},Se.prototype[d.captureRejectionSymbol]=function(D){this.destroy(D)};let ye;function ge(){return ye===void 0&&(ye={}),ye}return Se.fromWeb=function(D,F){return ge().newStreamWritableFromWritableStream(D,F)},Se.toWeb=function(D){return ge().newWritableStreamFromStreamWritable(D)},writable}var duplexify,hasRequiredDuplexify;function requireDuplexify(){if(hasRequiredDuplexify)return duplexify;hasRequiredDuplexify=1;const n=requireBrowser$1(),e=requireBuffer(),{isReadable:t,isWritable:r,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:a,isDuplexNodeStream:c,isReadableStream:l,isWritableStream:d}=requireUtils(),f=requireEndOfStream(),{AbortError:u,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g}}=requireErrors(),{destroyer:y}=requireDestroy(),w=requireDuplex(),_=requireReadable(),R=requireWritable(),{createDeferredPromise:b}=requireUtil(),C=requireFrom(),P=globalThis.Blob||e.Blob,H=typeof P<"u"?function(U){return U instanceof P}:function(U){return!1},M=globalThis.AbortController||requireBrowser$2().AbortController,{FunctionPrototypeCall:re}=requirePrimordials();class he extends w{constructor(U){super(U),U?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),U?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}duplexify=function ie(U,ce){if(c(U))return U;if(o(U))return q({readable:U});if(a(U))return q({writable:U});if(s(U))return q({writable:!1,readable:!1});if(l(U))return q({readable:_.fromWeb(U)});if(d(U))return q({writable:R.fromWeb(U)});if(typeof U=="function"){const{value:me,write:Ne,final:te,destroy:ae}=V(U);if(i(me))return C(he,me,{objectMode:!0,write:Ne,final:te,destroy:ae});const x=me?.then;if(typeof x=="function"){let O;const se=re(x,me,G=>{if(G!=null)throw new g("nully","body",G)},G=>{y(O,G)});return O=new he({objectMode:!0,readable:!1,write:Ne,final(G){te(async()=>{try{await se,n.nextTick(G,null)}catch(le){n.nextTick(G,le)}})},destroy:ae})}throw new g("Iterable, AsyncIterable or AsyncFunction",ce,me)}if(H(U))return ie(U.arrayBuffer());if(i(U))return C(he,U,{objectMode:!0,writable:!1});if(l(U?.readable)&&d(U?.writable))return he.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){const me=U!=null&&U.readable?o(U?.readable)?U?.readable:ie(U.readable):void 0,Ne=U!=null&&U.writable?a(U?.writable)?U?.writable:ie(U.writable):void 0;return q({readable:me,writable:Ne})}const Se=U?.then;if(typeof Se=="function"){let me;return re(Se,U,Ne=>{Ne!=null&&me.push(Ne),me.push(null)},Ne=>{y(me,Ne)}),me=new he({objectMode:!0,writable:!1,read(){}})}throw new p(ce,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function V(ie){let{promise:U,resolve:ce}=b();const Se=new M,me=Se.signal;return{value:ie((async function*(){for(;;){const te=U;U=null;const{chunk:ae,done:x,cb:O}=await te;if(n.nextTick(O),x)return;if(me.aborted)throw new u(void 0,{cause:me.reason});({promise:U,resolve:ce}=b()),yield ae}})(),{signal:me}),write(te,ae,x){const O=ce;ce=null,O({chunk:te,done:!1,cb:x})},final(te){const ae=ce;ce=null,ae({done:!0,cb:te})},destroy(te,ae){Se.abort(),ae(te)}}}function q(ie){const U=ie.readable&&typeof ie.readable.read!="function"?_.wrap(ie.readable):ie.readable,ce=ie.writable;let Se=!!t(U),me=!!r(ce),Ne,te,ae,x,O;function se(G){const le=x;x=null,le?le(G):G&&O.destroy(G)}return O=new he({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ce!=null&&ce.writableObjectMode),readable:Se,writable:me}),me&&(f(ce,G=>{me=!1,G&&y(U,G),se(G)}),O._write=function(G,le,pe){ce.write(G,le)?pe():Ne=pe},O._final=function(G){ce.end(),te=G},ce.on("drain",function(){if(Ne){const G=Ne;Ne=null,G()}}),ce.on("finish",function(){if(te){const G=te;te=null,G()}})),Se&&(f(U,G=>{Se=!1,G&&y(U,G),se(G)}),U.on("readable",function(){if(ae){const G=ae;ae=null,G()}}),U.on("end",function(){O.push(null)}),O._read=function(){for(;;){const G=U.read();if(G===null){ae=O._read;return}if(!O.push(G))return}}),O._destroy=function(G,le){!G&&x!==null&&(G=new u),ae=null,Ne=null,te=null,x===null?le(G):(x=le,y(ce,G),y(U,G))},O}return duplexify}var duplex,hasRequiredDuplex;function requireDuplex(){if(hasRequiredDuplex)return duplex;hasRequiredDuplex=1;const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:e,ObjectKeys:t,ObjectSetPrototypeOf:r}=requirePrimordials();duplex=o;const i=requireReadable(),s=requireWritable();r(o.prototype,i.prototype),r(o,i);{const d=t(s.prototype);for(let f=0;f<d.length;f++){const u=d[f];o.prototype[u]||(o.prototype[u]=s.prototype[u])}}function o(d){if(!(this instanceof o))return new o(d);i.call(this,d),s.call(this,d),d?(this.allowHalfOpen=d.allowHalfOpen!==!1,d.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),d.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}n(o.prototype,{writable:{__proto__:null,...e(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...e(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...e(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...e(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...e(s.prototype,"writableLength")},writableFinished:{__proto__:null,...e(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...e(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...e(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...e(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(d){this._readableState&&this._writableState&&(this._readableState.destroyed=d,this._writableState.destroyed=d)}}});let a;function c(){return a===void 0&&(a={}),a}o.fromWeb=function(d,f){return c().newStreamDuplexFromReadableWritablePair(d,f)},o.toWeb=function(d){return c().newReadableWritablePairFromDuplex(d)};let l;return o.from=function(d){return l||(l=requireDuplexify()),l(d,"body")},duplex}var transform$1,hasRequiredTransform;function requireTransform(){if(hasRequiredTransform)return transform$1;hasRequiredTransform=1;const{ObjectSetPrototypeOf:n,Symbol:e}=requirePrimordials();transform$1=o;const{ERR_METHOD_NOT_IMPLEMENTED:t}=requireErrors().codes,r=requireDuplex(),{getHighWaterMark:i}=requireState();n(o.prototype,r.prototype),n(o,r);const s=e("kCallback");function o(l){if(!(this instanceof o))return new o(l);const d=l?i(this,l,"readableHighWaterMark",!0):null;d===0&&(l={...l,highWaterMark:null,readableHighWaterMark:d,writableHighWaterMark:l.writableHighWaterMark||0}),r.call(this,l),this._readableState.sync=!1,this[s]=null,l&&(typeof l.transform=="function"&&(this._transform=l.transform),typeof l.flush=="function"&&(this._flush=l.flush)),this.on("prefinish",c)}function a(l){typeof this._flush=="function"&&!this.destroyed?this._flush((d,f)=>{if(d){l?l(d):this.destroy(d);return}f!=null&&this.push(f),this.push(null),l&&l()}):(this.push(null),l&&l())}function c(){this._final!==a&&a.call(this)}return o.prototype._final=a,o.prototype._transform=function(l,d,f){throw new t("_transform()")},o.prototype._write=function(l,d,f){const u=this._readableState,p=this._writableState,g=u.length;this._transform(l,d,(y,w)=>{if(y){f(y);return}w!=null&&this.push(w),p.ended||g===u.length||u.length<u.highWaterMark?f():this[s]=f})},o.prototype._read=function(){if(this[s]){const l=this[s];this[s]=null,l()}},transform$1}var passthrough,hasRequiredPassthrough;function requirePassthrough(){if(hasRequiredPassthrough)return passthrough;hasRequiredPassthrough=1;const{ObjectSetPrototypeOf:n}=requirePrimordials();passthrough=t;const e=requireTransform();n(t.prototype,e.prototype),n(t,e);function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return t.prototype._transform=function(r,i,s){s(null,r)},passthrough}var pipeline_1,hasRequiredPipeline;function requirePipeline(){if(hasRequiredPipeline)return pipeline_1;hasRequiredPipeline=1;const n=requireBrowser$1(),{ArrayIsArray:e,Promise:t,SymbolAsyncIterator:r,SymbolDispose:i}=requirePrimordials(),s=requireEndOfStream(),{once:o}=requireUtil(),a=requireDestroy(),c=requireDuplex(),{aggregateTwoErrors:l,codes:{ERR_INVALID_ARG_TYPE:d,ERR_INVALID_RETURN_VALUE:f,ERR_MISSING_ARGS:u,ERR_STREAM_DESTROYED:p,ERR_STREAM_PREMATURE_CLOSE:g},AbortError:y}=requireErrors(),{validateFunction:w,validateAbortSignal:_}=requireValidators(),{isIterable:R,isReadable:b,isReadableNodeStream:C,isNodeStream:P,isTransformStream:H,isWebStream:M,isReadableStream:re,isReadableFinished:he}=requireUtils(),V=globalThis.AbortController||requireBrowser$2().AbortController;let q,ie,U;function ce(G,le,pe){let Re=!1;G.on("close",()=>{Re=!0});const _e=s(G,{readable:le,writable:pe},B=>{Re=!B});return{destroy:B=>{Re||(Re=!0,a.destroyer(G,B||new p("pipe")))},cleanup:_e}}function Se(G){return w(G[G.length-1],"streams[stream.length - 1]"),G.pop()}function me(G){if(R(G))return G;if(C(G))return Ne(G);throw new d("val",["Readable","Iterable","AsyncIterable"],G)}async function*Ne(G){ie||(ie=requireReadable()),yield*ie.prototype[r].call(G)}async function te(G,le,pe,{end:Re}){let _e,B=null;const Z=ge=>{if(ge&&(_e=ge),B){const D=B;B=null,D()}},oe=()=>new t((ge,D)=>{_e?D(_e):B=()=>{_e?D(_e):ge()}});le.on("drain",Z);const ye=s(le,{readable:!1},Z);try{le.writableNeedDrain&&await oe();for await(const ge of G)le.write(ge)||await oe();Re&&(le.end(),await oe()),pe()}catch(ge){pe(_e!==ge?l(_e,ge):ge)}finally{ye(),le.off("drain",Z)}}async function ae(G,le,pe,{end:Re}){H(le)&&(le=le.writable);const _e=le.getWriter();try{for await(const B of G)await _e.ready,_e.write(B).catch(()=>{});await _e.ready,Re&&await _e.close(),pe()}catch(B){try{await _e.abort(B),pe(B)}catch(Z){pe(Z)}}}function x(...G){return O(G,o(Se(G)))}function O(G,le,pe){if(G.length===1&&e(G[0])&&(G=G[0]),G.length<2)throw new u("streams");const Re=new V,_e=Re.signal,B=pe?.signal,Z=[];_(B,"options.signal");function oe(){J(new y)}U=U||requireUtil().addAbortListener;let ye;B&&(ye=U(B,oe));let ge,D;const F=[];let k=0;function ee(K){J(K,--k===0)}function J(K,j){var we;if(K&&(!ge||ge.code==="ERR_STREAM_PREMATURE_CLOSE")&&(ge=K),!(!ge&&!j)){for(;F.length;)F.shift()(ge);(we=ye)===null||we===void 0||we[i](),Re.abort(),j&&(ge||Z.forEach(Ee=>Ee()),n.nextTick(le,ge,D))}}let X;for(let K=0;K<G.length;K++){const j=G[K],we=K<G.length-1,Ee=K>0,be=we||pe?.end!==!1,Ie=K===G.length-1;if(P(j)){let S=function(h){h&&h.name!=="AbortError"&&h.code!=="ERR_STREAM_PREMATURE_CLOSE"&&ee(h)};if(be){const{destroy:h,cleanup:m}=ce(j,we,Ee);F.push(h),b(j)&&Ie&&Z.push(m)}j.on("error",S),b(j)&&Ie&&Z.push(()=>{j.removeListener("error",S)})}if(K===0)if(typeof j=="function"){if(X=j({signal:_e}),!R(X))throw new f("Iterable, AsyncIterable or Stream","source",X)}else R(j)||C(j)||H(j)?X=j:X=c.from(j);else if(typeof j=="function"){if(H(X)){var N;X=me((N=X)===null||N===void 0?void 0:N.readable)}else X=me(X);if(X=j(X,{signal:_e}),we){if(!R(X,!0))throw new f("AsyncIterable",`transform[${K-1}]`,X)}else{var z;q||(q=requirePassthrough());const S=new q({objectMode:!0}),h=(z=X)===null||z===void 0?void 0:z.then;if(typeof h=="function")k++,h.call(X,$=>{D=$,$!=null&&S.write($),be&&S.end(),n.nextTick(ee)},$=>{S.destroy($),n.nextTick(ee,$)});else if(R(X,!0))k++,te(X,S,ee,{end:be});else if(re(X)||H(X)){const $=X.readable||X;k++,te($,S,ee,{end:be})}else throw new f("AsyncIterable or Promise","destination",X);X=S;const{destroy:m,cleanup:I}=ce(X,!1,!0);F.push(m),Ie&&Z.push(I)}}else if(P(j)){if(C(X)){k+=2;const S=se(X,j,ee,{end:be});b(j)&&Ie&&Z.push(S)}else if(H(X)||re(X)){const S=X.readable||X;k++,te(S,j,ee,{end:be})}else if(R(X))k++,te(X,j,ee,{end:be});else throw new d("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],X);X=j}else if(M(j)){if(C(X))k++,ae(me(X),j,ee,{end:be});else if(re(X)||R(X))k++,ae(X,j,ee,{end:be});else if(H(X))k++,ae(X.readable,j,ee,{end:be});else throw new d("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],X);X=j}else X=c.from(j)}return(_e!=null&&_e.aborted||B!=null&&B.aborted)&&n.nextTick(oe),X}function se(G,le,pe,{end:Re}){let _e=!1;if(le.on("close",()=>{_e||pe(new g)}),G.pipe(le,{end:!1}),Re){let B=function(){_e=!0,le.end()};he(G)?n.nextTick(B):G.once("end",B)}else pe();return s(G,{readable:!0,writable:!1},B=>{const Z=G._readableState;B&&B.code==="ERR_STREAM_PREMATURE_CLOSE"&&Z&&Z.ended&&!Z.errored&&!Z.errorEmitted?G.once("end",pe).once("error",pe):pe(B)}),s(le,{readable:!1,writable:!0},pe)}return pipeline_1={pipelineImpl:O,pipeline:x},pipeline_1}var compose,hasRequiredCompose;function requireCompose(){if(hasRequiredCompose)return compose;hasRequiredCompose=1;const{pipeline:n}=requirePipeline(),e=requireDuplex(),{destroyer:t}=requireDestroy(),{isNodeStream:r,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:a,isWritableStream:c,isReadableStream:l}=requireUtils(),{AbortError:d,codes:{ERR_INVALID_ARG_VALUE:f,ERR_MISSING_ARGS:u}}=requireErrors(),p=requireEndOfStream();return compose=function(...y){if(y.length===0)throw new u("streams");if(y.length===1)return e.from(y[0]);const w=[...y];if(typeof y[0]=="function"&&(y[0]=e.from(y[0])),typeof y[y.length-1]=="function"){const q=y.length-1;y[q]=e.from(y[q])}for(let q=0;q<y.length;++q)if(!(!r(y[q])&&!o(y[q]))){if(q<y.length-1&&!(i(y[q])||l(y[q])||a(y[q])))throw new f(`streams[${q}]`,w[q],"must be readable");if(q>0&&!(s(y[q])||c(y[q])||a(y[q])))throw new f(`streams[${q}]`,w[q],"must be writable")}let _,R,b,C,P;function H(q){const ie=C;C=null,ie?ie(q):q?P.destroy(q):!V&&!he&&P.destroy()}const M=y[0],re=n(y,H),he=!!(s(M)||c(M)||a(M)),V=!!(i(re)||l(re)||a(re));if(P=new e({writableObjectMode:!!(M!=null&&M.writableObjectMode),readableObjectMode:!!(re!=null&&re.readableObjectMode),writable:he,readable:V}),he){if(r(M))P._write=function(ie,U,ce){M.write(ie,U)?ce():_=ce},P._final=function(ie){M.end(),R=ie},M.on("drain",function(){if(_){const ie=_;_=null,ie()}});else if(o(M)){const U=(a(M)?M.writable:M).getWriter();P._write=async function(ce,Se,me){try{await U.ready,U.write(ce).catch(()=>{}),me()}catch(Ne){me(Ne)}},P._final=async function(ce){try{await U.ready,U.close().catch(()=>{}),R=ce}catch(Se){ce(Se)}}}const q=a(re)?re.readable:re;p(q,()=>{if(R){const ie=R;R=null,ie()}})}if(V){if(r(re))re.on("readable",function(){if(b){const q=b;b=null,q()}}),re.on("end",function(){P.push(null)}),P._read=function(){for(;;){const q=re.read();if(q===null){b=P._read;return}if(!P.push(q))return}};else if(o(re)){const ie=(a(re)?re.readable:re).getReader();P._read=async function(){for(;;)try{const{value:U,done:ce}=await ie.read();if(!P.push(U))return;if(ce){P.push(null);return}}catch{return}}}}return P._destroy=function(q,ie){!q&&C!==null&&(q=new d),b=null,_=null,R=null,C===null?ie(q):(C=ie,r(re)&&t(re,q))},P},compose}var hasRequiredOperators;function requireOperators(){if(hasRequiredOperators)return operators;hasRequiredOperators=1;const n=globalThis.AbortController||requireBrowser$2().AbortController,{codes:{ERR_INVALID_ARG_VALUE:e,ERR_INVALID_ARG_TYPE:t,ERR_MISSING_ARGS:r,ERR_OUT_OF_RANGE:i},AbortError:s}=requireErrors(),{validateAbortSignal:o,validateInteger:a,validateObject:c}=requireValidators(),l=requirePrimordials().Symbol("kWeak"),d=requirePrimordials().Symbol("kResistStopPropagation"),{finished:f}=requireEndOfStream(),u=requireCompose(),{addAbortSignalNoValidate:p}=requireAddAbortSignal(),{isWritable:g,isNodeStream:y}=requireUtils(),{deprecate:w}=requireUtil(),{ArrayPrototypePush:_,Boolean:R,MathFloor:b,Number:C,NumberIsNaN:P,Promise:H,PromiseReject:M,PromiseResolve:re,PromisePrototypeThen:he,Symbol:V}=requirePrimordials(),q=V("kEmpty"),ie=V("kEof");function U(B,Z){if(Z!=null&&c(Z,"options"),Z?.signal!=null&&o(Z.signal,"options.signal"),y(B)&&!g(B))throw new e("stream",B,"must be writable");const oe=u(this,B);return Z!=null&&Z.signal&&p(Z.signal,oe),oe}function ce(B,Z){if(typeof B!="function")throw new t("fn",["Function","AsyncFunction"],B);Z!=null&&c(Z,"options"),Z?.signal!=null&&o(Z.signal,"options.signal");let oe=1;Z?.concurrency!=null&&(oe=b(Z.concurrency));let ye=oe-1;return Z?.highWaterMark!=null&&(ye=b(Z.highWaterMark)),a(oe,"options.concurrency",1),a(ye,"options.highWaterMark",0),ye+=oe,(async function*(){const D=requireUtil().AbortSignalAny([Z?.signal].filter(R)),F=this,k=[],ee={signal:D};let J,X,N=!1,z=0;function K(){N=!0,j()}function j(){z-=1,we()}function we(){X&&!N&&z<oe&&k.length<ye&&(X(),X=null)}async function Ee(){try{for await(let be of F){if(N)return;if(D.aborted)throw new s;try{if(be=B(be,ee),be===q)continue;be=re(be)}catch(Ie){be=M(Ie)}z+=1,he(be,j,K),k.push(be),J&&(J(),J=null),!N&&(k.length>=ye||z>=oe)&&await new H(Ie=>{X=Ie})}k.push(ie)}catch(be){const Ie=M(be);he(Ie,j,K),k.push(Ie)}finally{N=!0,J&&(J(),J=null)}}Ee();try{for(;;){for(;k.length>0;){const be=await k[0];if(be===ie)return;if(D.aborted)throw new s;be!==q&&(yield be),k.shift(),we()}await new H(be=>{J=be})}}finally{N=!0,X&&(X(),X=null)}}).call(this)}function Se(B=void 0){return B!=null&&c(B,"options"),B?.signal!=null&&o(B.signal,"options.signal"),(async function*(){let oe=0;for await(const ge of this){var ye;if(B!=null&&(ye=B.signal)!==null&&ye!==void 0&&ye.aborted)throw new s({cause:B.signal.reason});yield[oe++,ge]}}).call(this)}async function me(B,Z=void 0){for await(const oe of x.call(this,B,Z))return!0;return!1}async function Ne(B,Z=void 0){if(typeof B!="function")throw new t("fn",["Function","AsyncFunction"],B);return!await me.call(this,async(...oe)=>!await B(...oe),Z)}async function te(B,Z){for await(const oe of x.call(this,B,Z))return oe}async function ae(B,Z){if(typeof B!="function")throw new t("fn",["Function","AsyncFunction"],B);async function oe(ye,ge){return await B(ye,ge),q}for await(const ye of ce.call(this,oe,Z));}function x(B,Z){if(typeof B!="function")throw new t("fn",["Function","AsyncFunction"],B);async function oe(ye,ge){return await B(ye,ge)?ye:q}return ce.call(this,oe,Z)}class O extends r{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}async function se(B,Z,oe){var ye;if(typeof B!="function")throw new t("reducer",["Function","AsyncFunction"],B);oe!=null&&c(oe,"options"),oe?.signal!=null&&o(oe.signal,"options.signal");let ge=arguments.length>1;if(oe!=null&&(ye=oe.signal)!==null&&ye!==void 0&&ye.aborted){const J=new s(void 0,{cause:oe.signal.reason});throw this.once("error",()=>{}),await f(this.destroy(J)),J}const D=new n,F=D.signal;if(oe!=null&&oe.signal){const J={once:!0,[l]:this,[d]:!0};oe.signal.addEventListener("abort",()=>D.abort(),J)}let k=!1;try{for await(const J of this){var ee;if(k=!0,oe!=null&&(ee=oe.signal)!==null&&ee!==void 0&&ee.aborted)throw new s;ge?Z=await B(Z,J,{signal:F}):(Z=J,ge=!0)}if(!k&&!ge)throw new O}finally{D.abort()}return Z}async function G(B){B!=null&&c(B,"options"),B?.signal!=null&&o(B.signal,"options.signal");const Z=[];for await(const ye of this){var oe;if(B!=null&&(oe=B.signal)!==null&&oe!==void 0&&oe.aborted)throw new s(void 0,{cause:B.signal.reason});_(Z,ye)}return Z}function le(B,Z){const oe=ce.call(this,B,Z);return(async function*(){for await(const ge of oe)yield*ge}).call(this)}function pe(B){if(B=C(B),P(B))return 0;if(B<0)throw new i("number",">= 0",B);return B}function Re(B,Z=void 0){return Z!=null&&c(Z,"options"),Z?.signal!=null&&o(Z.signal,"options.signal"),B=pe(B),(async function*(){var ye;if(Z!=null&&(ye=Z.signal)!==null&&ye!==void 0&&ye.aborted)throw new s;for await(const D of this){var ge;if(Z!=null&&(ge=Z.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;B--<=0&&(yield D)}}).call(this)}function _e(B,Z=void 0){return Z!=null&&c(Z,"options"),Z?.signal!=null&&o(Z.signal,"options.signal"),B=pe(B),(async function*(){var ye;if(Z!=null&&(ye=Z.signal)!==null&&ye!==void 0&&ye.aborted)throw new s;for await(const D of this){var ge;if(Z!=null&&(ge=Z.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;if(B-- >0&&(yield D),B<=0)return}}).call(this)}return operators.streamReturningOperators={asIndexedPairs:w(Se,"readable.asIndexedPairs will be removed in a future version."),drop:Re,filter:x,flatMap:le,map:ce,take:_e,compose:U},operators.promiseReturningOperators={every:Ne,forEach:ae,reduce:se,toArray:G,some:me,find:te},operators}var promises,hasRequiredPromises;function requirePromises(){if(hasRequiredPromises)return promises;hasRequiredPromises=1;const{ArrayPrototypePop:n,Promise:e}=requirePrimordials(),{isIterable:t,isNodeStream:r,isWebStream:i}=requireUtils(),{pipelineImpl:s}=requirePipeline(),{finished:o}=requireEndOfStream();requireStream();function a(...c){return new e((l,d)=>{let f,u;const p=c[c.length-1];if(p&&typeof p=="object"&&!r(p)&&!t(p)&&!i(p)){const g=n(c);f=g.signal,u=g.end}s(c,(g,y)=>{g?d(g):l(y)},{signal:f,end:u})})}return promises={finished:o,pipeline:a},promises}var hasRequiredStream;function requireStream(){if(hasRequiredStream)return stream.exports;hasRequiredStream=1;const{Buffer:n}=requireBuffer(),{ObjectDefineProperty:e,ObjectKeys:t,ReflectApply:r}=requirePrimordials(),{promisify:{custom:i}}=requireUtil(),{streamReturningOperators:s,promiseReturningOperators:o}=requireOperators(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:a}}=requireErrors(),c=requireCompose(),{setDefaultHighWaterMark:l,getDefaultHighWaterMark:d}=requireState(),{pipeline:f}=requirePipeline(),{destroyer:u}=requireDestroy(),p=requireEndOfStream(),g=requirePromises(),y=requireUtils(),w=stream.exports=requireLegacy().Stream;w.isDestroyed=y.isDestroyed,w.isDisturbed=y.isDisturbed,w.isErrored=y.isErrored,w.isReadable=y.isReadable,w.isWritable=y.isWritable,w.Readable=requireReadable();for(const R of t(s)){let C=function(...P){if(new.target)throw a();return w.Readable.from(r(b,this,P))};const b=s[R];e(C,"name",{__proto__:null,value:b.name}),e(C,"length",{__proto__:null,value:b.length}),e(w.Readable.prototype,R,{__proto__:null,value:C,enumerable:!1,configurable:!0,writable:!0})}for(const R of t(o)){let C=function(...P){if(new.target)throw a();return r(b,this,P)};const b=o[R];e(C,"name",{__proto__:null,value:b.name}),e(C,"length",{__proto__:null,value:b.length}),e(w.Readable.prototype,R,{__proto__:null,value:C,enumerable:!1,configurable:!0,writable:!0})}w.Writable=requireWritable(),w.Duplex=requireDuplex(),w.Transform=requireTransform(),w.PassThrough=requirePassthrough(),w.pipeline=f;const{addAbortSignal:_}=requireAddAbortSignal();return w.addAbortSignal=_,w.finished=p,w.destroy=u,w.compose=c,w.setDefaultHighWaterMark=l,w.getDefaultHighWaterMark=d,e(w,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return g}}),e(f,i,{__proto__:null,enumerable:!0,get(){return g.pipeline}}),e(p,i,{__proto__:null,enumerable:!0,get(){return g.finished}}),w.Stream=w,w._isUint8Array=function(b){return b instanceof Uint8Array},w._uint8ArrayToBuffer=function(b){return n.from(b.buffer,b.byteOffset,b.byteLength)},stream.exports}var hasRequiredBrowser;function requireBrowser(){return hasRequiredBrowser||(hasRequiredBrowser=1,(function(n){const e=requireStream(),t=requirePromises(),r=e.Readable.destroy;n.exports=e.Readable,n.exports._uint8ArrayToBuffer=e._uint8ArrayToBuffer,n.exports._isUint8Array=e._isUint8Array,n.exports.isDisturbed=e.isDisturbed,n.exports.isErrored=e.isErrored,n.exports.isReadable=e.isReadable,n.exports.Readable=e.Readable,n.exports.Writable=e.Writable,n.exports.Duplex=e.Duplex,n.exports.Transform=e.Transform,n.exports.PassThrough=e.PassThrough,n.exports.addAbortSignal=e.addAbortSignal,n.exports.finished=e.finished,n.exports.destroy=e.destroy,n.exports.destroy=r,n.exports.pipeline=e.pipeline,n.exports.compose=e.compose,Object.defineProperty(e,"promises",{configurable:!0,enumerable:!0,get(){return t}}),n.exports.Stream=e.Stream,n.exports.default=n.exports})(browser$2)),browser$2.exports}var browserExports=requireBrowser();const ITERATOR=Symbol("iter");function merge$1(n,e,t=4){if(t===0)return Object.assign(n,e);for(const r in e)n[r]=merge$1(n[r]||Object.create(null),e[r],t-1);return n}function intersect(n,e,t=4){let r=!1;for(const i in n)if(i in e){const s=t===0?null:intersect(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}function difference(n,e,t=4){let r=!1;for(const i in n)if(!(i in e))r=r||Object.create(null),r[i]=t===0?null:merge$1({},n[i],t-1);else if(t!==0){const s=difference(n[i],e[i],t-1);if(s!==!1)r=r||Object.create(null),r[i]=s;else if(t===3)return!1}return r}class N3EntityIndex{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||DataFactory$1}_termFromId(e){if(e[0]==="."){const t=this._entities,r=e.split(".");return this._factory.quad(this._termFromId(t[r[1]]),this._termFromId(t[r[2]]),this._termFromId(t[r[3]]),r[4]&&this._termFromId(t[r[4]]))}return termFromId(e,this._factory)}_termToNumericId(e){if(e.termType==="Quad"){const t=this._termToNumericId(e.subject),r=this._termToNumericId(e.predicate),i=this._termToNumericId(e.object);let s;return t&&r&&i&&(isDefaultGraph(e.graph)||(s=this._termToNumericId(e.graph)))&&this._ids[s?`.${t}.${r}.${i}.${s}`:`.${t}.${r}.${i}`]}return this._ids[termToId(e)]}_termToNewNumericId(e){const t=e&&e.termType==="Quad"?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${isDefaultGraph(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:termToId(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,r;if(e)for(t=e=`_:${e}`,r=1;this._ids[t];)t=e+r++;else do t=`_:b${this._blankNodeIndex++}`;while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class N3Store{constructor(e,t){this._size=0,this._graphs=Object.create(null),!t&&e&&!e[0]&&typeof e.match!="function"&&(t=e,e=null),t=t||{},this._factory=t.factory||DataFactory$1,this._entityIndex=t.entityIndex||new N3EntityIndex({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(e!==null)return e;e=0;const t=this._graphs;let r,i;for(const s in t)for(const o in r=t[s].subjects)for(const a in i=r[o])e+=Object.keys(i[a]).length;return this._size=e}_addToIndex(e,t,r,i){const s=e[t]||(e[t]={}),o=s[r]||(s[r]={}),a=i in o;return a||(o[i]=null),!a}_removeFromIndex(e,t,r,i){const s=e[t],o=s[r];delete o[i];for(const a in o)return;delete s[r];for(const a in s)return;delete e[t]}*_findInIndex(e,t,r,i,s,o,a,c){let l,d,f;const u=this._entities,p=this._termFromId(u[c]),g={subject:null,predicate:null,object:null};t&&((l=e,e={})[t]=l[t]);for(const y in e)if(d=e[y]){g[s]=this._termFromId(u[y]),r&&((l=d,d={})[r]=l[r]);for(const w in d)if(f=d[w]){g[o]=this._termFromId(u[w]);const _=i?i in f?[i]:[]:Object.keys(f);for(let R=0;R<_.length;R++)g[a]=this._termFromId(u[_[R]]),yield this._factory.quad(g.subject,g.predicate,g.object,p)}}}_loop(e,t){for(const r in e)t(r)}_loopByKey0(e,t,r){let i,s;if(i=e[t])for(s in i)r(s)}_loopByKey1(e,t,r){let i,s;for(i in e)s=e[i],s[t]&&r(i)}_loopBy2Keys(e,t,r,i){let s,o,a;if((s=e[t])&&(o=s[r]))for(a in o)i(a)}_countInIndex(e,t,r,i){let s=0,o,a,c;t&&((o=e,e={})[t]=o[t]);for(const l in e)if(a=e[l]){r&&((o=a,a={})[r]=o[r]);for(const d in a)(c=a[d])&&(i?i in c&&s++:s+=Object.keys(c).length)}return s}_getGraphs(e){return e=e===""?1:e&&(this._termToNumericId(e)||-1),typeof e!="number"?this._graphs:{[e]:this._graphs[e]}}_uniqueEntities(e){const t=Object.create(null);return r=>{r in t||(t[r]=!0,e(this._termFromId(this._entities[r],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,r,i){t||(i=e.graph,r=e.object,t=e.predicate,e=e.subject),i=i?this._termToNewNumericId(i):1;let s=this._graphs[i];return s||(s=this._graphs[i]={subjects:{},predicates:{},objects:{}},Object.freeze(s)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),r=this._termToNewNumericId(r),this._addToIndex(s.subjects,e,t,r)?(this._addToIndex(s.predicates,t,r,e),this._addToIndex(s.objects,r,e,t),this._size=null,!0):!1}addQuads(e){for(let t=0;t<e.length;t++)this.addQuad(e[t])}delete(e){return this.removeQuad(e),this}has(e,t,r,i){return e&&e.subject&&({subject:e,predicate:t,object:r,graph:i}=e),!this.readQuads(e,t,r,i).next().done}import(e){return e.on("data",t=>{this.addQuad(t)}),e}removeQuad(e,t,r,i){t||({subject:e,predicate:t,object:r,graph:i}=e),i=i?this._termToNumericId(i):1;const s=this._graphs;let o,a,c;if(!(e=e&&this._termToNumericId(e))||!(t=t&&this._termToNumericId(t))||!(r=r&&this._termToNumericId(r))||!(o=s[i])||!(a=o.subjects[e])||!(c=a[t])||!(r in c))return!1;this._removeFromIndex(o.subjects,e,t,r),this._removeFromIndex(o.predicates,t,r,e),this._removeFromIndex(o.objects,r,e,t),this._size!==null&&this._size--;for(e in o.subjects)return!0;return delete s[i],!0}removeQuads(e){for(let t=0;t<e.length;t++)this.removeQuad(e[t])}remove(e){return e.on("data",t=>{this.removeQuad(t)}),e}removeMatches(e,t,r,i){const s=new browserExports.Readable({objectMode:!0}),o=this.readQuads(e,t,r,i);return s._read=a=>{for(;--a>=0;){const{done:c,value:l}=o.next();if(c){s.push(null);return}s.push(l)}},this.remove(s)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,r,i){return[...this.readQuads(e,t,r,i)]}*readQuads(e,t,r,i){const s=this._getGraphs(i);let o,a,c,l;if(!(e&&!(a=this._termToNumericId(e))||t&&!(c=this._termToNumericId(t))||r&&!(l=this._termToNumericId(r))))for(const d in s)(o=s[d])&&(a?l?yield*this._findInIndex(o.objects,l,a,c,"object","subject","predicate",d):yield*this._findInIndex(o.subjects,a,c,null,"subject","predicate","object",d):c?yield*this._findInIndex(o.predicates,c,l,null,"predicate","object","subject",d):l?yield*this._findInIndex(o.objects,l,null,null,"object","subject","predicate",d):yield*this._findInIndex(o.subjects,null,null,null,"subject","predicate","object",d))}match(e,t,r,i){return new DatasetCoreAndReadableStream(this,e,t,r,i,{entityIndex:this._entityIndex})}countQuads(e,t,r,i){const s=this._getGraphs(i);let o=0,a,c,l,d;if(e&&!(c=this._termToNumericId(e))||t&&!(l=this._termToNumericId(t))||r&&!(d=this._termToNumericId(r)))return 0;for(const f in s)(a=s[f])&&(e?r?o+=this._countInIndex(a.objects,d,c,l):o+=this._countInIndex(a.subjects,c,l,d):t?o+=this._countInIndex(a.predicates,l,d,c):o+=this._countInIndex(a.objects,d,c,l));return o}forEach(e,t,r,i,s){this.some(o=>(e(o,this),!1),t,r,i,s)}every(e,t,r,i,s){return!this.some(o=>!e(o,this),t,r,i,s)}some(e,t,r,i,s){for(const o of this.readQuads(t,r,i,s))if(e(o,this))return!0;return!1}getSubjects(e,t,r){const i=[];return this.forSubjects(s=>{i.push(s)},e,t,r),i}forSubjects(e,t,r,i){const s=this._getGraphs(i);let o,a,c;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?c?this._loopBy2Keys(o.predicates,a,c,e):this._loopByKey1(o.subjects,a,e):c?this._loopByKey0(o.objects,c,e):this._loop(o.subjects,e))}getPredicates(e,t,r){const i=[];return this.forPredicates(s=>{i.push(s)},e,t,r),i}forPredicates(e,t,r,i){const s=this._getGraphs(i);let o,a,c;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?c?this._loopBy2Keys(o.objects,c,a,e):this._loopByKey0(o.subjects,a,e):c?this._loopByKey1(o.predicates,c,e):this._loop(o.predicates,e))}getObjects(e,t,r){const i=[];return this.forObjects(s=>{i.push(s)},e,t,r),i}forObjects(e,t,r,i){const s=this._getGraphs(i);let o,a,c;if(e=this._uniqueEntities(e),!(t&&!(a=this._termToNumericId(t))||r&&!(c=this._termToNumericId(r))))for(i in s)(o=s[i])&&(a?c?this._loopBy2Keys(o.subjects,a,c,e):this._loopByKey1(o.objects,a,e):c?this._loopByKey0(o.predicates,c,e):this._loop(o.objects,e))}getGraphs(e,t,r){const i=[];return this.forGraphs(s=>{i.push(s)},e,t,r),i}forGraphs(e,t,r,i){for(const s in this._graphs)this.some(o=>(e(o.graph),!0),t,r,i,this._termFromId(this._entities[s]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const r={},i=t?(()=>!0):((a,c)=>{throw new Error(`${a.value} ${c}`)}),s=this.getQuads(null,namespaces.rdf.rest,namespaces.rdf.nil,null),o=e?[...s]:[];return s.forEach(a=>{const c=[];let l=!1,d,f;const u=a.graph;let p=a.subject;for(;p&&!l;){const g=this.getQuads(null,null,p,null),y=this.getQuads(p,null,null,null);let w,_=null,R=null,b=null;for(let C=0;C<y.length&&!l;C++)w=y[C],w.graph.equals(u)?d?l=i(p,"has non-list arcs out"):w.predicate.value===namespaces.rdf.first?_?l=i(p,"has multiple rdf:first arcs"):o.push(_=w):w.predicate.value===namespaces.rdf.rest?R?l=i(p,"has multiple rdf:rest arcs"):o.push(R=w):g.length?l=i(p,"can't be subject and object"):(d=w,f="subject"):l=i(p,"not confined to single graph");for(let C=0;C<g.length&&!l;++C)w=g[C],d?l=i(p,"can't have coreferences"):w.predicate.value===namespaces.rdf.rest?b?l=i(p,"has incoming rdf:rest arcs"):b=w:(d=w,f="object");_?c.unshift(_.object):l=i(p,"has no list head"),p=b&&b.subject}l?e=!1:d&&(r[d[f].value]=c)}),e&&this.removeQuads(o),r}addAll(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),Array.isArray(e))this.addQuads(e);else if(e instanceof N3Store&&e._entityIndex===this._entityIndex)e._size!==0&&(this._graphs=merge$1(this._graphs,e._graphs),this._size=null);else for(const t of e)this.add(t);return this}contains(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return!0;if(!(e instanceof N3Store)||this._entityIndex!==e._entityIndex)return e.every(l=>this.has(l));const t=this._graphs,r=e._graphs;let i,s,o,a,c;for(const l in r){if(!(i=t[l]))return!1;i=i.subjects;for(const d in s=r[l].subjects){if(!(o=i[d]))return!1;for(const f in a=s[d]){if(!(c=o[f]))return!1;for(const u in a[f])if(!(u in c))return!1}}}return!0}deleteMatches(e,t,r,i){for(const s of this.match(e,t,r,i))this.removeQuad(s);return this}difference(e){if(e&&e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this)return new N3Store({entityIndex:this._entityIndex});if(e instanceof N3Store&&e._entityIndex===this._entityIndex){const t=new N3Store({entityIndex:this._entityIndex}),r=difference(this._graphs,e._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)e(r,this)&&t.add(r);return t}intersection(e){if(e instanceof DatasetCoreAndReadableStream&&(e=e.filtered),e===this){const t=new N3Store({entityIndex:this._entityIndex});return t._graphs=merge$1(Object.create(null),this._graphs),t._size=this._size,t}else if(e instanceof N3Store&&this._entityIndex===e._entityIndex){const t=new N3Store({entityIndex:this._entityIndex}),r=intersect(e._graphs,this._graphs);return r&&(t._graphs=r,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new N3Store({entityIndex:this._entityIndex});for(const r of this)t.add(e(r,this));return t}reduce(e,t){const r=this.readQuads();let i=t===void 0?r.next().value:t;for(const s of r)i=e(i,s,this);return i}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return new N3Writer().quadsToString(this)}union(e){const t=new N3Store({entityIndex:this._entityIndex});return t._graphs=merge$1(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function indexMatch(n,e,t=0){const r=e[t];if(r&&!(r in n))return!1;let i=!1;for(const s in r?{[r]:n[r]}:n){const o=t===2?null:indexMatch(n[s],e,t+1);o!==!1&&(i=i||Object.create(null),i[s]=o)}return i}class DatasetCoreAndReadableStream extends browserExports.Readable{constructor(e,t,r,i,s,o){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:r,object:i,graph:s,options:o})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:r,predicate:i,subject:s}=this,o=this._filtered=new N3Store({factory:e._factory,entityIndex:this.options.entityIndex});let a,c,l;if(s&&!(a=o._termToNumericId(s))||i&&!(c=o._termToNumericId(i))||r&&!(l=o._termToNumericId(r)))return o;const d=e._getGraphs(t);for(const f in d){let u,p,g,y;(y=d[f])&&(!a&&c?(p=indexMatch(y.predicates,[c,l,a]))&&(u=indexMatch(y.subjects,[a,c,l]),g=indexMatch(y.objects,[l,a,c])):l?(g=indexMatch(y.objects,[l,a,c]))&&(u=indexMatch(y.subjects,[a,c,l]),p=indexMatch(y.predicates,[c,l,a])):(u=indexMatch(y.subjects,[a,c,l]))&&(p=indexMatch(y.predicates,[c,l,a]),g=indexMatch(y.objects,[l,a,c])),u&&(o._graphs[f]={subjects:u,predicates:p,objects:g}))}o._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[ITERATOR]&&(this[ITERATOR]=this[Symbol.iterator]());const t=this[ITERATOR];for(;--e>=0;){const{done:r,value:i}=t.next();if(r){this.push(null);return}this.push(i)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,r,i){return this.filtered.deleteMatches(e,t,r,i)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,r,i,s){return this.filtered.every(e,t,r,i,s)}filter(e){return this.filtered.filter(e)}forEach(e,t,r,i,s){return this.filtered.forEach(e,t,r,i,s)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,r,i,s){return this.filtered.some(e,t,r,i,s)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return new N3Writer().quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,r,i){return new DatasetCoreAndReadableStream(this.filtered,e,t,r,i,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}var _a$7;function isRecord$1(n){return typeof n=="object"&&n!==null}function isPodTable(n){return isRecord$1(n)&&"columns"in n&&"config"in n}function hasStringValue$1(n){return isRecord$1(n)&&typeof n.value=="string"}function isAbsoluteIri(n){return n.startsWith("http://")||n.startsWith("https://")}function isBaseRelativeSubjectId(n){return!n||isAbsoluteIri(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTimeLocatorKey(n){return["yyyy","MM","dd","HH","mm","ss","timestamp"].includes(n)}function parseTemplateVariableField(n){return n.split("|").map(e=>e.trim()).filter(Boolean)[0]??n}function escapeSparqlString(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")}function hasTimeLocatorContext(n){return n.createdAt!==void 0||n.created_at!==void 0||n.dateCreated!==void 0}function getKnownRowIri(n){for(const e of["@id","subject","uri","source"]){const t=n[e];if(typeof t=="string"&&isAbsoluteIri(t))return t}}class PodDatabase{constructor(e,t,r){this.dialect=e,this.session=t,this.schema=r,this.notificationsClient=null,this.federatedExecutor=null,this.lastFederatedErrors=[]}getLastFederatedErrors(){return this.lastFederatedErrors}clearFederatedErrors(){this.lastFederatedErrors=[]}getFederatedExecutor(){return this.federatedExecutor||(this.federatedExecutor=new FederatedQueryExecutor({fetch:this.dialect.getAuthenticatedFetch()})),this.federatedExecutor}createTable(e,t){const r=e.table("default",t);return t.hooks&&(r.config.hooks=t.hooks),Reflect.set(r,"_db",this),r}select(e){return this.session.select(e)}insert(e){return this.session.insert(e)}update(e){return this.session.update(e)}delete(e){return this.session.delete(e)}async execute(e){return await this.executeSPARQL(e)}async executeSPARQL(e){if(typeof e!="string"||e.trim().length===0)throw new Error("executeSPARQL requires a non-empty SPARQL query string");return await this.dialect.executeSPARQL(e)}async batch(e){const t=[];for(const r of e)t.push(await r);return t}async findFirst(e,t){const r=this.select().from(e).limit(1);t&&Object.keys(t).length>0&&r.where(t);const i=await r;return i.length>0?i[0]:null}getLocatorTemplate(e){return e.getSubjectTemplate?.()??e.config?.subjectTemplate}getRequiredLocatorKeys(e){const t=this.getLocatorTemplate(e);if(!t)return["id"];const r=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>parseTemplateVariableField(i[1])).filter(i=>i!=="index");return Array.from(new Set(r))}resolveResourceTargetIri(e,t,r){if(typeof t=="string")return isAbsoluteIri(t)?t:this.resolveLocatorSubject(e,{id:t},r);if(!isRecord$1(t)||Array.isArray(t))throw new Error(`${r} requires a resource IRI, base-relative id, row, or locator object`);const i=getKnownRowIri(t);return i||this.resolveLocatorSubject(e,t,r)}resolveLocatorSubject(e,t,r){if(!isRecord$1(t)||Array.isArray(t))throw new Error(`${r} requires a locator object`);if("@id"in t)throw new Error(`${r} does not accept '@id'. Use ${this.getIriAlternative(r)} instead.`);const i=t.id;if(typeof i=="string"&&isAbsoluteIri(i))throw new Error(`${r} does not accept a full IRI in locator.id. Use ${this.getIriAlternative(r)} instead.`);const s=this.getRequiredLocatorKeys(e),o=this.dialect.getResolver(e),a=hasTimeLocatorContext(t),c=s.filter(l=>t[l]!==void 0&&t[l]!==null?!1:!(a&&isTimeLocatorKey(l)));if(typeof i=="string"&&isBaseRelativeSubjectId(i)){const l=s.filter(d=>d!=="id");if(i.startsWith("#")&&l.length>0){const d=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} requires a complete locator for subjectTemplate '${d}'. Missing [${l.join(", ")}]. Use a base-relative resource id that includes every storage slot.`)}return o.resolveSubject(e,t)}if(c.length>0){const l=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} requires a complete locator for subjectTemplate '${l}'. Missing [${c.join(", ")}]. Use ${this.getIriAlternative(r)} when you already have a full IRI.`)}return o.resolveSubject(e,t)}resolveIdSubject(e,t,r){if(!t||typeof t!="string")throw new Error(`${r} requires a valid base-relative resource id string`);if(isAbsoluteIri(t))throw new Error(`${r} requires a base-relative resource id. Use ${this.getIriAlternative(r)} for full IRIs.`);const i=this.getLocatorTemplate(e)??"<exact-id>",s=this.getRequiredLocatorKeys(e).filter(a=>a!=="id"),o=this.dialect.getResolver(e);if(isBaseRelativeSubjectId(t)){if(t.startsWith("#")&&s.length>0)throw new Error(`${r} requires a base-relative resource id for subjectTemplate '${i}', got local fragment id '${t}'. Missing [${s.join(", ")}]. Use a base-relative id that includes every storage slot.`);return o.resolveSubject(e,{id:t.startsWith("#")?t.slice(1):t})}if(s.length>0)throw new Error(`${r} requires a base-relative resource id for subjectTemplate '${i}', got local id '${t}'. Missing [${s.join(", ")}]. Use a base-relative id that includes every storage slot.`);return o.resolveSubject(e,{id:t})}warnFindByLocatorDeprecation(){PodDatabase.findByLocatorDeprecationWarned||(PodDatabase.findByLocatorDeprecationWarned=!0,console.warn("[drizzle-solid] findByLocator(resource, locator) is deprecated and will be removed in a future release. Use findById(resource, id) for base-relative resource ids, findByResource(resource, target) for generic exact targets, or findByIri(resource, iri) for full IRIs."))}getIriAlternative(e){return e==="resolveLocatorIri"||e==="resolveLocatorId"?"the full IRI directly":e==="findById"||e==="findByResource"?"findByIri(resource, iri)":e==="updateById"||e==="updateByResource"?"updateByIri(resource, iri, data)":e==="deleteById"||e==="deleteByResource"?"deleteByIri(resource, iri)":`${e.replace("Locator","Iri")}(resource, iri)`}resolveLocatorIri(e,t){return this.resolveLocatorSubject(e,t,"resolveLocatorIri")}resolveLocatorId(e,t){const r=this.resolveLocatorSubject(e,t,"resolveLocatorId");return this.resolveBaseRelativeResourceId(e,r)}resolveResourceIri(e,t){return this.resolveResourceTargetIri(e,t,"resolveResourceIri")}resolveResourceId(e,t){const r=this.resolveResourceTargetIri(e,t,"resolveResourceId");return this.resolveBaseRelativeResourceId(e,r)}resolveRelationIri(e,t){return this.resolveResourceTargetIri(e,t,"resolveRelationIri")}resolveRowIri(e,t){if(!isRecord$1(t)||Array.isArray(t))throw new Error("resolveRowIri requires a row object");return getKnownRowIri(t)??this.resolveLocatorSubject(e,t,"resolveRowIri")}resolveRowId(e,t){if(!isRecord$1(t)||Array.isArray(t))throw new Error("resolveRowId requires a row object");const r=getKnownRowIri(t)??this.resolveLocatorSubject(e,t,"resolveRowId");return this.resolveBaseRelativeResourceId(e,r)}resolveBaseRelativeResourceId(e,t){return parsePodResourceRef(e,t)?.resourceId??this.dialect.getResolver(e).parseId(e,t)}needsShortIdSubjectLookup(e,t){return!t||typeof t!="string"||isAbsoluteIri(t)||isBaseRelativeSubjectId(t)?!1:this.getRequiredLocatorKeys(e).some(r=>r!=="id")}buildShortIdSubjectSuffix(e,t){const r=this.getLocatorTemplate(e)??"<exact-id>",i=Array.from(r.matchAll(/\{([^}]+)\}/g));let s=-1;for(let f=i.length-1;f>=0;f--)if(parseTemplateVariableField(i[f][1])==="id"){s=f;break}if(s<0)return t;const o=i[s],a=i[s-1],c=a?.index===void 0?0:a.index+a[0].length,l=o.index??0,d=l+o[0].length;return`${r.slice(c,l)}${t}${r.slice(d)}`}resolveShortIdLookupSource(e){const t=this.dialect;if(typeof t.resolveTableResource=="function"){const r=t.resolveTableResource(e);if(r.mode==="sparql"&&r.endpoint)return{kind:"sparql",resourceUrl:r.endpoint,descriptor:r}}return null}extractSubjectFromLookupRow(e){if(!isRecord$1(e))return null;const t=e.subject??e.s??e["?subject"]??e["?s"];return typeof t=="string"?t:hasStringValue$1(t)?t.value:null}subjectMatchesShortId(e,t,r,i){const s=parsePodResourceRef(e,t);return s?s.templateValues.id===r:t.endsWith(i)}getIndexedSubject(e,t){const r=this.dialect;return typeof r.lookupIndexedResourceSubject!="function"?null:r.lookupIndexedResourceSubject(e,t)}async lookupSubjectIriByShortId(e,t,r){const i=this.resolveShortIdLookupSource(e);if(!i){const f=this.getLocatorTemplate(e)??"<exact-id>";throw new Error(`${r} cannot resolve short id '${t}' for subjectTemplate '${f}' because no resource query source is available.`)}const s=this.buildShortIdSubjectSuffix(e,t),o=t,c={type:"SELECT",query:`SELECT DISTINCT ?subject WHERE {
28
+ ${e.config?.type?`?subject ?typePredicate ?typeObject .
29
+ FILTER(?typePredicate = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?typeObject = <${e.config.type}> && CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`:`?subject ?predicate ?object .
30
+ FILTER(CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`}
31
+ }
32
+ LIMIT 50`,prefixes:{}},l=i.kind==="sparql"?await this.dialect.executeOnResource(i.resourceUrl,c,i.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(i.resourceUrl,c),d=Array.from(new Set(l.map(f=>this.extractSubjectFromLookupRow(f)).filter(f=>!!f).filter(f=>this.subjectMatchesShortId(e,f,t,s))));if(d.length>1)throw new Error(`${r} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return d[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,r){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,r):this.resolveIdSubject(e,t,r)}async findById(e,t){const r=await this.resolveIdSubjectForExactOperation(e,t,"findById");return r?await this.findByIri(e,r):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const r=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,r)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const r=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,r)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const r=await this.findByIriViaExactResource(e,t);return r!==void 0?r:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const r=this.parseIri(t).documentUrl,i=await this.readPredicateObjectRowsFromDocument(r,t);if(i===null)return null;if(i!==void 0){const c=this.mapPredicateObjectRows(e,t,i);if(c!==void 0)return c}if(typeof this.dialect.executeOnResource!="function")return;const s={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(r,s)}catch(c){if(this.isMissingExactResourceError(c))return;throw c}const a=this.mapPredicateObjectRows(e,t,o);if(a!==void 0)return a}async readPredicateObjectRowsFromDocument(e,t){const r=this.dialect.getAuthenticatedFetch;if(typeof r!="function")return;let i;try{i=await r.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(a){return this.isMissingExactResourceError(a)?null:void 0}if(i.status===404)return null;if(!i.ok)return;const s=i.headers.get("content-type")??"";if(s&&!s.includes("text/turtle")&&!s.includes("application/n-triples")&&!s.includes("application/trig")&&!s.includes("application/ld+json"))return;const o=await i.text();if(!o.trim())return null;try{return new N3Parser({baseIRI:e,format:s.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(l=>l.subject.termType==="NamedNode"&&l.subject.value===t).map(l=>({p:l.predicate.value,o:this.convertRdfTermToValue(l.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$1(e))return!1;if((e.status??e.statusCode)===404)return!0;const r=e.message;return typeof r=="string"&&/\b(?:HTTP status )?404\b/.test(r)}mapPredicateObjectRows(e,t,r){if(!Array.isArray(r)||r.length===0)return null;const i={subject:t,"@id":t,uri:t},s=this.extractIdFromIri(e,t);s!==void 0&&(i.id=s);let o=!1,a=!1,c=!1;for(const l of r){if(!isRecord$1(l))continue;const d=l.p??l.predicate??l["?p"],f=l.o??l.object??l["?o"];if(typeof d=="string"){d==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&f===e.config.type&&(o=!0);for(const[u,p]of Object.entries(e.columns??{})){if(p._virtualId)continue;const g=this.getColumnPredicate(e,p);if(!g||g==="@id"||g!==d)continue;if(p.options?.isArray||p.dataType==="array"){const w=Array.isArray(i[u])?i[u]:i[u]===void 0?[]:[i[u]];i[u]=[...w,f]}else i[u]===void 0&&(i[u]=f);(p.dataType==="object"||p.dataType==="json")&&typeof f=="string"&&isAbsoluteIri(f)&&(c=!0),a=!0}}}if(!o&&!a)return null;if(!c)return i}extractIdFromIri(e,t){const r=parsePodResourceRef(e,t)?.resourceId;if(r)return r;try{const a=this.dialect.getResolver(e).parseId(e,t);if(a)return a}catch{}const i=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!i)return;if(i==="{id}.ttl"){const a=t.split("/").pop()??"";return a.endsWith(".ttl")?a.slice(0,-4):a||void 0}if(i==="{id}.ttl#it"){const c=t.split("#")[0].split("/").pop()??"";return c.endsWith(".ttl")?c.slice(0,-4):c||void 0}const s=t.indexOf("#");if(s>=0&&i.includes("{id}")&&i.startsWith("#"))return decodeURIComponent(t.slice(s+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,r){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),a={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,a)}const{documentUrl:i}=this.parseIri(t),s=await this.notificationsClient.subscribe(i,{channel:r.channel,features:r.features,onNotification:async o=>{try{if(o.type==="Update"){const a=await this.findByIri(e,t);a&&await r.onUpdate(a)}else o.type==="Delete"&&await r.onDelete?.()}catch(a){r.onError?.(a)}},onError:r.onError});return()=>s.unsubscribe()}async updateByIri(e,t,r){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const i=r;return await this.session.update(e).set(i).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,r){const i=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return i?await this.updateByIri(e,i,r):null}async updateByLocator(e,t,r){const i=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,i,r)}async updateByResource(e,t,r){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,r);const i=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,i,r)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const r=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return r?await this.deleteByIri(e,r):!1}async deleteByLocator(e,t){const r=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,r)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const r=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,r)}async transaction(e){return await this.session.transaction(async t=>{const r=new PodDatabase(this.dialect,t,this.schema);return await e(r)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const s=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(s,o)}const r=this.resolveResourceTopic(e,t.iri),i={channel:t.channel,features:t.features,onNotification:s=>{if(t.onNotification?.(s),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const a={id:s.id,type:s.type,object:s.object,published:s.published,state:s.state};switch(s.type){case"Create":t.onCreate?.(a);break;case"Update":t.onUpdate?.(a);break;case"Delete":t.onDelete?.(a);break;case"Add":t.onAdd?.(a);break;case"Remove":t.onRemove?.(a);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(r,i)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const r=e.config.base||"";if(r.startsWith("http://")||r.startsWith("https://"))return r;const i=this.dialect.getPodUrl(),s=i.endsWith("/")?i:`${i}/`,o=r.startsWith("/")?r.slice(1):r;return`${s}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const r=t[0],i=r.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${r.container}, shape: ${i||"none"}`),i){const l=this.dialect.getShapeManager(),d=await l.loadShape(i,this.dialect.getAuthenticatedFetch());if(d){console.log(`[discoverTable] Loaded shape with ${d.properties.length} properties`);const f=l.shapeToTable(d,r.container);return await this.init(f.table),f.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:d}=await Promise.resolve().then(()=>index);return{podTable:l,string:d}},void 0),a=this.extractClassName(e),c=s(a,{id:o("id").primaryKey()},{type:e,base:r.container});return await this.init(c),c}async discoverTables(e){const t=[];for(const r of e){const i=await this.discoverTable(r);i&&t.push(i)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const r=t??{};let i;if(r.shape)typeof r.shape=="string"?(i=e.shapes.find(l=>l.url===r.shape),i||(i={url:r.shape,source:"config"})):i=r.shape;else if(r.appId){if(i=e.shapes.find(l=>l.registeredBy===r.appId),!i)throw new Error(`[locationToTable] No shape found for appId: ${r.appId}`)}else i=e.shapes[0];if(i?.url){const l=this.dialect.getShapeManager(),d=await l.loadShape(i.url,this.dialect.getAuthenticatedFetch());if(d){console.log(`[locationToTable] Loaded shape: ${i.url} (${d.properties.length} properties)`),i.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${i.registeredBy}`);const f=l.shapeToTable(d,e.container);return await this.init(f.table),f.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:d}=await Promise.resolve().then(()=>index);return{podTable:l,string:d}},void 0),a=this.extractContainerName(e.container),c=s(a,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(c),c}extractContainerName(e){const t=e.replace(/\/$/,""),r=t.lastIndexOf("/");return r>=0&&t.substring(r+1).toLowerCase()||"data"}async discoverTablesFor(e,t,r){const i=await this.discover(e,t),s=[];for(const o of i){const a=await this.locationToTable(o,r);s.push(a)}return s}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const r=e.lastIndexOf("/");return r>=0?e.substring(r+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,r;const i=e[e.length-1];i&&typeof i=="object"&&!Array.isArray(i)&&!("columns"in i)?(t=i,r=e.slice(0,-1)):r=e;const s=[];for(const o of r)if(o)if(Array.isArray(o))for(const a of o)a&&s.push(a);else s.push(o);for(const o of s)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const a=this.dialect.getShapeManager(),c=a.generateShape(o);if(t?.saveShape){const l=this.dialect.getPodUrl();let d=t.shapeLocation;d?d.startsWith("http")||(d=`${l}${d.replace(/^\//,"")}`):d=`${l}shapes/`,d.endsWith("/")||(d+="/");const f=`${d}${o.config.name}Shape.ttl`;try{await a.saveShape(c,f),console.log(`[init] Shape saved to: ${f}`)}catch(u){console.warn(`[init] Failed to save Shape to ${f}:`,u)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[s,o]of e)isPodTable(o)&&t.set(s,o);const r=(s,o)=>{const a=b=>{let C=null;const P=()=>(C||(C=b()),C);return{then:(H,M)=>P().then(H,M),catch:H=>P().catch(H),finally:H=>P().finally(H),[Symbol.toStringTag]:"Promise"}},c=(b,C,P)=>{const H={};for(const[M,re]of Object.entries(C)){if(re instanceof PodColumnBase){H[M]=b[re.name];continue}if(typeof re=="string"){H[M]=b[re]??b[re.split(".").pop()??re];continue}const he=re?.name;if(typeof he=="string"){H[M]=b[he];continue}H[M]=b[M]}if(P)for(const M of Object.keys(P))H[M]=b[M]??[];return H},l=async b=>{this.clearFederatedErrors();let C=this.session.select().from(o);b?.where&&(C=C.where(b.where)),b?.orderBy&&(Array.isArray(b.orderBy)?b.orderBy:[b.orderBy]).forEach(re=>{C=C.orderBy(re.column,re.direction??"asc")}),typeof b?.limit=="number"&&(C=C.limit(b.limit)),typeof b?.offset=="number"&&(C=C.offset(b.offset));let P=await C;b?.with&&Object.keys(b.with).length>0&&(P=await this.eagerLoadWith(P,o,b.with,t));const H=b?.columns;return H&&(P=P.map(M=>c(M,H,b.with))),P},d=b=>a(()=>l(b)),f=async(b,C)=>{if(!b)return null;let P=[b];C?.with&&Object.keys(C.with).length>0&&(P=await this.eagerLoadWith(P,o,C.with,t));const H=C?.columns;return H&&(P=P.map(M=>c(M,H,C.with))),P[0]??null},u=b=>a(async()=>(await l({...b,limit:1}))[0]??null),p=b=>a(async()=>(await l({where:b?.where,columns:void 0,limit:void 0,offset:void 0})).length),g=()=>(b,C)=>a(async()=>await f(await this.findByLocator(o,b),C)),y=()=>(b,C)=>a(async()=>await f(await this.findById(o,b),C)),w=()=>(b,C)=>a(async()=>await f(await this.findByIri(o,b),C)),_=()=>(b,C)=>a(async()=>await f(await this.findByResource(o,b),C));return{findMany:d,findFirst:u,find:(b,C)=>_()(b,C),findById:y(),findByLocator:g(),findByIri:w(),findByResource:_(),count:p}},i={};return new Proxy(i,{get:(s,o)=>{if(typeof o!="string")return;const a=t.get(o);if(a)return r(o,a)}})}async eagerLoadWith(e,t,r,i){if(!e||e.length===0)return e;const s=this.dedupeBySubject(e);for(const[o,a]of Object.entries(r)){if(!a)continue;const c=t.relations?.[o],l=typeof a=="object"&&a.table?a.table:c?.table??i.get(o);if(!l)continue;if(isSolidSchema(l)||c?.isFederated){if(c&&c.discover)try{const re=await this.getFederatedExecutor().execute(s,{...c,relationName:o});re.errors&&re.errors.length>0&&this.lastFederatedErrors.push(...re.errors)}catch(M){console.warn(`Federated relation "${o}" failed:`,M),s.forEach(re=>{re[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),s.forEach(M=>{M[o]=[]});continue}const d=l,f=d.config.type,u=c?.fields&&c.fields.length>0?c.fields:Object.values(d.columns??{}),p=M=>!!(M&&(M.options?.linkTarget===t.config.type||M.options?.linkTable===t||M.getLinkTable?.()===t)),g=M=>!!(M&&(M.options?.linkTarget===f||M.options?.linkTable===d||M.getLinkTable?.()===d)),y=c?.fields&&c.fields.length>0?u:u.filter(M=>p(M)&&!M.isInverse?.());if(y.length===0){const re=(c?.references??[]).filter(me=>!!(me&&typeof me.isInverse=="function"&&me.isInverse()&&g(me))),he=Object.values(t.columns??{}),V=(re.length>0?re:he).filter(me=>typeof me.isInverse=="function"&&me.isInverse()&&g(me));if(V.length===0)continue;const q=s.map(me=>this.collectInverseLinkValues(me,V)),ie=Array.from(new Set(q.flat().filter(me=>typeof me=="string"&&me.length>0)));if(ie.length===0){e.forEach(me=>{me[o]=[]});continue}let U=this.session.select().from(d);U=U.whereByIri(ie);const ce=await U,Se=this.groupRowsByIri(ce);s.forEach((me,Ne)=>{const te=q[Ne],ae=[];te.forEach(x=>{const O=Se.get(x);O&&O.length>0&&ae.push(...O)}),me[o]=ae});continue}const w=y[0],_=c?.references&&c.references[0],R=w.isLink(),b=s.map(M=>this.resolveParentKey(M,_,R)).filter(M=>typeof M=="string"&&M.length>0);if(b.length===0)continue;let C=this.session.select().from(d);R?C=C.where(inArray(w,b)):C=C.where({[w.name]:b});const P=await C,H=new Map;for(const M of P){const re=M[w.name],he=this.normalizeLiteralValue(re),V=R?this.collectLinkLookupKeys(re):he?[he]:[];for(const q of V){const ie=H.get(q)??[];ie.push(M),H.set(q,ie)}}s.forEach(M=>{const re=R?Array.from(new Set([this.resolveParentKey(M,_,!0),this.resolveIdFromRow(M)].filter(V=>typeof V=="string"&&V.length>0))):[this.resolveParentKey(M,_,!1)].filter(V=>typeof V=="string"&&V.length>0),he=[];for(const V of re){const q=H.get(V)??[];for(const ie of q)he.includes(ie)||he.push(ie)}M[o]=he})}return s}dedupeBySubject(e){const t=new Map,r=[];for(const i of e){const s=this.resolveIriFromRow(i)??this.resolveIdFromRow(i);if(!s){r.push(`__anon_${r.length}`),t.set(r[r.length-1],{...i});continue}if(!t.has(s)){t.set(s,{...i}),r.push(s);continue}const o=t.get(s);if(o)for(const[a,c]of Object.entries(i)){if(c===void 0)continue;const l=o[a];if(l===void 0){o[a]=c;continue}const d=Array.isArray(l)?l:[l],f=Array.isArray(c)?c:[c],u=[...d];for(const p of f)u.some(g=>g===p)||u.push(p);o[a]=u.length===1?u[0]:u}}return r.map(i=>t.get(i)).filter(i=>i!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,r){if(t){const i=e[t.name];return r?this.normalizeLinkValue(i):this.normalizeLiteralValue(i)}return r?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],r=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(r){t.push(r);const i=this.extractFragment(r);i&&!t.includes(i)&&t.push(i)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const r=[];for(const i of t){const s=e[i.name];if(s==null)continue;const o=a=>{const c=this.normalizeLinkValue(a)??(typeof a=="string"?a:void 0);c&&r.push(c)};Array.isArray(s)?s.forEach(o):o(s)}return r}groupRowsByIri(e){const t=new Map;for(const r of e){const i=this.normalizeLinkValue(r["@id"])??this.normalizeLinkValue(r.uri)??(typeof r["@id"]=="string"?r["@id"]:void 0);if(!i)continue;const s=t.get(i)??[];s.push(r),t.set(i,s)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$7=entityKind;PodDatabase[_a$7]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(n){return!!n&&typeof n=="object"&&n.kind==="aggregate"}function inferSPARQLQueryType(n){const r=n.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(r){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return r;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(n,e,t){const r=n?`${n}.${e}`:e;return t==null?new UnaryExpression("IS NULL",r):Array.isArray(t)?new BinaryExpression(r,"IN",t):new BinaryExpression(r,"=",t)}function buildConditionTreeFromObject(n,e){if(!n)return;const t=Object.entries(n);if(t.length===0)return;const r=t.map(([i,s])=>createLiteralCondition(e,i,s));return r.length===1?r[0]:new LogicalExpression("AND",r)}function resolveRowSubject(n){if(!(!n||typeof n!="object")){if(typeof n["@id"]=="string"&&n["@id"].length>0)return n["@id"];if(typeof n.subject=="string"&&n.subject.length>0)return n.subject;if(typeof n.uri=="string"&&n.uri.length>0)return n.uri;if(typeof n.source=="string"&&n.source.length>0)return n.source;if(typeof n.id=="string"&&n.id.length>0)return n.id}}function orderRowsBySubjects(n,e){if(!n.length||!e.length)return n;const t=new Map,r=[];for(const s of n){const o=resolveRowSubject(s);if(!o){r.push(s);continue}const a=t.get(o)??[];a.push(s),t.set(o,a)}const i=[];for(const s of e){const o=t.get(s);o?.length&&(i.push(...o),t.delete(s))}for(const s of t.values())i.push(...s);return i.push(...r),i}function isSelectFieldMap(n){return!!n&&typeof n=="object"&&!(n instanceof PodColumnBase)&&!(n instanceof PodTable)&&!("aggregateType"in n)}function resolveFieldBindingCandidates(n,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[r,i]=e.split(".",2);i&&(t.add(`${r}.${i}`),t.add(i))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(n){if(n==null)return!0;if(Array.isArray(n))return n.length===0;if(typeof n=="object"){const e=Object.values(n);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(n,e){const t=e.config.name,r={};let i=!1;for(const s of Object.keys(e.columns)){const a=(t?[`${t}.${s}`,s]:[s]).find(c=>n[c]!==void 0);r[s]=a?n[a]:void 0,r[s]!==void 0&&(i=!0)}return i?r:null}function projectFieldValue(n,e,t){if(t instanceof PodTable)return projectTableRow(n,t);if(isSelectFieldMap(t)){const r={};for(const[i,s]of Object.entries(t))r[i]=projectFieldValue(n,i,s);return isEmptyProjectedValue(r)?null:r}for(const r of resolveFieldBindingCandidates(e,t))if(n[r]!==void 0)return n[r];return n[e]}function projectReturningRow(n,e){if(!e||e===!0)return n;const t={};for(const[r,i]of Object.entries(e))t[r]=projectFieldValue(n,r,i);return t}function projectReturningRows(n,e){return!e||e===!0?n:n.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,r,i){const s=i?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const d=this.resolveBaseRelativeSubjectId(e,o);if(d)return d;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const a=this.getEffectivePattern(e),c=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(c,a);const l=this.applyTemplate(a,t,r,e,s);return l===null?this.generateFallbackUri(c,a,r):this.isAbsoluteUri(l)?l:this.combineBaseAndPattern(c,l)}parseSubject(e,t){if(!e)return null;const r=e.indexOf("#"),i=r!==-1,s=i?e.slice(0,r):e,o=i?e.slice(r+1):void 0,a=this.extractPublicId(e,t),c=this.getResourceMode(t);return{uri:e,resourceUrl:s,fragment:o,id:a,mode:c}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const i=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(i)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,r,i){const s=r["@id"]??r.id;return typeof s=="string"?s:`${this.getResourceUrl(e)}#${t}-${i+1}`}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,r){const i=String(e??""),s=r?.record&&typeof r.record=="object"?r.record:void 0;if(this.isAbsoluteUri(i))return i;if(i.startsWith("/")||i.startsWith("#")){const d=r?.baseUri||this.podUrl;if(d)try{return new URL(i,d).toString()}catch{}throw new Error(`Cannot resolve relative URI "${i}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const d=this.getTableUriInfo(o);if(d)return this.buildFullUri(i,d.baseUrl,d.subjectTemplate,o,r,s);throw new Error(`Cannot resolve URI "${i}": linked table "${o.config?.name}" has no base configured.`)}const a=t.getLinkTableName?.();if(a){if(r?.tableNameRegistry){const f=r.tableNameRegistry.get(a);if(f){const u=this.getTableUriInfo(f);if(u)return this.buildFullUri(i,u.baseUrl,u.subjectTemplate,f,r,s)}}const d=r?.tableNameRegistry?Array.from(r.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${i}": table "${a}" not found in schema. Available tables: ${d}`)}const c=t.getLinkTarget?.();if(c){if(!r?.tableRegistry)throw new Error(`Cannot resolve URI "${i}" (links to ${c}): tableRegistry not configured. Ensure the schema is properly registered.`);const d=r.tableRegistry.get(c);if(d&&d.length>0){if(d.length>1){const p=d.map(g=>g.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${c}" has multiple tables [${p}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const f=d[0],u=this.getTableUriInfo(f);if(u)return this.buildFullUri(i,u.baseUrl,u.subjectTemplate,f,r,s)}throw new Error(`Cannot resolve URI "${i}": class "${c}" not found in tableRegistry. Available classes: ${Array.from(r.tableRegistry.keys()).join(", ")||"(none)"}`)}const l=r?.baseUri||this.podUrl;if(l&&this.isAbsoluteUri(l)){const d=l.endsWith("/")?l:`${l}/`;return this.buildFullUri(i,d)}throw new Error(`Cannot resolve URI "${i}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const r=e.getLinkTable?.()||e.options?.linkTable;if(r)return r;const i=e.getLinkTableName?.()||e.options?.linkTableName;if(i&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(i);if(o)return o}const s=e.getLinkTarget?.()||e.options?.linkTarget;if(s&&t?.tableRegistry){const o=t.tableRegistry.get(s);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,r){if(e?.startsWith("/")){const o=r?.baseUri||this.podUrl;if(o){const a=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const i=this.findTargetTable(t,r);if(!i)return e;const s=this.extractTemplateIdFromSubject(e,i);return s||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const r=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:r}}buildFullUri(e,t,r,i,s,o){const a=String(e??"");if(!r){const u=this.combineBaseAndResourceId(t,a);return this.assertNoUnresolvedTemplate(u,void 0,i),u}if(!UUID_REGEX.test(a)&&a.includes("/")&&!a.includes("{")){const u=`${t}${a}`;return this.assertNoUnresolvedTemplate(u,r,i),u}const c=this.buildTemplateRecord(a,r,i,s,o),l=this.applyTemplate(r,c,void 0,i,!0,s);if(l===null)throw new Error(`[UriResolver] Failed to resolve URI template "${r}" for table "${i?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(l))return this.assertNoUnresolvedTemplate(l,r,i),l;if(l.startsWith("#")){const p=`${t.endsWith("/")?t.slice(0,-1):t}${l}`;return this.assertNoUnresolvedTemplate(p,r,i),p}const f=`${t.endsWith("/")?t:`${t}/`}${l}`;return this.assertNoUnresolvedTemplate(f,r,i),f}buildTemplateRecord(e,t,r,i,s){const o={...s??{}};o.id=e;for(const a of t.matchAll(/\{([^}]+)\}/g)){const l=this.parseTemplateVariable(a[1]).field;if(l==="id"||l==="index"||l in o)continue;const d=this.resolveTemplateVariable(l,r,i,s);d!=null&&d!==""&&(o[l]=d)}return o}resolveTemplateVariable(e,t,r,i){if(!i||typeof i!="object")return;if(e in i){const c=t?.columns?.[e];return this.normalizeValue(i[e],c,r)}const s=`${e}Id`;if(s in i)return String(i[s]);const o=t?.columns?.[e],a=o?this.findTargetTable(o,r):void 0;if(a)for(const[c,l]of Object.entries(i)){const d=r?.currentTable?.columns?.[c];if((d?this.findTargetTable(d,r):void 0)===a)return this.normalizeValue(l,o,r)}}assertNoUnresolvedTemplate(e,t,r){if(/\{[^}]+\}/.test(e)){const i=r?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${i}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const r=e.config?.subjectTemplate;if(r&&r.trim().length>0)return r}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const r=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>this.parseTemplateVariable(i[1]).field);return t==="#{id}"||t.startsWith("#")&&r.length===1&&r[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const r=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${r}${t}`:null;if(r.endsWith("/"))return`${r}${t}`;const i=r.lastIndexOf("/");return`${i>=0?r.slice(0,i+1):`${r}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,r){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,r):String(e)}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:r}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,r,i){let s=this.normalizeValue(e,r,i);for(const o of t.transforms){if(o==="id"){s=r&&this.isLinkColumn(r)?this.extractLinkId(s,r,i):s;continue}o==="slug"&&(s=this.slugifyValue(s))}return s}applyTemplate(e,t,r,i,s=!0,o){if(!e.includes("{"))return e;const a=this.createTimeContext(t),c=[],l=e.replace(/(#?)\{([^}]+)\}/g,(d,f,u)=>{const p=this.parseTemplateVariable(u),g=p.field;if(g in a)return f+a[g];if(g==="index"&&r!==void 0)return f+String(r+1);let y=t[g];if(g==="id"&&y==null&&(y=t["@id"]??t.uri),y==null)return c.push(u),d;const w=i?.columns?.[g],_=o??(i?{tableRegistry:i[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:i[Symbol.for("drizzle:tableNameRegistry")]}:void 0),R=this.applyTransforms(y,p,w,_);return f==="#"&&R.startsWith("#")?f+R.slice(1):f+R});if(c.length>0){if(s){const d=i?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${d}": [${c.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return l}createTimeContext(e){let t;const r=e.createdAt??e.created_at??e.dateCreated;r instanceof Date?t=r:typeof r=="string"||typeof r=="number"?t=new Date(r):t=new Date;const i=t.getUTCFullYear().toString(),s=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),a=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:i,MM:s,dd:o,timestamp:a}}generateFallbackUri(e,t,r){const i=r!==void 0?`row-${r+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${i}`:`${e.endsWith("/")?e:`${e}/`}${i}.ttl`}extractRelativeSubjectId(e,t){const r=t.config?.base??"";let i="";if(r&&e.includes(r)){const s=e.indexOf(r);i=e.substring(s+r.length),i.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(i=`${r.split("/").filter(Boolean).pop()??""}${i}`),i.startsWith("/")&&(i=i.substring(1))}else if(!r)i=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${r}" not found in URI "${e}"`),"";return i}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const r=this.extractRelativeSubjectId(e,t),i=t.config?.subjectTemplate;return i?this.extractIdFromTemplate(r,i):r}extractIdFromTemplate(e,t){let r=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");r=`^${r}$`;try{const i=new RegExp(r),s=e.match(i);if(s&&s.groups?.id)return s.groups.id;if(s&&s[1])return s[1]}catch{}return null}}function isOrderByExpression(n){if(!n||typeof n!="object")return!1;const e=n;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(n){return n==="id"||n==="@id"||n.endsWith(".id")||n.endsWith(".@id")}function isReservedIdentifierOperand(n){if(n instanceof PodColumnBase){const e=n;return n.name==="id"||n.options?.predicate==="@id"||e._virtualId===!0}return typeof n=="string"?isReservedIdentifierKey(n):!1}function conditionTargetsReservedIdentifier(n){return n.type==="binary_expr"?!!(isReservedIdentifierOperand(n.left)||isReservedIdentifierOperand(n.right)):n.type==="logical_expr"?n.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):n.type==="unary_expr"?n.value!=null&&typeof n.value=="object"&&"type"in n.value&&conditionTargetsReservedIdentifier(n.value):!1}function createWhereIdentifierError(n){switch(n){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(n,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(n))}}function assertPublicWhereCondition(n,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(n))}var define_process_env_default$2={},_a$6;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereByIri(e){return this.processWhereObject({"@id":e}),this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,r=e.right,i=e.operator,s=typeof t=="string"?t:t?.name;if(i==="="&&s&&r!==void 0)return{[s]:r}}if(e.type==="logical_expr"){const t=e.operator,r=e.expressions;if(t==="AND"&&r){const i={};for(const s of r){const o=this.convertQueryConditionToSimple(s);if(!o||Object.keys(o).length===0)return{};for(const[a,c]of Object.entries(o))i[a]=c}return i}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const r=t.table;if(r)return this.tableAliases.get(r)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(r=>this.resolveColumnReference(r));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,r){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const i=this.ensureAliasForTable(t),s=e==="crossJoin"?void 0:this.resolveJoinConditions(r,i);return this.joins.push({type:e,table:t,alias:i,rawCondition:r,resolvedConditions:s}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const r=e.config.name||"table",i=this.aliasUsage.get(r)??0,s=i+1;this.aliasUsage.set(r,s);const o=i===0?r:`${r}_${s}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const r=Object.entries(e);if(r.length===0)throw new Error("JOIN condition cannot be empty");return r.map(([i,s])=>{const o=this.resolveColumnReference(i),a=this.resolveColumnReference(s);if(o.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:a}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const s=(e.operator??"").toUpperCase(),o=e.expressions??[];if(s!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(a=>this.resolveJoinConditionExpression(a,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const r=this.getConditionColumnReference(e.left),i=this.getConditionColumnReference(e.right);if(!r||!i)throw new Error("JOIN equality must compare two table columns");if(r.alias!==t&&i.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:r,right:i}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const r=t??this.primaryAlias,i=r?this.aliasToTable.get(r):void 0;if(i&&e in(i.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const r=e.table;if(!r)throw new Error(`Column ${e.name} is not associated with a table`);const i=this.ensureAliasForTable(r);return{table:r,alias:i,column:e.name}}if(typeof e=="string"){const{alias:r,column:i}=this.parseColumnReferenceString(e),s=r??t??this.primaryAlias;if(!s)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(s);if(!o)throw new Error(`Unknown table alias "${s}" in column reference "${e}"`);return{table:o,alias:s,column:i}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[r,i]=t.split(".",2);return{alias:r,column:i}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[r,i]of Object.entries(e)){const{alias:s,column:o}=this.parseColumnReferenceString(r),a=s??this.primaryAlias;if(!a||a===this.primaryAlias||!this.aliasToTable.has(a)){t[o]=i;continue}this.joinFilters.push(createLiteralCondition(a,o,i))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const r=this.convertQueryConditionToSimple(e);Object.keys(r).length>0&&(this.whereConditions=r)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(r=>({type:r.type,table:r.table,alias:r.alias,conditions:(r.resolvedConditions??[]).map(({left:i,right:s})=>({left:i,right:s}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(r=>({rawColumn:r.column,direction:r.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const r=typeof e=="string"?e:e.name;if(!r)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:r,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const r=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(r);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:r,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,r=this.joins.length>0,i=this.shouldUseAggregateFallback(),s=this.shouldUseProjectionFallback(),o=r||i;(r||i||s)&&(e.select=void 0,e.selectAll=!0);const a=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...r?{joins:void 0,joinFilters:void 0}:{},...i?{groupBy:void 0,having:void 0}:{}}:r?{...e,joins:void 0,joinFilters:void 0}:e,c={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(c.plan=a,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let l;if(!r&&!i&&!s?(this.selectedFields&&(c.select=this.selectedFields),l=await this.session.execute(c),l=this.applySubjectMetadata(l)):(r?c.select=void 0:!i&&!s?c.select=this.selectedFields:c.select=void 0,l=await this.session.execute(c),r||(l=this.applySubjectMetadata(l)),r&&(l=this.normalizeBaseRows(l),l=this.mergeRowsBySubject(l),l=await this.applyJoinFallback(l),l=this.applyJoinFilters(l))),i){let f=this.handleAggregateFallback(l);return f=this.applyHavingFilter(f),o&&(f=this.applyDeferredOrderBy(f),f=this.applyDeferredOffsetAndLimit(f)),f}let d=l;return r||(d=this.mergeRowsBySubject(d)),this.selectedTable&&(d=await this.hydrateInlineColumns(d,this.selectedTable,!r)),r&&(d=this.applyDeferredOrderBy(d)),this.selectedFields&&(d=d.map(f=>this.projectSelectedRow(f))),d=this.applyDistinctRows(d),r||(d=this.mergeRowsBySubject(d)),r&&(d=this.applyDeferredOffsetAndLimit(d)),d}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,r=!0){const i={};for(const[s,o]of Object.entries(t))i[s]=this.projectFieldValue(e,s,o,r);return i}projectFieldValue(e,t,r,i=!0){if(isAggregateExpression(r))return i?e[t]:void 0;if(r instanceof PodTable)return this.projectTableValue(e,r);if(this.isSelectFieldMap(r)){const s=this.collectSelectionAliases(r),o=s.size===1&&!s.has(this.primaryAlias??""),a=this.projectFieldMap(e,r,!o);if(s.size===1){const[c]=Array.from(s);if(c&&c!==this.primaryAlias&&this.isProjectedValueEmpty(a))return null}return a}for(const s of this.resolveFieldBindingCandidates(t,r))if(e[s]!==void 0)return e[s];return i?e[t]:void 0}projectTableValue(e,t){const r=this.tableAliases.get(t)??t.config.name,i={};let s=!1;for(const o of Object.keys(t.columns)){const c=(r===this.primaryAlias?[o,`${r}.${o}`]:[`${r}.${o}`]).find(l=>e[l]!==void 0);i[o]=c?e[c]:void 0,i[o]!==void 0&&(s=!0)}return r!==this.primaryAlias&&!s?null:i}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:r}=this.parseColumnReferenceString(e);return new Set(r?[r]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const r of Object.values(e))for(const i of this.collectSelectionAliases(r))t.add(i);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(r=>this.isProjectedValueEmpty(r))}return!1}resolveFieldBindingCandidates(e,t){const r=new Set;if(typeof t=="string"){const{alias:i,column:s}=this.parseColumnReferenceString(t);r.add(t),r.add(s),i&&r.add(`${i}.${s}`)}else if(t instanceof PodColumnBase){const i=this.resolveColumnReference(t);r.add(`${i.alias}.${i.column}`),(!i.alias||i.alias===this.primaryAlias)&&r.add(t.name)}else if(t&&typeof t=="object"){const i=t.name;typeof i=="string"&&r.add(i)}return Array.from(r)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[r,i]of Object.entries(this.selectedFields))isAggregateExpression(i)&&(t[r]=this.computeAggregateValue(i,e));return t}computeAggregateValue(e,t){const r=this.resolveAggregateColumnRef(e);if(!r)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(r,t,!!e.distinct).length;case"sum":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:i.reduce((s,o)=>s+o,0)}case"avg":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:i.reduce((o,a)=>o+a,0)/i.length}case"min":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:Math.min(...i)}case"max":{const i=this.collectNumericValues(r,t,!!e.distinct);return i.length===0?null:Math.max(...i)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const r=t.name;if(typeof r=="string")return this.resolveColumnReference(r)}}}collectValuesForCount(e,t,r){const i=t.map(a=>this.getRowValueForColumn(a,e)).filter(a=>a!=null);if(!r)return i;const s=new Set,o=[];for(const a of i){const c=this.serializeValueForKey(a);s.has(c)||(s.add(c),o.push(a))}return o}collectNumericValues(e,t,r){const i=[],s=new Set;for(const o of t){const a=this.getRowValueForColumn(o,e);if(a==null)continue;const c=Number(a);if(!Number.isNaN(c))if(r){const l=this.serializeValueForKey(c);s.has(l)||(s.add(l),i.push(c))}else i.push(c)}return i}countDistinctRows(e){const t=new Set;for(const r of e){const i=this.serializeValueForKey(r);t.add(i)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const r of e){const i=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(r,o))),s=JSON.stringify(i);t.has(s)||t.set(s,r)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const i of e){const s=this.groupByColumns.map(a=>this.serializeValueForKey(this.getRowValueForColumn(i,a))),o=JSON.stringify(s);t.has(o)||t.set(o,{rows:[],first:i}),t.get(o)?.rows.push(i)}const r=[];for(const{rows:i,first:s}of t.values()){const o=this.buildAggregateRow(i),a={};for(const[c,l]of Object.entries(this.selectedFields))if(isAggregateExpression(l))a[c]=o[c];else{const d=this.resolveSelectFieldColumn(l);a[c]=d?this.getRowValueForColumn(s,d):void 0}r.push(a)}return r}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const r=this.resolveSelectFieldColumn(t);if(!r)continue;const i=`${r.alias}.${r.column}`;if(!e.includes(i))throw new Error(`Column ${i} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(i=>isAggregateExpression(i)),r=e.some(i=>!isAggregateExpression(i));return t&&r}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const r=t.value;return typeof r=="string"&&r.length>0?r:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const r=this.extractIdFromSubject(t,this.selectedTable);r!==void 0&&(e.id=r)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(r=>{const i={...r};for(const[o,a]of Object.entries(r))o!==`${t}.${o}`&&(i[`${t}.${o}`]=a);const s=this.extractSubjectValue(r);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${t}.subject`]=s,i[`${t}.@id`]=s,i[`${t}.uri`]=s;const o=this.extractIdFromSubject(s,this.selectedTable);o!==void 0&&(i.id===void 0&&(i.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||i[`${t}.id`]===void 0)&&(i[`${t}.id`]=o))}return i})}async hydrateInlineColumns(e,t,r=!0){if(!e.length)return e;const i=Object.values(t.columns??{}).filter(w=>this.isInlineObjectColumn(w));if(i.length===0)return e;r&&(e=this.mergeRowsBySubject(e));const s=new Map;i.forEach(w=>{const _=w.getPredicate(t.config.namespace);s.set(_,w)});const o=Array.from(new Set(e.map(w=>this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id)).filter(w=>!!w)));if(o.length===0||s.size===0)return e;const a=Array.from(s.keys()).map(w=>`<${w}>`).join(" "),c=this.session.getDialect().getSPARQLExecutor(),l=[],d=new Map;for(const w of o){const _=this.inferSourceFromChild(w,t),R=d.get(_)??[];R.push(w),d.set(_,R)}for(const[w,_]of d.entries()){const b={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
33
+ VALUES ?parent { ${_.map(P=>`<${P}>`).join(" ")} }
34
+ VALUES ?linkPred { ${a} }
35
+ ?parent ?linkPred ?child .
36
+ OPTIONAL { ?child ?pred ?obj . }
37
+ }`,prefixes:{}},C=await c.executeQueryWithSource(b,w);l.push(...C)}const f=t.config.namespace?.uri??t.config.namespace,u=new Map,p=new Map;l.forEach(w=>{const _=this.normalizeInlineIri(w.parent),R=this.normalizeInlineIri(w.linkPred),b=this.normalizeInlineIri(w.child),C=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!_||!R)return;const H=s.get(R);if(H){const V=u.get(_)??new Map,q=V.get(H.name)??[];b&&!q.includes(b)&&q.push(b),V.set(H.name,q),u.set(_,V)}if(!b||!C)return;const M=p.get(b)??{"@id":b,id:this.extractIdFromSubject(b,t)},re=this.normalizeInlinePredicateKey(C,f);if(P===void 0){p.set(b,M);return}const he=M[re];he===void 0?M[re]=P:Array.isArray(he)?M[re]=[...he,P]:M[re]=[he,P],p.set(b,M)});const g=w=>{if(Array.isArray(w))return w.map(R=>this.normalizeInlineIri(R)).filter(R=>!!R);const _=this.normalizeInlineIri(w);return _?[_]:[]},y=(w,_,R)=>{const b=w?u.get(w)?.get(R.name)??[]:[],P=(b.length>0?b:g(_)).map(H=>p.get(H)??{"@id":H,id:this.extractIdFromSubject(H,t)});return R.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const _=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);i.forEach(R=>{w[R.name]=y(_,w[R.name],R)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const r=e.lastIndexOf("#");if(r!==-1&&r<e.length-1)return e.slice(r+1);const i=e.lastIndexOf("/");return i!==-1&&i<e.length-1?e.slice(i+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((r,i)=>{for(const s of this.orderByClauses){const o=this.getOrderByValue(r,s.column),a=this.getOrderByValue(i,s.column),c=this.compareOrderByValues(o,a);if(c!==0)return s.direction==="desc"?-c:c}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,r=[];for(const i of e){const s=this.serializeValueForKey(i);t.has(s)||(t.add(s),r.push(i))}return r}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,r=t>0?e.slice(t):e;return this.limitCount===void 0?r:r.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const r=Object.keys(e).find(i=>i.endsWith(`.${t}`));if(r)return e[r]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,r=[];return e.forEach(s=>{const o=this.normalizeInlineIri(s["@id"])??this.normalizeInlineIri(s.subject)??this.normalizeInlineIri(s.uri)??(typeof s.id=="string"?s.id:void 0);if(define_process_env_default$2.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",o),!o){r.push(`__anon_${r.length}`),t.set(r[r.length-1],{...s});return}if(!t.has(o)){const l={...s};Object.entries(l).forEach(([d,f])=>{if(f===void 0)return;const u=this.getColumnDefinitionForRowKey(d);(u?.options?.isArray||u?.dataType==="array")&&!Array.isArray(f)&&(l[d]=[f])}),t.set(o,l),r.push(o);return}const a=t.get(o),c=l=>{if(l instanceof Date)return`date:${l.toISOString()}`;if(typeof l=="string")return`str:${l}`;if(typeof l=="number")return`num:${l}`;if(typeof l=="boolean")return`bool:${l}`;if(l==null)return"nil";try{return`obj:${JSON.stringify(l)}`}catch{return`obj:${String(l)}`}};Object.entries(s).forEach(([l,d])=>{if(d===void 0)return;const f=a[l];if(f===void 0){a[l]=d;return}const u=Array.isArray(f)?f:[f],p=Array.isArray(d)?d:[d],g=[...u];p.forEach(_=>{const R=c(_);g.some(b=>c(b)===R)||g.push(_)});const y=this.getColumnDefinitionForRowKey(l),w=y?.options?.isArray||y?.dataType==="array";!w&&g.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${l}' on subject '${o}'. Using first value.`),a[l]=g[0]):w?a[l]=g:a[l]=g.length===1?g[0]:g})}),r.map(s=>t.get(s))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,r]=e.split(".",2);if(!(!t||!r))return t===this.primaryAlias?this.selectedTable?.columns[r]:this.aliasToTable.get(t)?.columns?.[r]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const r=e.indexOf("#");if(r>0)return e.slice(0,r);const i=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return i?i.startsWith("http")?i:`${this.session.getDialect().getPodUrl()}${i.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){if(!e)return!1;if(e.dataType==="object"||e.dataType==="json")return!0;if(e.dataType==="array"){const t=e.elementType??e.options?.baseType;return t==="object"||t==="json"}return!1}async applyJoinFallback(e){let t=e;for(const r of this.joins){const i=await this.fetchJoinRows(r,t);t=this.mergeRowsWithJoin(t,r,i)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const g=await this.session.select().from(e.table);return this.normalizeJoinRows(e,g)}const r=e.resolvedConditions??[];if(r.length===0)return[];const[i]=r,s=i.left.alias===e.alias?i.left:i.right,o=s===i.left?i.right:i.left,a=new Map;for(const g of t){const y=this.getRowValueForColumn(g,o);if(y==null)continue;const w=this.serializeValueForKey(y);a.has(w)||a.set(w,y)}if(a.size===0)return[];const c=Array.from(a.values()),l=()=>this.session.select().from(e.table),d=e.table.getColumn(s.column),f=this.buildExactJoinLookupConditions(e,t);if(f&&f.length>0){const g=[];for(const y of f){const w=l(),R=await(conditionTargetsReservedIdentifier(y)?w.applyInternalQueryCondition(y):w.where(y));g.push(...R)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,g))}const u=this.buildJoinLookupCondition(d,c);if(u){const g=l(),w=await(conditionTargetsReservedIdentifier(u)?g.applyInternalQueryCondition(u):g.where(u));return this.normalizeJoinRows(e,w)}const p=await l();return this.normalizeJoinRows(e,p)}buildExactJoinLookupConditions(e,t){const r=e.resolvedConditions??[];if(r.length===0)return;const[i]=r,s=i.left.alias===e.alias?i.left:i.right,o=s===i.left?i.right:i.left,a=this.getRequiredSubjectTemplateVariables(e.table),c=s.column==="id"&&a.length>0;if(!c&&r.length===1)return;const l=new Map;for(const u of r){const p=u.left.alias===e.alias?u.left:u.right;l.set(p.column,u)}const d=[],f=new Set;for(const u of t){const p=this.getRowValueForColumn(u,o);if(p==null)continue;const g=typeof p=="string"&&this.isAbsoluteIri(p),y=[],w=[];let _=!1;for(const b of r){const C=b.left.alias===e.alias?b.left:b.right,P=C===b.left?b.right:b.left,H=this.getRowValueForColumn(u,P);if(H==null){if(c&&!g&&a.includes(C.column))throw new Error(this.buildMissingJoinLocatorError(e,a.filter(re=>{const he=l.get(re);if(!he)return!0;const q=(he.left.alias===e.alias?he.left:he.right)===he.left?he.right:he.left,ie=this.getRowValueForColumn(u,q);return ie==null})));_=!0;break}const M=e.table.getColumn(C.column);if(!M){_=!0;break}y.push(eq(M,H)),w.push(`${C.column}:${this.serializeValueForKey(H)}`)}if(_)continue;if(c&&!g){const b=a.filter(C=>{const P=l.get(C);if(!P)return!0;const M=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,re=this.getRowValueForColumn(u,M);return re==null});if(b.length>0)throw new Error(this.buildMissingJoinLocatorError(e,b))}if(y.length===0)continue;const R=w.join("|");f.has(R)||(f.add(R),d.push(y.length===1?y[0]:and(...y)))}return d.length>0?d:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(r=>r[1].split("|")[0]?.trim()||r[1]).filter(Boolean))).filter(r=>r!=="id"&&r!=="index"&&r!=="yyyy"&&r!=="MM"&&r!=="dd"&&r!=="HH"&&r!=="mm"&&r!=="ss"&&r!=="timestamp"&&r!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const r=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",i=Array.from(new Set(t)),s=i[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${r}" because locator variable(s) [${i.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${s}, join.${s})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(r=>{const i={};for(const[o,a]of Object.entries(r))i[`${e.alias}.${o}`]=a;const s=this.extractSubjectValue(r);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${e.alias}.subject`]=s,i[`${e.alias}.@id`]=s,i[`${e.alias}.uri`]=s;const o=this.extractIdFromSubject(s,e.table);o!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||i[`${e.alias}.id`]===void 0)&&(i[`${e.alias}.id`]=o)}return i})}mergeRowsWithJoin(e,t,r){if(t.type==="crossJoin"){if(e.length===0||r.length===0)return[];const d=[];for(const f of e)for(const u of r)d.push({...f,...u});return d}const i=t.resolvedConditions??[];if(i.length===0)return e;const[s]=i,o=s.left.alias===t.alias?s.left:s.right,a=o===s.left?s.right:s.left,c=new Map;for(const d of r){const f=this.getRowValueForColumn(d,o);if(f==null)continue;const u=this.serializeValueForKey(f);c.has(u)||c.set(u,[]),c.get(u).push(d)}const l=[];for(const d of e){const f=this.getRowValueForColumn(d,a),u=this.serializeValueForKey(f),g=(f!=null?c.get(u)??[]:[]).filter(y=>this.joinRowMatchesAllConditions(d,y,t.alias,i));if(g.length===0){if(t.type==="innerJoin")continue;l.push({...d,...this.createEmptyJoinRow(t)});continue}for(const y of g)l.push({...d,...y})}return l}joinRowMatchesAllConditions(e,t,r,i){return i.every(s=>{const o=s.left.alias===r?s.left:s.right,a=o===s.left?s.right:s.left,c=this.getRowValueForColumn(e,a),l=this.getRowValueForColumn(t,o);return c==null||l===void 0||l===null?!1:this.serializeValueForKey(c)===this.serializeValueForKey(l)})}createEmptyJoinRow(e){const t={};for(const r of Object.keys(e.table.columns))t[`${e.alias}.${r}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(r=>this.evaluateCondition(t,r)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const r=t.left,i=t.right,s=t.operator;if(!r)return!0;const o=this.resolveConditionOperandValue(e,r,this.primaryAlias),a=this.resolveConditionOperandValue(e,i);switch(s.toUpperCase()){case"=":return o===a;case"!=":case"<>":return o!==a;case">":return Number(o)>Number(a);case">=":return Number(o)>=Number(a);case"<":return Number(o)<Number(a);case"<=":return Number(o)<=Number(a);case"IN":return Array.isArray(a)&&a.includes(o);case"NOT IN":return Array.isArray(a)&&!a.includes(o);case"LIKE":return typeof o=="string"&&typeof a=="string"&&this.computeLikeMatch(o,a);default:return!0}}evaluateUnaryCondition(e,t){const r=t.operator,i=t.value;if(r.toUpperCase()==="NOT")return!this.evaluateCondition(e,i);if(!i)return!0;const s=this.resolveConditionOperandValue(e,i,this.primaryAlias);switch(r.toUpperCase()){case"IS NULL":return s==null;case"IS NOT NULL":return s!=null;default:return!0}}evaluateLogicalCondition(e,t){const r=t.operator,i=t.expressions??[];return r.toUpperCase()==="AND"?i.every(s=>this.evaluateCondition(e,s)):r.toUpperCase()==="OR"?i.some(s=>this.evaluateCondition(e,s)):!0}resolveConditionOperandValue(e,t,r){if(t instanceof SelectionAliasExpression)return e[t.alias];const i=this.getConditionColumnReference(t,r);return i?this.getRowValueForColumn(e,i):t}getColumnKeyCandidates(e){const t=[],r=this.primaryAlias;return e.alias===r&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const r=this.getColumnKeyCandidates(t);for(const i of r)if(i in e)return e[i]}shouldUseSubjectIdentityColumn(e,t){const r=e?.columns?.[t];return!!(r?._virtualId||r?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const s=parsePodResourceRef(t,e)?.resourceId;if(s)return s}if(t){const s=this.session.getDialect?.(),a=(s?.getUriResolver?.()??new UriResolverImpl(s?.getPodUrl?.()??"")).parseSubject(e,t);if(a&&a.id)return a.id}const r=e.indexOf("#");if(r!==-1)return e.slice(r);const i=e.lastIndexOf("/");if(i!==-1){const s=e.slice(i+1);if(s.length>0)return s}}computeLikeMatch(e,t){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(s=>s.id||s["@id"]).filter(s=>typeof s=="string"&&s.length>0)}then(e,t){return this.execute().then(e,t)}}_a$6=entityKind;SelectQueryBuilder[_a$6]="SelectQueryBuilder";var _a$5;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const r=this.getRowsWithDefaults();return{table:this.table,rows:r}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const r=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(r);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:r,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],r={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},i=await this.session.execute(r),s=this.returningFields?await this.fetchReturningRowsBySubjects(t):i;return await this.runAfterInsertHooks(s),s}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(r=>generateSubjectUri(r,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const r=this.buildHookContext();if(!r){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const i of e)try{await t.afterInsert(r,i)}catch(s){console.error("[InsertQueryBuilder] afterInsert hook failed:",s)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(r=>this.applyDefaultValues(r))}applyDefaultValues(e){const t={...e},r=this.table?.columns??{},i=Object.entries(r);for(const[s,o]of i.filter(([,a])=>!this.isPrimaryKeyColumn(a)))this.applyDefaultValue(t,s,o);for(const[s,o]of i.filter(([,a])=>this.isPrimaryKeyColumn(a)))this.applyDefaultValue(t,s,o);return t}applyDefaultValue(e,t,r){if(e[t]===void 0){const i=r.options?.defaultValue;i!==void 0&&(e[t]=this.resolveDefaultValue(i,r,e))}}resolveDefaultValue(e,t,r){const i=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&i)return renderDefaultIdTemplate(e,{key:i,row:r,resource:this.table});if(typeof e!="function")return e;const s=e;return s.length===0?s():s(i,r)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$5=entityKind;InsertQueryBuilder[_a$5]="InsertQueryBuilder";var _a$4;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const r=this.normalizeWhereConditionsForUpdate();if(!r)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:r}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,r=e.right,i=typeof t=="string"?t:t?.name;if(i&&r!==void 0)return{[i]:r}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const r=this.toIR();return t.convertUpdate(r.data,r.where,r.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),r=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(a=>resolveRowSubject(a)).filter(a=>typeof a=="string"&&a.length>0),i={type:"update",table:this.table,data:e.data,where:e.where,plan:e},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(r):s;return await this.runAfterUpdateHooks(o),o}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),r=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),i=Object.entries(this.updateData??{}).filter(([,s])=>Array.isArray(s));return i.length===0?r:r.map(s=>{const o={...s};for(const[a,c]of i)a in o&&(o[a]=[...c]);return o})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const r=this.buildHookContext();if(!r){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const i=this.updateData??{};for(const s of e)try{await t.afterUpdate(r,s,i)}catch(o){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;UpdateQueryBuilder[_a$4]="UpdateQueryBuilder";var _a$3;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const r=this.normalizeWhereConditionsForDelete();return{table:this.table,where:r}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,r=e.right,i=typeof t=="string"?t:t?.name;if(i&&r!==void 0)return{[i]:r}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const r=this.toIR();return t.convertDelete(r.where??{},r.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],r=t.map(a=>resolveRowSubject(a)).filter(a=>typeof a=="string"&&a.length>0),i={type:"delete",table:this.table,where:e.where,plan:e},s=await this.session.execute(i),o=this.returningFields?projectReturningRows(orderRowsBySubjects(t,r),this.returningFields):s;return await this.runAfterDeleteHooks(o),o}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let r=this.session.select().from(this.table);return e&&(r=r.where(e)),await r}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const r=this.buildHookContext();if(!r){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const i of e)try{await t.afterDelete(r,i)}catch(s){console.error("[DeleteQueryBuilder] afterDelete hook failed:",s)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),r=e.getAuthenticatedFetch();return!t||!r?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:r},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$3=entityKind;DeleteQueryBuilder[_a$3]="DeleteQueryBuilder";var _a$2;class PodAsyncSession{constructor(e,t,r={}){this.dialect=e,this._schema=t,this.options=r}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(r){if(t!=="best-effort")throw r;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(r){if(t!=="best-effort")throw r}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const i of e.joins)i?.table&&await this.ensureInitialized(i.table);const r=await this.dialect.query(e);return this.updateSubjectIndex(e,r),r}updateSubjectIndex(e,t){if(e.type==="select")return;const r=this.dialect;if(typeof r.registerResourceSubject!="function"&&typeof r.unregisterResourceSubject!="function")return;const i=this.resolveOperationSubjects(e,t);if(e.type==="delete"){i.forEach(s=>r.unregisterResourceSubject?.(e.table,s));return}i.forEach(s=>r.registerResourceSubject?.(e.table,s))}resolveOperationSubjects(e,t){const r=new Set;for(const i of t){const s=this.getKnownRowIri(i);s&&r.add(s)}if(e.type==="insert"){const i=e.plan;(Array.isArray(i?.rows)?i.rows:[]).forEach(o=>{try{r.add(generateSubjectUri(o,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(r)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const r of["@id","subject","uri","source"]){const i=t[r];if(typeof i=="string"&&/^https?:\/\//.test(i))return i}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$2=entityKind;PodAsyncSession[_a$2]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const r=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(i,s,o){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),r.call(this,i,s,o)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const r=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!r||typeof r.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return r},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("@comunica/query-sparql-solid"),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,r)=>{try{const i=await e(t,r),s=new Map;i.headers&&i.headers.forEach((c,l)=>{s.set(l.toLowerCase(),c||"")});const a={...i,headers:{get:c=>{const l=c.toLowerCase();return s.get(l)||null},has:c=>{const l=c.toLowerCase();return s.has(l)},forEach:c=>{s.forEach((l,d)=>c(l,d))},entries:()=>s.entries(),keys:()=>s.keys(),values:()=>s.values(),[Symbol.iterator]:()=>s.entries(),includes:c=>{if(!c)return!1;for(const[l,d]of Array.from(s.entries()))if(l.toLowerCase().includes(c.toLowerCase())||d.toLowerCase().includes(c.toLowerCase()))return!0;return!1}},status:i.status||200,statusText:i.statusText||"OK",ok:i.ok!==void 0?i.ok:!0,url:i.url||(typeof t=="string"?t:t.toString()),type:i.type||"basic",redirected:i.redirected||!1,body:i.body,bodyUsed:i.bodyUsed||!1,includes:c=>{if(!c)return!1;for(const[l,d]of Array.from(s.entries()))if(l.toLowerCase().includes(c.toLowerCase())||d.toLowerCase().includes(c.toLowerCase()))return!0;return!1},text:async()=>{try{return await i.text()}catch(c){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(c)),""}},json:async()=>{try{return await i.json()}catch(c){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(c)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,r)}catch(c){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(c)),a}}};return a}catch(i){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(i)),i}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},r=this.sources[0];if(!r)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",r)),await this.executeQueryWithSource(t,r)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(s=>{const o=s,a={},c=(l,d)=>{const f=this.extractBindingKeyName(l);f&&(a[f]=this.convertComunicaTerm(d))};if(o&&typeof o.forEach=="function")o.forEach((l,d)=>c(d,l));else if(o&&typeof o.entries=="function")for(const[l,d]of o.entries())c(l,d);else for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&c(l,o[l]);return a})}catch(r){throw console.error("SELECT query failed:",this.formatError(r)),r}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(r){throw console.error("ASK query failed:",this.formatError(r)),r}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const r=[];for(const i of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${i}:`,e.query.substring(0,100)+"...");let s=null;try{const l=await this.fetchFn(i,{method:"HEAD",headers:{Accept:"text/turtle"}});l.ok&&(s=l.headers.get("ETag"),this.logging&&s&&console.log(`[UPDATE] Got ETag for ${i}: ${s}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${i}, continuing without ETag`)}const o={"Content-Type":"application/sparql-update","If-Match":s??"*"},a=async l=>this.fetchFn(i,{method:"PATCH",headers:l,body:e.query}),c=await a(o);if(c.ok)r.push({success:!0,source:i,status:c.status}),await this.invalidateCache(t,i);else if(c.status===409||c.status===412){this.logging&&console.log(`[UPDATE] ${c.status} conflict for ${i}, trying multiple retry strategies`);let l=!1;if(c.status===412)try{const d=await this.fetchFn(i,{method:"HEAD",headers:{Accept:"text/turtle"}});if(d.ok){const f=d.headers.get("ETag");if(f){const u={...o,"If-Match":f},p=await a(u);p.ok&&(r.push({success:!0,source:i,status:p.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,i),l=!0)}}}catch(d){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",d)}if(!l)try{const d=await a({"Content-Type":"application/sparql-update"});d.ok&&(r.push({success:!0,source:i,status:d.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,i),l=!0)}catch(d){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",d)}if(!l)try{if((await this.fetchFn(i,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const f=await this.fetchFn(i,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});f.ok&&(r.push({success:!0,source:i,status:f.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,i),l=!0)}}catch(d){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",d)}if(!l){const d=await c.text();r.push({success:!1,source:i,error:`All retry strategies failed: ${c.status} ${c.statusText}`,details:d})}}else{const l=await c.text();r.push({success:!1,source:i,error:`${c.status} ${c.statusText}`,details:l})}}catch(s){r.push({success:!1,source:i,error:this.formatError(s)})}return r}catch(r){throw console.error("UPDATE query failed:",this.formatError(r)),r}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const r=e.invalidateHttpCache;if(typeof r=="function")try{await r.call(e,t)}catch(i){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(i))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const r=t.datatype.value;if(typeof r=="string"){if(r.includes("#integer")||r.includes("#int"))return parseInt(String(t.value),10);if(r.includes("#decimal")||r.includes("#double"))return parseFloat(String(t.value));if(r.includes("#boolean"))return t.value==="true";if(r.includes("#dateTime"))return new Date(String(t.value));if(r.includes("#json"))try{return JSON.parse(String(t.value))}catch(i){return console.warn("Failed to parse JSON value:",t.value,this.formatError(i)),t.value}else if(r.includes("#jsonArray")||r.includes("solid/terms#jsonArray"))try{const i=JSON.parse(String(t.value));return Array.isArray(i)?i:(console.warn("Expected array but got:",typeof i,i),[i])}catch(i){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(i)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const r=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let i;return t?i=t:i={type:"SELECT",query:`
38
+ SELECT ?subject ?predicate ?object WHERE {
39
+ ?subject ?predicate ?object .
40
+ FILTER(STRSTARTS(STR(?subject), "${r}"))
41
+ }
42
+ `},this.executeQueryWithSource(i,r)}async executeQueryWithSource(e,t,r="auto"){try{const i=await this.initEngine(),s=this.createSourceRef(t,r);if(this.logging&&(console.log(`[Comunica] Executing ${e.type} query on ${t}:`,e.query),console.log("[Debug] sparqlQuery object:",JSON.stringify(e,null,2))),e.type==="SELECT"){const a=await(await i.queryBindings(e.query,{sources:[s],fetch:this.fetchFn})).toArray(),c=a.map(l=>{const d=l,f={};if(this.logging&&a.indexOf(l)===0&&(console.log("[Debug] Binding object:",d),console.log("[Debug] Binding type:",typeof d),console.log("[Debug] Binding constructor:",d.constructor?.name),console.log("[Debug] Binding keys:",Object.keys(d)),console.log("[Debug] Has entries method:",typeof d.entries),console.log("[Debug] Has keys method:",typeof d.keys),console.log("[Debug] Has get method:",typeof d.get)),d.entries&&typeof d.entries=="function")try{for(const[u,p]of d.entries()){const g=this.extractBindingKeyName(u);g&&(f[g]=this.convertComunicaTerm(p))}}catch(u){console.warn("[Warning] binding.entries() failed:",this.formatError(u))}else if(d.keys&&typeof d.keys=="function"&&typeof d.get=="function")try{for(const u of d.keys()){const p=d.get(u);if(p){const g=this.extractBindingKeyName(u);if(!g)continue;const y=this.convertComunicaTerm(p);f[g]=y,this.logging&&a.indexOf(l)===0&&(console.log(`[Debug] Variable: ${g}, Term: ${y}`),console.log("[Debug] Variable object:",u),console.log("[Debug] Term object:",p))}}}catch(u){console.warn("[Warning] binding.keys()/get() failed:",this.formatError(u))}if(Object.keys(f).length===0){for(const u in d)if(Object.prototype.hasOwnProperty.call(d,u)&&u!=="type"&&u!=="size"){const p=d[u];if(p){const g=this.extractBindingKeyName(u);g&&(f[g]=this.convertComunicaTerm(p))}}}return f});return this.logging&&console.log(`[Comunica] ${e.type} query results:`,c),c}else if(e.type==="ASK"){const o=await i.queryBoolean(e.query,{sources:[s],fetch:this.fetchFn});return this.logging&&console.log(`[Comunica] ${e.type} query result:`,o),[{result:o}]}else{const o=this.sources;this.sources=[t];try{const a=await this.executeUpdate(e,i),c=a.filter(l=>!l.success);if(c.length>0){const l=c[0],d=l&&l.error?l.error:"UPDATE operation failed";throw new Error(d)}return this.logging&&console.log(`[Comunica] ${e.type} operation completed successfully`),a}finally{this.sources=o}}}catch(i){throw this.logging&&console.error("[Comunica] Query execution failed:",this.formatError(i)),i}}addSource(e){this.sources.includes(e)||this.sources.push(e)}removeSource(e){const t=this.sources.indexOf(e);t>-1&&this.sources.splice(t,1)}getSources(){return[...this.sources]}}const SolidSPARQLExecutor=ComunicaSPARQLExecutor,sparqlExecutor=Object.freeze(Object.defineProperty({__proto__:null,ComunicaSPARQLExecutor,SolidSPARQLExecutor},Symbol.toStringTag,{value:"Module"}));var define_process_env_default$1={};class PodExecutor{constructor(e){this.deps=e}async query(e){await this.deps.ensureConnected(),await this.deps.ensureTableResourcePath(e.table);const t=this.deps.resolveTableResource(e.table),r=e.type==="select"?this.getSelectStrategy(e,t):this.deps.getLdpStrategy(),{containerUrl:i,resourceUrl:s}=this.deps.resolveTableUrls(e.table),o=this.deps.normalizeResourceUrl(s),c=(e.type==="select"?this.getExactSelectResourceUrl(e):void 0)??(e.type==="select"&&t.mode==="sparql"?t.endpoint:o);try{switch(e.type){case"select":return await this.executeSelect(e,r,i,c);case"insert":return await this.executeInsert(e,r,i,o,t);case"update":return await this.executeUpdate(e,r,i,o,t);case"delete":return await this.executeDelete(e,r,i,o,t);default:throw new Error(`Unsupported operation type: ${e.type}`)}}catch(l){throw typeof process<"u"&&define_process_env_default$1?.LINX_DEBUG==="1"&&console.error(`${e.type.toUpperCase()} operation failed:`,l),l}}shouldSkipResourcePreparation(){return this.deps.shouldSkipResourcePreparation?.()??!1}shouldUseWriteTimeResourcePreparation(){return this.deps.shouldUseWriteTimeResourcePreparation?.()??this.shouldSkipResourcePreparation()}shouldContinueAfterResourcePreparationError(){return this.deps.shouldContinueAfterResourcePreparationError?.()??!1}async prepareResource(e,t){if(!this.shouldSkipResourcePreparation())try{await t()}catch(r){if(!this.shouldContinueAfterResourcePreparationError())throw r;typeof process<"u"&&define_process_env_default$1?.LINX_DEBUG==="1"&&console.warn(`[${e}] Resource preparation failed; continuing in best-effort mode:`,r)}}async executeSelect(e,t,r,i){let s;if(e.plan&&this.deps.isSelectPlan(e.plan))s=e.plan;else{if(e.plan&&!this.deps.isSelectPlan(e.plan))throw new Error("Invalid plan supplied for select operation");{const a=e.table.config.name??"table",c={baseTable:e.table,baseAlias:a,selectAll:!0,conditionTree:e.where,limit:e.limit,offset:e.offset,distinct:e.distinct,aliasToTable:new Map([[a,e.table]]),tableToAlias:new Map([[e.table,a]])};c._simpleSelectOptions=e.sql?void 0:{table:e.table,where:e.where,limit:e.limit,offset:e.offset,orderBy:e.orderBy,distinct:e.distinct},c._sql=e.sql,s=c}}return await t.executeSelect(s,r,i)}getSelectStrategy(e,t){return this.deps.getStrategy(e.table)}isExactIriSelect(e){const t=e.where;if(!t||typeof t!="object"||"type"in t)return!1;const r=t["@id"];return typeof r=="string"&&r.startsWith("http")}getExactSelectResourceUrl(e){if(!this.isExactIriSelect(e))return;const t=e.where["@id"],r=t.indexOf("#");return r>=0?t.slice(0,r):t}async executeInsert(e,t,r,i,s){const o=Array.isArray(e.values)?e.values:[e.values];if(!o||o.length===0)throw new Error("INSERT operation requires at least one value");const a=this.shouldUseWriteTimeResourcePreparation(),c=a&&!this.shouldSkipResourcePreparation();if(!a&&!this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r))&&await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(r)),s.mode==="ldp"&&!a&&!this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))&&await this.prepareResource("INSERT",()=>this.deps.ensureResourceExists(i,{createIfMissing:!0})),s.mode==="ldp"&&!a)for(const f of o)try{const u=this.deps.sparqlConverter.generateSubjectUri(f,e.table),p={type:"ASK",query:`ASK { <${u}> ?p ?o }`,prefixes:{}};if((await this.deps.sparqlExecutor.executeQueryWithSource(p,i))[0]?.result)throw new Error(`Duplicate primary key: ${u} already exists.`)}catch(u){if(u.message&&u.message.includes("Duplicate primary key"))throw u;await this.deps.sparqlExecutor.invalidateHttpCache(i)}const l={...this.deps.isInsertPlan(e.plan)?e.plan:{table:e.table,rows:o},ensureContainerExists:a?void 0:async f=>{await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(f))},repairContainerOnWriteFailure:c?async f=>{await this.prepareResource("INSERT",()=>this.deps.ensureContainerExists(f))}:void 0,skipResourceExistenceCheck:a||this.deps.isInsertPlan(e.plan)&&e.plan.skipResourceExistenceCheck===!0,tableRegistry:this.deps.getTableRegistries?.().tableRegistry,tableNameRegistry:this.deps.getTableRegistries?.().tableNameRegistry};if(!t.executeInsert)throw new Error("Strategy does not support INSERT operations");return await t.executeInsert(l,r,i)}async executeUpdate(e,t,r,i,s){if(!e.data)throw new Error("UPDATE operation requires data");if(!e.where||Object.keys(e.where).length===0)throw new Error("UPDATE operation requires where conditions to locate target resources");if(s.mode==="ldp"&&!this.shouldUseWriteTimeResourcePreparation()){if(!this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r)))try{await this.prepareResource("UPDATE",()=>this.deps.ensureContainerExists(r))}catch(c){const l=c instanceof Error?c.message:String(c);if(l.includes("Failed to check container: 401")||l.includes("Failed to check container: 403"))console.warn(`[UPDATE] Skipping container existence check for ${r}: ${l}`);else throw c}this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))||await this.prepareResource("UPDATE",()=>this.deps.ensureResourceExists(i,{createIfMissing:!1}))}const o=this.deps.isUpdatePlan(e.plan)?e.plan:{table:e.table,data:e.data,where:e.where};if(s.mode==="sparql"){const c=await this.deps.ensureIdentifierCondition(o.where,o.table,i);if(!c)return console.warn("[UPDATE] No matching subjects found for provided condition, skipping update."),[];o.where=c}if(!t.executeUpdate)throw new Error("Strategy does not support UPDATE operations");return await t.executeUpdate(o,r,i)}async executeDelete(e,t,r,i,s){if(s.mode==="ldp"&&!this.shouldUseWriteTimeResourcePreparation()&&(this.deps.preparedContainers.has(this.deps.normalizeContainerKey(r))||await this.prepareResource("DELETE",()=>this.deps.ensureContainerExists(r)),!(this.deps.preparedResources.has(this.deps.normalizeResourceKey(i))||this.shouldSkipResourcePreparation()?!0:await this.deps.resourceExists(i))))return console.log("[DELETE] Target resource does not exist, skipping execution"),[{success:!0,source:i,status:404}];const o=this.deps.isDeletePlan(e.plan)?e.plan:{table:e.table,where:e.where};if(s.mode==="sparql"&&o.where){const c=await this.deps.ensureIdentifierCondition(o.where,o.table,i);if(!c)return console.warn("[DELETE] No matching subjects found for provided condition, skipping delete."),[];o.where=c}if(!t.executeDelete)throw new Error("Strategy does not support DELETE operations");return await t.executeDelete(o,r,i)}}function isSameOrigin(n,e){try{const t=new URL(n),r=new URL(e);return t.origin===r.origin}catch{return!1}}function getFetchForOrigin(n,e,t){return isSameOrigin(n,e)?t:fetch}const normalize=n=>n.endsWith("/")?n:`${n}/`,pickSameOrigin=(n,e)=>{try{const t=new URL(n).origin;return e.find(i=>{try{return new URL(i).origin===t}catch{return!1}})||null}catch{return null}},deriveFromUrl=n=>{if(!n||n.trim().length===0)return null;try{const e=new URL(n),r=e.pathname.split("/").filter(Boolean)[0],i=r&&r!=="profile"?`/${r}/`:"/";return normalize(`${e.origin}${i}`)}catch{return null}};function resolvePodBase(n){const{webId:e,podUrl:t,storages:r}=n,i=(r||[]).filter(Boolean);if(i.length>0){const l=pickSameOrigin(e,i)||i[0];return normalize(l)}const s=deriveFromUrl(t),o=deriveFromUrl(e),a=c=>{if(!c)return!1;try{return new URL(c).pathname!=="/"}catch{return!1}};if(a(s))return s;if(a(o))return o;if(s)return s;if(o)return o;try{const c=new URL(e);return normalize(c.origin)}catch{return normalize(e)}}const PIM_STORAGE="http://www.w3.org/ns/pim/space#storage",SOLID_POD="http://www.w3.org/ns/solid/terms#pod";class WebIdResolver{constructor(){this.cache=new Map}extractStorageFromProfile(e,t,r){const i=r?.split(";")[0]?.trim().toLowerCase(),o=new N3Parser({baseIRI:e,format:i==="application/n-triples"?"N-Triples":void 0}).parse(t),a=[PIM_STORAGE,SOLID_POD];for(const c of a){const l=o.find(d=>d.subject.value===e&&d.predicate.value===c);if(l?.object?.value)return l.object.value}return null}async resolveStorage(e,t){if(this.cache.has(e))return this.cache.get(e)??null;try{const i=await(t??fetch)(e,{headers:{Accept:"text/turtle, application/n-triples;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!i.ok)throw new Error(`Failed to fetch WebID profile: ${i.status} ${i.statusText}`);const s=await i.text(),o=this.extractStorageFromProfile(e,s,i.headers.get("content-type"));if(o){const a=o.endsWith("/")?o:`${o}/`;return console.log(`[WebIdResolver] Resolved storage for ${e} -> ${a}`),this.cache.set(e,a),a}}catch(r){console.warn(`[WebIdResolver] Failed to resolve storage for ${e}`,r)}return null}clearCache(){this.cache.clear()}}const webIdResolver=new WebIdResolver,REQUEST_ID_DETECTION_TIMEOUT_MS=3e3;function generateRequestId(){const n=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`${n}-${e}`}class PodRuntime{constructor(e){this.storageUrl=null,this.storageResolvedAt=0,this.connected=!1,this.wrappedFetch=null,this.requestIdSupported=null,this.storageTTL=300*1e3,this.session=e.session,this.webId=e.webId,this.podUrl=resolvePodBase({webId:this.webId,podUrl:e.podUrl}),this.explicitPodUrl=typeof e.podUrl=="string"&&e.podUrl.trim().length>0,e.storageTTL!==void 0&&(this.storageTTL=e.storageTTL)}async detectRequestIdSupport(){const e=new AbortController,t=setTimeout(()=>e.abort(),REQUEST_ID_DETECTION_TIMEOUT_MS);try{return((await globalThis.fetch(this.podUrl,{method:"OPTIONS",signal:e.signal})).headers.get("Access-Control-Allow-Headers")||"").toLowerCase().includes("x-request-id")}catch{return!1}finally{clearTimeout(t)}}createWrappedFetch(){const e=this.session.fetch,t=this;return async(r,i)=>{if(!t.requestIdSupported)return e(r,i);const s=generateRequestId(),o=new Headers(i?.headers);return o.has("X-Request-ID")||o.set("X-Request-ID",s),e(r,{...i,headers:o})}}getSession(){return this.session}getFetch(){return this.wrappedFetch||(this.wrappedFetch=this.createWrappedFetch()),this.wrappedFetch}getWebId(){return this.webId}getPodUrl(){return this.podUrl}getStorageUrl(){return this.storageUrl}isStorageExpired(){return this.storageResolvedAt?Date.now()-this.storageResolvedAt>this.storageTTL:!0}async getPodUrlWithRefresh(){return this.isStorageExpired()&&await this.refreshStorage(),this.podUrl}async refreshStorage(){if(this.explicitPodUrl)return this.storageUrl=this.podUrl,this.storageResolvedAt=Date.now(),this.storageUrl;webIdResolver.clearCache();const e=await webIdResolver.resolveStorage(this.webId,this.getFetch());return e&&(this.storageUrl=e,this.storageResolvedAt=Date.now(),!this.explicitPodUrl&&e!==this.podUrl&&(console.log(`[PodRuntime] Storage refreshed: ${e}`),this.podUrl=e)),this.storageUrl}setPodUrl(e){this.podUrl=e.endsWith("/")?e:`${e}/`}isConnected(){return this.connected}async connect(){if(!this.connected)try{if(console.log(`Connecting to Solid Pod: ${this.podUrl}`),console.log(`Using WebID: ${this.webId}`),this.explicitPodUrl){this.requestIdSupported=!1,this.wrappedFetch=this.createWrappedFetch(),this.storageUrl=this.podUrl,this.storageResolvedAt=Date.now(),this.connected=!0,console.log("Using explicit Pod URL; skipping Pod root probe");return}this.requestIdSupported=await this.detectRequestIdSupport(),this.wrappedFetch=this.createWrappedFetch();const e=await webIdResolver.resolveStorage(this.webId,this.wrappedFetch);e&&(this.storageUrl=e,this.storageResolvedAt=Date.now(),e!==this.podUrl&&(console.log(`[PodRuntime] IdP-SP separation detected: storage at ${e}`),this.podUrl=e));const t=await this.wrappedFetch(this.podUrl,{method:"HEAD"}),r=t.status;if(r===500&&!this.explicitPodUrl){const i=this.requestIdSupported?t.headers.get("X-Request-ID")||"unknown":"disabled";throw console.error(`Pod probe failed, X-Request-ID: ${i}`),new Error(`Failed to connect to Pod: ${r} ${t.statusText}`)}r===500&&this.explicitPodUrl&&console.warn(`Pod root returned ${r} for explicit Pod URL, continuing (child resources may still be writable)`),t.ok?console.log("Successfully connected to Solid Pod"):console.warn(r===401||r===403?`Pod root returned ${r}, continuing (child resources may still be writable)`:`Pod root returned ${r}, continuing (child resources may still be writable)`),this.connected=!0}catch(e){throw console.error("Failed to connect to Pod:",e),e}}async disconnect(){this.connected=!1,console.log("Disconnected from Solid Pod")}}var Wildcard={},hasRequiredWildcard;function requireWildcard(){if(hasRequiredWildcard)return Wildcard;hasRequiredWildcard=1;let n=class{constructor(){return e||this}equals(r){return r&&this.termType===r.termType}};Object.defineProperty(n.prototype,"value",{enumerable:!0,value:"*"}),Object.defineProperty(n.prototype,"termType",{enumerable:!0,value:"Wildcard"});var e=new n;return Wildcard.Wildcard=n,Wildcard}var SparqlParser_1,hasRequiredSparqlParser;function requireSparqlParser(){if(hasRequiredSparqlParser)return SparqlParser_1;hasRequiredSparqlParser=1;var n=(function(){var e=function(Y,Q,ne,fe){for(ne=ne||{},fe=Y.length;fe--;ne[Y[fe]]=Q);return ne},t=[6,12,13,15,16,24,32,36,41,45,100,110,113,115,116,123,126,131,197,224,229,308,329,330,331,332,333],r=[2,247],i=[100,110,113,115,116,123,126,131,329,330,331,332,333],s=[2,409],o=[1,18],a=[1,27],c=[13,16,45,197,224,229,308],l=[28,29,53],d=[28,53],f=[1,42],u=[1,45],p=[1,41],g=[1,44],y=[123,126],w=[1,67],_=[39,45,87],R=[13,16,45,197,224,308],b=[1,87],C=[2,281],P=[1,86],H=[13,16,45,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],M=[6,28,29,53,63,70,73,81,83,85],re=[6,13,16,28,29,53,63,70,73,81,83,85,87,308],he=[6,13,16,28,29,45,53,63,70,73,81,82,83,85,87,89,197,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314],V=[6,13,16,28,29,31,39,45,47,48,53,63,70,73,81,82,83,85,87,89,109,112,121,123,126,128,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,337,338,340,341,342,343,344,345,346],q=[13,16,308],ie=[112,132,327,334],U=[13,16,112,132,308],ce=[1,111],Se=[1,117],me=[112,132,327,328,334],Ne=[13,16,112,132,308,328],te=[28,29,45,53,87],ae=[1,138],x=[1,151],O=[1,128],se=[1,127],G=[1,129],le=[1,140],pe=[1,141],Re=[1,142],_e=[1,143],B=[1,144],Z=[1,145],oe=[1,147],ye=[1,148],ge=[2,457],D=[1,158],F=[1,159],k=[1,160],ee=[1,152],J=[1,153],X=[1,156],N=[1,171],z=[1,172],K=[1,173],j=[1,174],we=[1,175],Ee=[1,176],be=[1,167],Ie=[1,168],S=[1,169],h=[1,170],m=[1,157],I=[1,166],$=[1,161],L=[1,162],W=[1,163],Te=[1,164],xe=[1,165],Fe=[6,13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335],je=[1,195],Le=[6,31,73,81,83,85],Ft=[2,285],Qt=[1,199],rt=[1,201],Xe=[6,31,70,73,81,83,85],bt=[2,283],wt=[1,207],ut=[1,218],Ye=[1,223],v=[1,219],A=[1,225],de=[1,226],ue=[1,224],ve=[6,63,70,73,81,83,85],Me=[1,236],Ge=[2,334],Gt=[1,243],it=[1,241],ze=[6,193],Lt=[2,349],Ht=[2,339],nt=[28,128],jt=[47,48,193,272],_t=[47,48,193,242,272],st=[47,48,193,242,246,272],et=[47,48,193,242,246,250,263,265,272,290,297,298,299,300,301,302,341,342,343,344,345,346],ke=[39,47,48,193,242,246,250,263,265,272,290,297,298,299,300,301,302,338,341,342,343,344,345,346],tt=[1,271],Zr=[1,270],qe=[6,13,16,29,31,39,45,47,48,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,338,341,342,343,344,345,346,347,348,349,350,351],Qr=[1,281],Gr=[1,280],He=[13,16,29,31,39,45,47,48,82,85,87,89,112,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346],Kt=[45,89],nr=[13,16,29,31,39,45,47,48,82,85,87,89,112,159,160,161,163,164,174,193,197,224,229,231,232,242,246,250,263,265,272,290,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346],ir=[13,16,31,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],sr=[31,89],or=[48,87],Et=[6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337,338],ot=[6,13,16,39,45,48,82,87,89,231,263,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337,338,340],Hr=[1,313],Ut=[6,85],Er=[6,31,81,83,85],Kr=[2,361],dt=[2,353],It=[1,343],Jt=[31,112,335],ft=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],Ir=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335],Jr=[6,109,193],vt=[31,112],Ve=[13,16,45,82,87,224,263,265,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312,346,347,348,349,350,351],vr=[1,390],xr=[1,391],St=[13,16,87,197,308,314],Xr=[13,16,39,45,82,87,224,263,265,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312,346,347,348,349,350,351],ar=[1,417],cr=[1,418],Yr=[13,16,48,197,229,308],Tt=[6,31,85],en=[6,13,16,31,45,73,81,83,85,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],Cr=[6,13,16,29,31,45,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,231,268,269,270,271,273,274,276,277,279,280,283,285,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,346,347,348,349,350,351],xt=[29,31,85,112,159,160,161,163,164],lr=[1,443],ur=[1,444],tn=[1,449],Ct=[31,112,193,232,318,335],dr=[13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],rn=[13,16,31,45,48,82,87,89,112,193,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],Ar=[13,16,29,31,45,48,82,85,87,89,112,159,160,161,163,164,193,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],Xt=[13,16,31,48,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],Yt=[31,45],nn=[1,507],sn=[1,508],on=[6,13,16,29,31,39,45,47,48,63,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,336,338,341,342,343,344,345,346,347,348,349,350,351],fr=[29,31,85,112,159,160,161,163,164,335],At=[6,13,16,31,45,70,73,81,83,85,87,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],an=[13,16,31,45,48,82,87,89,112,193,197,231,232,272,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,317,318,335],cn=[2,352],Nr=[13,16,197,308,314],ln=[1,565],kt=[6,13,16,31,45,76,78,81,83,85,87,268,269,270,271,273,274,276,277,279,280,283,285,308,346,347,348,349,350,351],un=[13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],ht=[13,16,29,31,45,82,85,87,89,112,159,160,161,163,164,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335],dn=[13,16,87,308],pt=[2,364],Ot=[29,31,85,112,159,160,161,163,164,193,232,318,335],hr=[31,112,193,232,272,318,335],gt=[2,359],fn=[13,16,48,82,174,294,295,296,297,298,299,300,301,302,303,304,305,306,308,312],pr=[29,31,85,112,159,160,161,163,164,193,232,272,318,335],hn=[13,16,31,45,82,87,89,112,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],pn=[2,347],Pr={trace:function(){},yy:{},symbols_:{error:2,QueryOrUpdate:3,Prologue:4,QueryOrUpdate_group0:5,EOF:6,Query:7,Qry:8,Query_option0:9,Prologue_repetition0:10,BaseDecl:11,BASE:12,IRIREF:13,PrefixDecl:14,PREFIX:15,PNAME_NS:16,SelectClauseWildcard:17,Qry_repetition0:18,WhereClause:19,SolutionModifierNoGroup:20,SelectClauseVars:21,Qry_repetition1:22,SolutionModifier:23,CONSTRUCT:24,ConstructTemplate:25,Qry_repetition2:26,Qry_repetition3:27,WHERE:28,"{":29,Qry_option0:30,"}":31,DESCRIBE:32,Qry_group0:33,Qry_repetition4:34,Qry_option1:35,ASK:36,Qry_repetition5:37,SelectClauseBase:38,"*":39,SelectClauseVars_repetition_plus0:40,SELECT:41,SelectClauseBase_option0:42,SelectClauseItem:43,Var:44,"(":45,Expression:46,AS:47,")":48,SubSelect:49,SubSelect_option0:50,SubSelect_option1:51,DatasetClause:52,FROM:53,DatasetClause_option0:54,iri:55,WhereClause_option0:56,GroupGraphPattern:57,SolutionModifier_option0:58,SolutionModifierNoGroup_option0:59,SolutionModifierNoGroup_option1:60,SolutionModifierNoGroup_option2:61,GroupClause:62,GROUP:63,BY:64,GroupClause_repetition_plus0:65,GroupCondition:66,BuiltInCall:67,FunctionCall:68,HavingClause:69,HAVING:70,HavingClause_repetition_plus0:71,OrderClause:72,ORDER:73,OrderClause_repetition_plus0:74,OrderCondition:75,ASC:76,BrackettedExpression:77,DESC:78,Constraint:79,LimitOffsetClauses:80,LIMIT:81,INTEGER:82,OFFSET:83,ValuesClause:84,VALUES:85,InlineData:86,VAR:87,InlineData_repetition0:88,NIL:89,InlineData_repetition1:90,InlineData_repetition_plus2:91,InlineData_repetition3:92,DataBlock:93,DataBlockValueList:94,DataBlockValueList_repetition_plus0:95,Update:96,Update_repetition0:97,Update1:98,Update_option0:99,LOAD:100,Update1_option0:101,Update1_option1:102,Update1_group0:103,Update1_option2:104,GraphRefAll:105,Update1_group1:106,Update1_option3:107,GraphOrDefault:108,TO:109,CREATE:110,Update1_option4:111,GRAPH:112,INSERTDATA:113,QuadPattern:114,DELETEDATA:115,DELETEWHERE:116,Update1_option5:117,InsertDeleteClause:118,Update1_repetition0:119,IntoGraphClause:120,INTO:121,GraphRef:122,DELETE:123,InsertDeleteClause_option0:124,InsertClause:125,INSERT:126,UsingClause:127,USING:128,UsingClause_option0:129,WithClause:130,WITH:131,DEFAULT:132,GraphOrDefault_option0:133,GraphRefAll_group0:134,Quads:135,Quads_option0:136,Quads_repetition0:137,QuadsNotTriples:138,VarOrIri:139,QuadsNotTriples_option0:140,QuadsNotTriples_option1:141,QuadsNotTriples_option2:142,TriplesTemplate:143,TriplesTemplate_repetition0:144,TriplesSameSubject:145,TriplesTemplate_option0:146,GroupGraphPatternSub:147,GroupGraphPatternSub_option0:148,GroupGraphPatternSub_repetition0:149,GroupGraphPatternSubTail:150,GraphPatternNotTriples:151,GroupGraphPatternSubTail_option0:152,GroupGraphPatternSubTail_option1:153,TriplesBlock:154,TriplesBlock_repetition0:155,TriplesSameSubjectPath:156,TriplesBlock_option0:157,GroupOrUnionGraphPattern:158,OPTIONAL:159,MINUS:160,SERVICE:161,GraphPatternNotTriples_option0:162,FILTER:163,BIND:164,InlineDataOneVar:165,InlineDataFull:166,InlineDataOneVar_repetition0:167,InlineDataFull_repetition0:168,InlineDataFull_repetition_plus1:169,InlineDataFull_repetition2:170,DataBlockValue:171,Literal:172,QuotedTriple:173,UNDEF:174,GroupOrUnionGraphPattern_repetition0:175,ArgList:176,ArgList_option0:177,ArgList_repetition0:178,ExpressionList:179,ExpressionList_repetition0:180,ConstructTemplate_option0:181,ConstructTriples:182,ConstructTriples_repetition0:183,ConstructTriples_option0:184,VarOrTermOrQuotedTP:185,PropertyListNotEmpty:186,TriplesNode:187,PropertyList:188,PropertyList_option0:189,VerbObjectList:190,PropertyListNotEmpty_repetition0:191,SemiOptionalVerbObjectList:192,";":193,SemiOptionalVerbObjectList_option0:194,Verb:195,ObjectList:196,a:197,ObjectList_repetition0:198,Object:199,GraphNode:200,Object_option0:201,PropertyListPathNotEmpty:202,TriplesNodePath:203,TriplesSameSubjectPath_option0:204,O:205,PropertyListPathNotEmpty_repetition0:206,PropertyListPathNotEmptyTail:207,O_group0:208,ObjectListPath:209,ObjectListPath_repetition0:210,ObjectPath:211,GraphNodePath:212,ObjectPath_option0:213,Path:214,Path_repetition0:215,PathSequence:216,PathSequence_repetition0:217,PathEltOrInverse:218,PathElt:219,PathPrimary:220,PathElt_option0:221,PathEltOrInverse_option0:222,IriOrA:223,"!":224,PathNegatedPropertySet:225,PathOneInPropertySet:226,PathNegatedPropertySet_repetition0:227,PathNegatedPropertySet_option0:228,"^":229,TriplesNode_repetition_plus0:230,"[":231,"]":232,TriplesNodePath_repetition_plus0:233,VarOrTermOrQuotedTPExpr:234,VarOrTerm:235,GraphTerm:236,BlankNode:237,ConditionalOrExpression:238,ConditionalAndExpression:239,ConditionalOrExpression_repetition0:240,ConditionalOrExpressionTail:241,"||":242,RelationalExpression:243,ConditionalAndExpression_repetition0:244,ConditionalAndExpressionTail:245,"&&":246,NumericExpression:247,RelationalExpression_group0:248,RelationalExpression_option0:249,IN:250,MultiplicativeExpression:251,NumericExpression_repetition0:252,AdditiveExpressionTail:253,AdditiveExpressionTail_group0:254,NumericLiteralPositive:255,AdditiveExpressionTail_repetition0:256,NumericLiteralNegative:257,AdditiveExpressionTail_repetition1:258,UnaryExpression:259,MultiplicativeExpression_repetition0:260,MultiplicativeExpressionTail:261,MultiplicativeExpressionTail_group0:262,"+":263,PrimaryExpression:264,"-":265,ExprQuotedTP:266,Aggregate:267,FUNC_ARITY0:268,FUNC_ARITY1:269,FUNC_ARITY1_SPARQL_STAR:270,FUNC_ARITY2:271,",":272,FUNC_ARITY3:273,FUNC_ARITY3_SPARQL_STAR:274,BuiltInCall_group0:275,BOUND:276,BNODE:277,BuiltInCall_option0:278,EXISTS:279,COUNT:280,Aggregate_option0:281,Aggregate_group0:282,FUNC_AGGREGATE:283,Aggregate_option1:284,GROUP_CONCAT:285,Aggregate_option2:286,Aggregate_option3:287,GroupConcatSeparator:288,SEPARATOR:289,"=":290,String:291,LANGTAG:292,"^^":293,DECIMAL:294,DOUBLE:295,BOOLEAN:296,INTEGER_POSITIVE:297,DECIMAL_POSITIVE:298,DOUBLE_POSITIVE:299,INTEGER_NEGATIVE:300,DECIMAL_NEGATIVE:301,DOUBLE_NEGATIVE:302,STRING_LITERAL1:303,STRING_LITERAL2:304,STRING_LITERAL_LONG1:305,STRING_LITERAL_LONG2:306,PrefixedName:307,PNAME_LN:308,BLANK_NODE_LABEL:309,ANON:310,QuotedTP:311,"<<":312,qtSubjectOrObject:313,">>":314,DataValueTerm:315,AnnotationPattern:316,"{|":317,"|}":318,AnnotationPatternPath:319,ExprVarOrTerm:320,QueryOrUpdate_group0_option0:321,Prologue_repetition0_group0:322,Qry_group0_repetition_plus0:323,SelectClauseBase_option0_group0:324,DISTINCT:325,REDUCED:326,NAMED:327,SILENT:328,CLEAR:329,DROP:330,ADD:331,MOVE:332,COPY:333,ALL:334,".":335,UNION:336,"|":337,"/":338,PathElt_option0_group0:339,"?":340,"!=":341,"<":342,">":343,"<=":344,">=":345,NOT:346,CONCAT:347,COALESCE:348,SUBSTR:349,REGEX:350,REPLACE:351,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",12:"BASE",13:"IRIREF",15:"PREFIX",16:"PNAME_NS",24:"CONSTRUCT",28:"WHERE",29:"{",31:"}",32:"DESCRIBE",36:"ASK",39:"*",41:"SELECT",45:"(",47:"AS",48:")",53:"FROM",63:"GROUP",64:"BY",70:"HAVING",73:"ORDER",76:"ASC",78:"DESC",81:"LIMIT",82:"INTEGER",83:"OFFSET",85:"VALUES",87:"VAR",89:"NIL",100:"LOAD",109:"TO",110:"CREATE",112:"GRAPH",113:"INSERTDATA",115:"DELETEDATA",116:"DELETEWHERE",121:"INTO",123:"DELETE",126:"INSERT",128:"USING",131:"WITH",132:"DEFAULT",159:"OPTIONAL",160:"MINUS",161:"SERVICE",163:"FILTER",164:"BIND",174:"UNDEF",193:";",197:"a",224:"!",229:"^",231:"[",232:"]",242:"||",246:"&&",250:"IN",263:"+",265:"-",268:"FUNC_ARITY0",269:"FUNC_ARITY1",270:"FUNC_ARITY1_SPARQL_STAR",271:"FUNC_ARITY2",272:",",273:"FUNC_ARITY3",274:"FUNC_ARITY3_SPARQL_STAR",276:"BOUND",277:"BNODE",279:"EXISTS",280:"COUNT",283:"FUNC_AGGREGATE",285:"GROUP_CONCAT",289:"SEPARATOR",290:"=",292:"LANGTAG",293:"^^",294:"DECIMAL",295:"DOUBLE",296:"BOOLEAN",297:"INTEGER_POSITIVE",298:"DECIMAL_POSITIVE",299:"DOUBLE_POSITIVE",300:"INTEGER_NEGATIVE",301:"DECIMAL_NEGATIVE",302:"DOUBLE_NEGATIVE",303:"STRING_LITERAL1",304:"STRING_LITERAL2",305:"STRING_LITERAL_LONG1",306:"STRING_LITERAL_LONG2",308:"PNAME_LN",309:"BLANK_NODE_LABEL",310:"ANON",312:"<<",314:">>",317:"{|",318:"|}",325:"DISTINCT",326:"REDUCED",327:"NAMED",328:"SILENT",329:"CLEAR",330:"DROP",331:"ADD",332:"MOVE",333:"COPY",334:"ALL",335:".",336:"UNION",337:"|",338:"/",340:"?",341:"!=",342:"<",343:">",344:"<=",345:">=",346:"NOT",347:"CONCAT",348:"COALESCE",349:"SUBSTR",350:"REGEX",351:"REPLACE"},productions_:[0,[3,3],[7,2],[4,1],[11,2],[14,3],[8,4],[8,4],[8,5],[8,7],[8,5],[8,4],[17,2],[21,2],[38,2],[43,1],[43,5],[49,4],[49,4],[52,3],[19,2],[23,2],[20,3],[62,3],[66,1],[66,1],[66,3],[66,5],[66,1],[69,2],[72,3],[75,2],[75,2],[75,1],[75,1],[80,2],[80,2],[80,4],[80,4],[84,2],[86,4],[86,4],[86,6],[86,2],[94,3],[96,3],[98,4],[98,3],[98,5],[98,4],[98,2],[98,2],[98,2],[98,5],[120,2],[118,3],[118,1],[125,2],[127,3],[130,2],[108,1],[108,2],[122,2],[105,1],[105,1],[114,3],[135,2],[138,7],[143,3],[57,3],[57,3],[147,2],[150,3],[154,3],[151,1],[151,2],[151,2],[151,3],[151,4],[151,2],[151,6],[151,1],[93,1],[93,1],[165,4],[166,4],[166,6],[171,1],[171,1],[171,1],[171,1],[158,2],[79,1],[79,1],[79,1],[68,2],[176,1],[176,5],[179,1],[179,4],[25,3],[182,3],[145,2],[145,2],[188,1],[186,2],[192,2],[190,2],[195,1],[195,1],[196,2],[199,2],[156,2],[156,2],[202,2],[207,1],[207,2],[205,2],[209,2],[211,2],[214,2],[216,2],[219,2],[218,2],[220,1],[220,2],[220,3],[225,1],[225,1],[225,4],[226,1],[226,2],[187,3],[187,3],[203,3],[203,3],[200,1],[200,1],[212,1],[212,1],[234,1],[235,1],[235,1],[139,1],[139,1],[44,1],[236,1],[236,1],[236,1],[236,1],[46,1],[238,2],[241,2],[239,2],[245,2],[243,1],[243,3],[243,4],[247,2],[253,2],[253,2],[253,2],[251,2],[261,2],[259,2],[259,2],[259,2],[259,1],[264,1],[264,1],[264,1],[264,1],[264,1],[264,1],[264,1],[77,3],[67,1],[67,2],[67,4],[67,4],[67,6],[67,8],[67,8],[67,2],[67,4],[67,2],[67,4],[67,3],[267,5],[267,5],[267,6],[288,4],[172,1],[172,2],[172,3],[172,1],[172,1],[172,1],[172,1],[172,1],[172,1],[255,1],[255,1],[255,1],[257,1],[257,1],[257,1],[291,1],[291,1],[291,1],[291,1],[55,1],[55,1],[307,1],[307,1],[237,1],[237,1],[311,5],[173,5],[313,1],[313,1],[313,1],[313,1],[313,1],[315,1],[315,1],[315,1],[185,1],[185,1],[185,1],[316,3],[319,3],[266,5],[320,1],[320,1],[320,1],[223,1],[223,1],[321,0],[321,1],[5,1],[5,1],[5,1],[9,0],[9,1],[322,1],[322,1],[10,0],[10,2],[18,0],[18,2],[22,0],[22,2],[26,0],[26,2],[27,0],[27,2],[30,0],[30,1],[323,1],[323,2],[33,1],[33,1],[34,0],[34,2],[35,0],[35,1],[37,0],[37,2],[40,1],[40,2],[324,1],[324,1],[42,0],[42,1],[50,0],[50,1],[51,0],[51,1],[54,0],[54,1],[56,0],[56,1],[58,0],[58,1],[59,0],[59,1],[60,0],[60,1],[61,0],[61,1],[65,1],[65,2],[71,1],[71,2],[74,1],[74,2],[88,0],[88,2],[90,0],[90,2],[91,1],[91,2],[92,0],[92,2],[95,1],[95,2],[97,0],[97,4],[99,0],[99,2],[101,0],[101,1],[102,0],[102,1],[103,1],[103,1],[104,0],[104,1],[106,1],[106,1],[106,1],[107,0],[107,1],[111,0],[111,1],[117,0],[117,1],[119,0],[119,2],[124,0],[124,1],[129,0],[129,1],[133,0],[133,1],[134,1],[134,1],[134,1],[136,0],[136,1],[137,0],[137,2],[140,0],[140,1],[141,0],[141,1],[142,0],[142,1],[144,0],[144,3],[146,0],[146,1],[148,0],[148,1],[149,0],[149,2],[152,0],[152,1],[153,0],[153,1],[155,0],[155,3],[157,0],[157,1],[162,0],[162,1],[167,0],[167,2],[168,0],[168,2],[169,1],[169,2],[170,0],[170,2],[175,0],[175,3],[177,0],[177,1],[178,0],[178,3],[180,0],[180,3],[181,0],[181,1],[183,0],[183,3],[184,0],[184,1],[189,0],[189,1],[191,0],[191,2],[194,0],[194,1],[198,0],[198,3],[201,0],[201,1],[204,0],[204,1],[206,0],[206,2],[208,1],[208,1],[210,0],[210,3],[213,0],[213,1],[215,0],[215,3],[217,0],[217,3],[339,1],[339,1],[339,1],[221,0],[221,1],[222,0],[222,1],[227,0],[227,3],[228,0],[228,1],[230,1],[230,2],[233,1],[233,2],[240,0],[240,2],[244,0],[244,2],[248,1],[248,1],[248,1],[248,1],[248,1],[248,1],[249,0],[249,1],[252,0],[252,2],[254,1],[254,1],[256,0],[256,2],[258,0],[258,2],[260,0],[260,2],[262,1],[262,1],[275,1],[275,1],[275,1],[275,1],[275,1],[278,0],[278,1],[281,0],[281,1],[282,1],[282,1],[284,0],[284,1],[286,0],[286,1],[287,0],[287,1]],performAction:function(Q,ne,fe,Ce,Ae,T,Je){var E=T.length-1;switch(Ae){case 1:if(T[E-1]=T[E-1]||{},De.base&&(T[E-1].base=De.base),De.base="",T[E-1].prefixes=De.prefixes,De.prefixes=null,De.pathOnly){if(T[E-1].type==="path"||"termType"in T[E-1])return T[E-1];throw new Error("Received full SPARQL query in path only mode")}else if(T[E-1].type==="path"||"termType"in T[E-1])throw new Error("Received only path in full SPARQL mode");if(T[E-1].type==="update"){const $e={};for(const Ue of T[E-1].updates)if(Ue.updateType==="insert"){const Pe={};for(const Ze of Ue.insert)if(Ze.type==="bgp"||Ze.type==="graph")for(const Qe of Ze.triples)Qe.subject.termType==="BlankNode"&&(Pe[Qe.subject.value]=!0),Qe.predicate.termType==="BlankNode"&&(Pe[Qe.predicate.value]=!0),Qe.object.termType==="BlankNode"&&(Pe[Qe.object.value]=!0);for(const Ze of Object.keys(Pe)){if($e[Ze])throw new Error("Detected reuse blank node across different INSERT DATA clauses");$e[Ze]=!0}}}return T[E-1];case 2:this.$={...T[E-1],...T[E],type:"query"};break;case 4:De.base=er(T[E]);break;case 5:De.prefixes||(De.prefixes={}),T[E-1]=T[E-1].substr(0,T[E-1].length-1),T[E]=er(T[E]),De.prefixes[T[E-1]]=T[E];break;case 6:this.$={...T[E-3],...$t(T[E-2]),...T[E-1],...T[E]};break;case 7:if(!De.skipValidation&&(Or(T[E-3].variables.map(Ue=>kr(Ue.expression))).some(Ue=>Ue.aggregation==="count"&&!(Ue.expression instanceof gr))||T[E].group)){for(const Ue of T[E-3].variables)if(Ue.termType==="Variable"){if(!T[E].group||!T[E].group.map(Pe=>Mt(Pe)).includes(Mt(Ue)))throw Error("Projection of ungrouped variable (?"+Mt(Ue)+")")}else if(kr(Ue.expression).length===0){const Pe=kn(Ue.expression);for(const Ze of Pe)if(!T[E].group||!T[E].group.map||!T[E].group.map(Qe=>Mt(Qe)).includes(Mt(Ze)))throw Error("Use of ungrouped variable in projection of operation (?"+Mt(Ze)+")")}}const Wt=T[E-1].where.filter($e=>$e.type==="query");if(Wt.length>0){const $e=T[E-3].variables.filter(Pe=>Pe.variable&&Pe.variable.value).map(Pe=>Pe.variable.value),Ue=Or(Wt.map(Pe=>Pe.variables)).map(Pe=>Pe.value||Pe.variable.value);for(const Pe of $e)if(Ue.indexOf(Pe)>=0)throw Error("Target id of 'AS' (?"+Pe+") already used in subquery")}this.$=Oe(T[E-3],$t(T[E-2]),T[E-1],T[E]);break;case 8:this.$=Oe({queryType:"CONSTRUCT",template:T[E-3]},$t(T[E-2]),T[E-1],T[E]);break;case 9:this.$=Oe({queryType:"CONSTRUCT",template:T[E-2]=T[E-2]?T[E-2].triples:[]},$t(T[E-5]),{where:[{type:"bgp",triples:Bt([],T[E-2])}]},T[E]);break;case 10:this.$=Oe({queryType:"DESCRIBE",variables:T[E-3]==="*"?[new gr]:T[E-3]},$t(T[E-2]),T[E-1],T[E]);break;case 11:this.$=Oe({queryType:"ASK"},$t(T[E-2]),T[E-1],T[E]);break;case 12:this.$=Oe(T[E-1],{variables:[new gr]});break;case 13:const Vr=T[E].map($e=>$e.value||$e.variable.value),Sr=On(Vr);if(Sr.length>0)throw Error("Two or more of the resulting columns have the same name (?"+Sr[0]+")");this.$=Oe(T[E-1],{variables:T[E]});break;case 14:this.$=Oe({queryType:"SELECT"},T[E]&&(T[E-1]=Ke(T[E]),T[E]={},T[E][T[E-1]]=!0,T[E]));break;case 16:case 27:this.$=zt(T[E-3],{variable:T[E-1]});break;case 17:case 18:this.$=Oe(T[E-3],T[E-2],T[E-1],T[E],{type:"query"});break;case 19:case 58:this.$={iri:T[E],named:!!T[E-1]};break;case 20:this.$={where:T[E].patterns};break;case 21:this.$=Oe(T[E-1],T[E]);break;case 22:this.$=Oe(T[E-2],T[E-1],T[E]);break;case 23:this.$={group:T[E]};break;case 24:case 25:case 28:case 31:case 33:case 34:this.$=zt(T[E]);break;case 26:this.$=zt(T[E-1]);break;case 29:this.$={having:T[E]};break;case 30:this.$={order:T[E]};break;case 32:this.$=zt(T[E],{descending:!0});break;case 35:this.$={limit:Vt(T[E])};break;case 36:this.$={offset:Vt(T[E])};break;case 37:this.$={limit:Vt(T[E-2]),offset:Vt(T[E])};break;case 38:this.$={limit:Vt(T[E]),offset:Vt(T[E-2])};break;case 39:case 43:this.$={type:"values",values:T[E]};break;case 40:case 84:this.$=T[E-1].map($e=>({[T[E-3]]:$e}));break;case 41:case 85:this.$=T[E-1].map(()=>({}));break;case 42:case 86:var Rt=T[E-4].length;T[E-4]=T[E-4].map($r),this.$=T[E-1].map(function($e){if($e.length!==Rt)throw Error("Inconsistent VALUES length");for(var Ue={},Pe=0;Pe<Rt;Pe++)Ue["?"+T[E-4][Pe].value]=$e[Pe];return Ue});break;case 44:case 65:case 100:case 126:case 175:this.$=T[E-1];break;case 45:this.$={type:"update",updates:Pt(T[E-2],T[E-1])};break;case 46:this.$=Oe({type:"load",silent:!!T[E-2],source:T[E-1]},T[E]&&{destination:T[E]});break;case 47:this.$={type:Ke(T[E-2]),silent:!!T[E-1],graph:T[E]};break;case 48:this.$={type:Ke(T[E-4]),silent:!!T[E-3],source:T[E-2],destination:T[E]};break;case 49:this.$={type:"create",silent:!!T[E-2],graph:{type:"graph",name:T[E]}};break;case 50:this.$={updateType:"insert",insert:In(T[E])};break;case 51:this.$={updateType:"delete",delete:qr(In(T[E]))};break;case 52:this.$={updateType:"deletewhere",delete:qr(T[E])};break;case 53:this.$={updateType:"insertdelete",...T[E-4],...T[E-3],...$t(T[E-2],"using"),where:T[E].patterns};break;case 54:case 57:case 62:case 167:case 191:case 236:this.$=T[E];break;case 55:this.$={delete:qr(T[E-1]),insert:T[E]||[]};break;case 56:this.$={delete:[],insert:T[E]};break;case 59:this.$={graph:T[E]};break;case 60:this.$={type:"graph",default:!0};break;case 61:case 63:this.$={type:"graph",name:T[E]};break;case 64:this.$={[Ke(T[E])]:!0};break;case 66:this.$=T[E-1]?at(T[E],[T[E-1]]):at(T[E]);break;case 67:var br=Oe(T[E-3]||{triples:[]},{type:"graph",name:T[E-5]});this.$=T[E]?[br,T[E]]:[br];break;case 68:case 73:this.$={type:"bgp",triples:at(T[E-2],[T[E-1]])};break;case 69:this.$={type:"group",patterns:[T[E-1]]};break;case 70:for(const $e of T[E-1].filter(Ue=>Ue.type==="bind")){const Ue=T[E-1].indexOf($e),Pe=new Set;for(const Ze of T[E-1].slice(0,Ue))(Ze.type==="group"||Ze.type==="bgp")&&Rn(Ze).forEach(Qe=>Pe.add(Qe));if(Pe.has($e.variable.value))throw Error("Variable used to bind is already bound (?"+$e.variable.value+")")}this.$={type:"group",patterns:T[E-1]};break;case 71:this.$=T[E-1]?at([T[E-1]],T[E]):at(T[E]);break;case 72:this.$=T[E]?[T[E-2],T[E]]:T[E-2];break;case 75:this.$=Oe(T[E],{type:"optional"});break;case 76:this.$=Oe(T[E],{type:"minus"});break;case 77:this.$=Oe(T[E],{type:"graph",name:T[E-1]});break;case 78:this.$=Oe(T[E],{type:"service",name:T[E-1],silent:!!T[E-2]});break;case 79:this.$={type:"filter",expression:T[E]};break;case 80:this.$={type:"bind",variable:T[E-1],expression:T[E-3]};break;case 89:this.$=rr(T[E]);break;case 90:this.$=void 0;break;case 91:this.$=T[E-1].length?{type:"union",patterns:at(T[E-1].map(Fr),[Fr(T[E])])}:T[E];break;case 95:this.$={...T[E],function:T[E-1]};break;case 96:this.$={type:"functionCall",args:[]};break;case 97:this.$={type:"functionCall",args:Pt(T[E-2],T[E-1]),distinct:!!T[E-3]};break;case 98:case 115:case 128:case 247:case 249:case 251:case 253:case 255:case 263:case 267:case 297:case 299:case 303:case 307:case 328:case 341:case 349:case 355:case 361:case 367:case 369:case 373:case 375:case 379:case 381:case 385:case 391:case 395:case 401:case 405:case 409:case 411:case 420:case 428:case 430:case 440:case 444:case 446:case 448:this.$=[];break;case 99:this.$=Pt(T[E-2],T[E-1]);break;case 101:this.$=at(T[E-2],[T[E-1]]);break;case 102:case 112:this.$=zr(T[E].map($e=>Oe(mt(T[E-1]),$e)));break;case 103:this.$=zr(Bt(T[E].map($e=>Oe(mt(T[E-1].entity),$e)),T[E-1].triples));break;case 105:this.$=at([T[E-1]],T[E]);break;case 106:this.$=at(T[E]);break;case 107:this.$=Ur(T[E-1],T[E]);break;case 109:case 237:this.$=De.factory.namedNode(Cn);break;case 110:case 118:this.$=Pt(T[E-1],T[E]);break;case 111:this.$=T[E]?{annotation:T[E],object:T[E-1]}:T[E-1];break;case 113:this.$=T[E]?zr(Bt(T[E].map($e=>Oe(mt(T[E-1].entity),$e)),T[E-1].triples)):T[E-1].triples;break;case 114:this.$=Ur(...T[E-1],T[E]);break;case 116:this.$=Ur(...T[E]);break;case 117:case 159:case 163:this.$=[T[E-1],T[E]];break;case 119:this.$=T[E]?{object:T[E-1],annotation:T[E]}:T[E-1];break;case 120:this.$=T[E-1].length?qt("|",Pt(T[E-1],T[E])):T[E];break;case 121:this.$=T[E-1].length?qt("/",Pt(T[E-1],T[E])):T[E];break;case 122:this.$=T[E]?qt(T[E],[T[E-1]]):T[E-1];break;case 123:this.$=T[E-1]?qt(T[E-1],[T[E]]):T[E];break;case 125:case 131:this.$=qt(T[E-1],[T[E]]);break;case 129:this.$=qt("|",Pt(T[E-2],T[E-1]));break;case 132:case 134:this.$=jn(T[E-1]);break;case 133:case 135:this.$=Un(T[E-1]);break;case 140:this.$={entity:T[E],triples:[]};break;case 145:this.$=$r(T[E]);break;case 149:this.$=De.factory.namedNode(gn);break;case 151:case 153:case 158:case 162:this.$=Dr(T[E-1],T[E]);break;case 152:this.$=["||",T[E]];break;case 154:this.$=["&&",T[E]];break;case 156:this.$=We(T[E-1],[T[E-2],T[E]]);break;case 157:this.$=We(T[E-2]?"notin":"in",[T[E-3],T[E]]);break;case 160:this.$=["+",Dr(T[E-1],T[E])];break;case 161:var wr=ct(T[E-1].value.replace("-",""),T[E-1].datatype);this.$=["-",Dr(wr,T[E])];break;case 164:this.$=We("UPLUS",[T[E]]);break;case 165:this.$=We(T[E-1],[T[E]]);break;case 166:this.$=We("UMINUS",[T[E]]);break;case 177:this.$=We(Ke(T[E-1]));break;case 178:this.$=We(Ke(T[E-3]),[T[E-1]]);break;case 179:this.$=rr(We(Ke(T[E-3]),[T[E-1]]));break;case 180:this.$=We(Ke(T[E-5]),[T[E-3],T[E-1]]);break;case 181:this.$=We(Ke(T[E-7]),[T[E-5],T[E-3],T[E-1]]);break;case 182:this.$=rr(We(Ke(T[E-7]),[T[E-5],T[E-3],T[E-1]]));break;case 183:this.$=We(Ke(T[E-1]),T[E]);break;case 184:this.$=We("bound",[$r(T[E-1])]);break;case 185:this.$=We(T[E-1],[]);break;case 186:this.$=We(T[E-3],[T[E-1]]);break;case 187:this.$=We(T[E-2]?"notexists":"exists",[Fr(T[E])]);break;case 188:case 189:this.$=zt(T[E-1],{type:"aggregate",aggregation:Ke(T[E-4]),distinct:!!T[E-2]});break;case 190:this.$=zt(T[E-2],{type:"aggregate",aggregation:Ke(T[E-5]),distinct:!!T[E-3],separator:typeof T[E-1]=="string"?T[E-1]:" "});break;case 192:this.$=ct(T[E]);break;case 193:this.$=$n(T[E-1],Ke(T[E].substr(1)));break;case 194:this.$=ct(T[E-2],T[E]);break;case 195:case 204:this.$=ct(T[E],mn);break;case 196:case 205:this.$=ct(T[E],yn);break;case 197:case 206:this.$=ct(Ke(T[E]),bn);break;case 200:this.$=ct(T[E].toLowerCase(),Pn);break;case 201:this.$=ct(T[E].substr(1),mn);break;case 202:this.$=ct(T[E].substr(1),yn);break;case 203:this.$=ct(T[E].substr(1).toLowerCase(),bn);break;case 207:case 208:this.$=Tn(T[E],1);break;case 209:case 210:this.$=Tn(T[E],3);break;case 211:this.$=De.factory.namedNode(er(T[E]));break;case 213:var _r=T[E].indexOf(":"),Be=T[E].substr(0,_r),lt=De.prefixes[Be];if(!lt)throw new Error("Unknown prefix: "+Be);var Dt=er(lt+T[E].substr(_r+1));this.$=De.factory.namedNode(Dt);break;case 214:if(T[E]=T[E].substr(0,T[E].length-1),!(T[E]in De.prefixes))throw new Error("Unknown prefix: "+T[E]);var Dt=er(De.prefixes[T[E]]);this.$=De.factory.namedNode(Dt);break;case 215:this.$=tr(T[E].replace(/^(_:)/,""));break;case 216:this.$=tr();break;case 217:case 218:case 232:this.$=rr(Lr(T[E-3],T[E-2],T[E-1]));break;case 230:case 231:this.$=rr(T[E-1]);break;case 248:case 250:case 252:case 254:case 256:case 260:case 264:case 268:case 270:case 292:case 294:case 296:case 298:case 300:case 302:case 304:case 306:case 329:case 342:case 356:case 368:case 370:case 372:case 374:case 392:case 402:case 425:case 427:case 429:case 431:case 441:case 445:case 447:case 449:T[E-1].push(T[E]);break;case 259:case 269:case 291:case 293:case 295:case 301:case 305:case 371:case 424:case 426:this.$=[T[E]];break;case 308:T[E-3].push(T[E-2]);break;case 350:case 362:case 376:case 380:case 382:case 386:case 396:case 406:case 410:case 412:case 421:T[E-2].push(T[E-1]);break}},table:[e(t,r,{3:1,4:2,10:3}),{1:[3]},e(i,[2,307],{5:4,7:5,321:6,214:7,8:8,96:9,215:10,17:11,21:12,97:16,38:17,6:[2,238],13:s,16:s,45:s,197:s,224:s,229:s,308:s,24:[1,13],32:[1,14],36:[1,15],41:o}),e([6,13,16,24,32,36,41,45,100,110,113,115,116,123,126,131,197,224,229,308,329,330,331,332,333],[2,3],{322:19,11:20,14:21,12:[1,22],15:[1,23]}),{6:[1,24]},{6:[2,240]},{6:[2,241]},{6:[2,242]},{6:[2,243],9:25,84:26,85:a},{6:[2,239]},e(c,[2,411],{216:28,217:29}),e(l,[2,249],{18:30}),e(l,[2,251],{22:31}),e(d,[2,255],{25:32,27:33,29:[1,34]}),{13:f,16:u,33:35,39:[1,37],44:39,55:40,87:p,139:38,307:43,308:g,323:36},e(l,[2,267],{37:46}),e(y,[2,326],{98:47,103:49,106:50,117:55,130:61,100:[1,48],110:[1,51],113:[1,52],115:[1,53],116:[1,54],131:[1,62],329:[1,56],330:[1,57],331:[1,58],332:[1,59],333:[1,60]}),{39:[1,63],40:64,43:65,44:66,45:w,87:p},e(_,[2,273],{42:68,324:69,325:[1,70],326:[1,71]}),e(t,[2,248]),e(t,[2,245]),e(t,[2,246]),{13:[1,72]},{16:[1,73]},{1:[2,1]},{6:[2,2]},{6:[2,244]},{45:[1,77],85:[1,78],86:74,87:[1,75],89:[1,76]},e([6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312],[2,120],{337:[1,79]}),e(R,[2,418],{218:80,222:81,229:[1,82]}),{19:83,28:b,29:C,52:84,53:P,56:85},{19:88,28:b,29:C,52:89,53:P,56:85},e(l,[2,253],{26:90}),{28:[1,91],52:92,53:P},e(H,[2,385],{181:93,182:94,183:95,31:[2,383]}),e(M,[2,263],{34:96}),e(M,[2,261],{44:39,55:40,307:43,139:97,13:f,16:u,87:p,308:g}),e(M,[2,262]),e(re,[2,259]),e(he,[2,143]),e(he,[2,144]),e([6,13,16,28,29,31,39,45,47,48,53,63,70,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,197,224,229,231,232,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,317,318,335,338,341,342,343,344,345,346,347,348,349,350,351],[2,145]),e(V,[2,211]),e(V,[2,212]),e(V,[2,213]),e(V,[2,214]),{19:98,28:b,29:C,52:99,53:P,56:85},{6:[2,309],99:100,193:[1,101]},e(q,[2,311],{101:102,328:[1,103]}),e(ie,[2,317],{104:104,328:[1,105]}),e(U,[2,322],{107:106,328:[1,107]}),{111:108,112:[2,324],328:[1,109]},{29:ce,114:110},{29:ce,114:112},{29:ce,114:113},{118:114,123:[1,115],125:116,126:Se},e(me,[2,315]),e(me,[2,316]),e(Ne,[2,319]),e(Ne,[2,320]),e(Ne,[2,321]),e(y,[2,327]),{13:f,16:u,55:118,307:43,308:g},e(l,[2,12]),e(l,[2,13],{44:66,43:119,45:w,87:p}),e(te,[2,269]),e(te,[2,15]),{13:f,16:u,44:136,45:ae,46:120,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(_,[2,14]),e(_,[2,274]),e(_,[2,271]),e(_,[2,272]),e(t,[2,4]),{13:[1,177]},e(Fe,[2,39]),{29:[1,178]},{29:[1,179]},{87:[1,181],91:180},{45:[1,187],87:[1,185],89:[1,186],93:182,165:183,166:184},e(c,[2,410]),e([6,13,16,45,48,82,87,89,231,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,337],[2,121],{338:[1,188]}),{13:f,16:u,45:[1,193],55:194,197:je,219:189,220:190,223:191,224:[1,192],307:43,308:g},e(R,[2,419]),e(Le,Ft,{20:196,59:197,69:198,70:Qt}),e(l,[2,250]),{29:rt,57:200},e(q,[2,279],{54:202,327:[1,203]}),{29:[2,282]},e(Xe,bt,{23:204,58:205,62:206,63:wt}),e(l,[2,252]),{19:208,28:b,29:C,52:209,53:P,56:85},{29:[1,210]},e(d,[2,256]),{31:[1,211]},{31:[2,384]},{13:f,16:u,44:215,45:ut,55:220,82:x,87:p,89:Ye,145:212,172:221,185:213,187:214,231:v,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(ve,[2,265],{56:85,35:227,52:228,19:229,28:b,29:C,53:P}),e(re,[2,260]),e(Xe,bt,{58:205,62:206,23:230,63:wt}),e(l,[2,268]),{6:[2,45]},e(t,r,{10:3,4:231}),{13:f,16:u,55:232,307:43,308:g},e(q,[2,312]),{105:233,112:Me,122:234,132:[1,237],134:235,327:[1,238],334:[1,239]},e(ie,[2,318]),e(q,Ge,{108:240,133:242,112:Gt,132:it}),e(U,[2,323]),{112:[1,244]},{112:[2,325]},e(ze,[2,50]),e(H,Lt,{135:245,136:246,143:247,144:248,31:Ht,112:Ht}),e(ze,[2,51]),e(ze,[2,52]),e(nt,[2,328],{119:249}),{29:ce,114:250},e(nt,[2,56]),{29:ce,114:251},e(y,[2,59]),e(te,[2,270]),{47:[1,252]},e(jt,[2,150]),e(_t,[2,428],{240:253}),e(st,[2,430],{244:254}),e(st,[2,155],{248:255,249:256,250:[2,438],290:[1,257],341:[1,258],342:[1,259],343:[1,260],344:[1,261],345:[1,262],346:[1,263]}),e(et,[2,440],{252:264}),e(ke,[2,448],{260:265}),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,255:154,257:155,264:266,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,255:154,257:155,264:267,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,255:154,257:155,264:268,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(ke,[2,167]),e(ke,[2,168]),e(ke,[2,169]),e(ke,[2,170],{176:269,45:tt,89:Zr}),e(ke,[2,171]),e(ke,[2,172]),e(ke,[2,173]),e(ke,[2,174]),{13:f,16:u,44:136,45:ae,46:272,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(qe,[2,176]),{89:[1,273]},{45:[1,274]},{45:[1,275]},{45:[1,276]},{45:[1,277]},{45:[1,278]},{45:Qr,89:Gr,179:279},{45:[1,282]},{45:[1,284],89:[1,283]},{279:[1,285]},e(He,[2,192],{292:[1,286],293:[1,287]}),e(He,[2,195]),e(He,[2,196]),e(He,[2,197]),e(He,[2,198]),e(He,[2,199]),e(He,[2,200]),{13:f,16:u,44:39,55:40,82:x,87:p,139:289,172:291,255:154,257:155,266:290,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,320:288},{45:[1,292]},{45:[1,293]},{45:[1,294]},e(Kt,[2,452]),e(Kt,[2,453]),e(Kt,[2,454]),e(Kt,[2,455]),e(Kt,[2,456]),{279:[2,458]},e(nr,[2,207]),e(nr,[2,208]),e(nr,[2,209]),e(nr,[2,210]),e(He,[2,201]),e(He,[2,202]),e(He,[2,203]),e(He,[2,204]),e(He,[2,205]),e(He,[2,206]),e(t,[2,5]),e(ir,[2,297],{88:295}),e(sr,[2,299],{90:296}),{48:[1,297],87:[1,298]},e(or,[2,301]),e(Fe,[2,43]),e(Fe,[2,82]),e(Fe,[2,83]),{29:[1,299]},{29:[1,300]},{87:[1,302],169:301},e(c,[2,412]),e(Et,[2,123]),e(Et,[2,416],{221:303,339:304,39:[1,306],263:[1,307],340:[1,305]}),e(ot,[2,124]),{13:f,16:u,45:[1,311],55:194,89:[1,310],197:je,223:312,225:308,226:309,229:Hr,307:43,308:g},e(c,s,{215:10,214:314}),e(ot,[2,236]),e(ot,[2,237]),e(Ut,[2,6]),e(Er,[2,287],{60:315,72:316,73:[1,317]}),e(Le,[2,286]),{13:f,16:u,45:ae,55:323,67:321,68:322,71:318,77:320,79:319,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,307:43,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe},e([6,31,63,70,73,81,83,85],[2,20]),e(H,Kr,{38:17,49:324,147:325,17:326,21:327,148:328,154:329,155:330,29:dt,31:dt,85:dt,112:dt,159:dt,160:dt,161:dt,163:dt,164:dt,41:o}),{13:f,16:u,55:331,307:43,308:g},e(q,[2,280]),e(Ut,[2,7]),e(Le,Ft,{59:197,69:198,20:332,70:Qt}),e(Xe,[2,284]),{64:[1,333]},e(Xe,bt,{58:205,62:206,23:334,63:wt}),e(l,[2,254]),e(H,Lt,{144:248,30:335,143:336,31:[2,257]}),e(l,[2,100]),{31:[2,387],184:337,335:[1,338]},{13:f,16:u,44:39,55:40,87:p,139:342,186:339,190:340,195:341,197:It,307:43,308:g},e(Jt,[2,389],{44:39,55:40,307:43,190:340,195:341,139:342,188:344,189:345,186:346,13:f,16:u,87:p,197:It,308:g}),e(ft,[2,227]),e(ft,[2,228]),e(ft,[2,229]),{13:f,16:u,44:215,45:ut,55:220,82:x,87:p,89:Ye,172:221,185:351,187:350,200:348,230:347,231:v,234:349,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},{13:f,16:u,44:39,55:40,87:p,139:342,186:352,190:340,195:341,197:It,307:43,308:g},e(ft,[2,146]),e(ft,[2,147]),e(ft,[2,148]),e(ft,[2,149]),{13:f,16:u,44:354,55:355,82:x,87:p,172:357,237:356,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:358,312:ue,313:353},e(Ir,[2,215]),e(Ir,[2,216]),e(Xe,bt,{58:205,62:206,23:359,63:wt}),e(M,[2,264]),e(ve,[2,266]),e(Ut,[2,11]),e(i,[2,308],{6:[2,310]}),e(ze,[2,313],{102:360,120:361,121:[1,362]}),e(ze,[2,47]),e(ze,[2,63]),e(ze,[2,64]),{13:f,16:u,55:363,307:43,308:g},e(ze,[2,336]),e(ze,[2,337]),e(ze,[2,338]),{109:[1,364]},e(Jr,[2,60]),{13:f,16:u,55:365,307:43,308:g},e(q,[2,335]),{13:f,16:u,55:366,307:43,308:g},{31:[1,367]},e(vt,[2,341],{137:368}),e(vt,[2,340]),{13:f,16:u,44:215,45:ut,55:220,82:x,87:p,89:Ye,145:369,172:221,185:213,187:214,231:v,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},{28:[1,370],127:371,128:[1,372]},e(nt,[2,330],{124:373,125:374,126:Se}),e(nt,[2,57]),{44:375,87:p},e(jt,[2,151],{241:376,242:[1,377]}),e(_t,[2,153],{245:378,246:[1,379]}),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,247:380,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{250:[1,381]},e(Ve,[2,432]),e(Ve,[2,433]),e(Ve,[2,434]),e(Ve,[2,435]),e(Ve,[2,436]),e(Ve,[2,437]),{250:[2,439]},e([47,48,193,242,246,250,272,290,341,342,343,344,345,346],[2,158],{253:382,254:383,255:384,257:385,263:[1,386],265:[1,387],297:N,298:z,299:K,300:j,301:we,302:Ee}),e(et,[2,162],{261:388,262:389,39:vr,338:xr}),e(ke,[2,164]),e(ke,[2,165]),e(ke,[2,166]),e(qe,[2,95]),e(qe,[2,96]),e(Ve,[2,377],{177:392,325:[1,393]}),{48:[1,394]},e(qe,[2,177]),{13:f,16:u,44:136,45:ae,46:395,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:396,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:397,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:398,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:399,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(qe,[2,183]),e(qe,[2,98]),e(Ve,[2,381],{180:400}),{87:[1,401]},e(qe,[2,185]),{13:f,16:u,44:136,45:ae,46:402,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{29:rt,57:403},e(He,[2,193]),{13:f,16:u,55:404,307:43,308:g},{13:f,16:u,44:39,55:40,87:p,139:342,195:405,197:It,307:43,308:g},e(St,[2,233]),e(St,[2,234]),e(St,[2,235]),e(Xr,[2,459],{281:406,325:[1,407]}),e(Ve,[2,463],{284:408,325:[1,409]}),e(Ve,[2,465],{286:410,325:[1,411]}),{13:f,16:u,31:[1,412],55:414,82:x,171:413,172:415,173:416,174:ar,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:cr},{31:[1,419],89:[1,420]},{29:[1,421]},e(or,[2,302]),e(ir,[2,367],{167:422}),e(sr,[2,369],{168:423}),{48:[1,424],87:[1,425]},e(or,[2,371]),e(Et,[2,122]),e(Et,[2,417]),e(Et,[2,413]),e(Et,[2,414]),e(Et,[2,415]),e(ot,[2,125]),e(ot,[2,127]),e(ot,[2,128]),e(Yr,[2,420],{227:426}),e(ot,[2,130]),{13:f,16:u,55:194,197:je,223:427,307:43,308:g},{48:[1,428]},e(Tt,[2,289],{61:429,80:430,81:[1,431],83:[1,432]}),e(Er,[2,288]),{64:[1,433]},e(Le,[2,29],{307:43,267:139,275:146,278:149,77:320,67:321,68:322,55:323,79:434,13:f,16:u,45:ae,268:le,269:pe,270:Re,271:_e,273:B,274:Z,276:oe,277:ye,279:ge,280:D,283:F,285:k,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe}),e(en,[2,293]),e(Cr,[2,92]),e(Cr,[2,93]),e(Cr,[2,94]),{45:tt,89:Zr,176:269},{31:[1,435]},{31:[1,436]},{19:437,28:b,29:C,56:85},{19:438,28:b,29:C,56:85},e(xt,[2,355],{149:439}),e(xt,[2,354]),{13:f,16:u,44:215,45:lr,55:220,82:x,87:p,89:Ye,156:440,172:221,185:441,203:442,231:ur,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(M,[2,19]),e(Tt,[2,21]),{13:f,16:u,44:450,45:tn,55:323,65:445,66:446,67:447,68:448,87:p,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,307:43,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe},e(Ut,[2,8]),{31:[1,451]},{31:[2,258]},{31:[2,101]},e(H,[2,386],{31:[2,388]}),e(Jt,[2,102]),e(Ct,[2,391],{191:452}),e(H,[2,395],{196:453,198:454}),e(H,[2,108]),e(H,[2,109]),e(Jt,[2,103]),e(Jt,[2,104]),e(Jt,[2,390]),{13:f,16:u,44:215,45:ut,48:[1,455],55:220,82:x,87:p,89:Ye,172:221,185:351,187:350,200:456,231:v,234:349,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(dr,[2,424]),e(rn,[2,136]),e(rn,[2,137]),e(Ar,[2,140]),{232:[1,457]},{13:f,16:u,44:39,55:40,87:p,139:342,195:458,197:It,307:43,308:g},e(St,[2,219]),e(St,[2,220]),e(St,[2,221]),e(St,[2,222]),e(St,[2,223]),e(Ut,[2,10]),e(ze,[2,46]),e(ze,[2,314]),{112:Me,122:459},e(ze,[2,62]),e(q,Ge,{133:242,108:460,112:Gt,132:it}),e(Jr,[2,61]),e(ze,[2,49]),e([6,28,126,128,193],[2,65]),{31:[2,66],112:[1,462],138:461},e(vt,[2,351],{146:463,335:[1,464]}),{29:rt,57:465},e(nt,[2,329]),e(q,[2,332],{129:466,327:[1,467]}),e(nt,[2,55]),e(nt,[2,331]),{48:[1,468]},e(_t,[2,429]),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,239:469,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(st,[2,431]),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,243:470,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(st,[2,156]),{45:Qr,89:Gr,179:471},e(et,[2,441]),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,251:472,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(ke,[2,444],{256:473}),e(ke,[2,446],{258:474}),e(Ve,[2,442]),e(Ve,[2,443]),e(ke,[2,449]),{13:f,16:u,44:136,45:ae,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,255:154,257:155,259:475,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(Ve,[2,450]),e(Ve,[2,451]),e(Ve,[2,379],{178:476}),e(Ve,[2,378]),e([6,13,16,29,31,39,45,47,48,73,76,78,81,82,83,85,87,89,112,159,160,161,163,164,193,231,242,246,250,263,265,268,269,270,271,272,273,274,276,277,279,280,283,285,290,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,335,338,341,342,343,344,345,346,347,348,349,350,351],[2,175]),{48:[1,477]},{48:[1,478]},{272:[1,479]},{272:[1,480]},{272:[1,481]},{13:f,16:u,44:136,45:ae,46:482,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{48:[1,483]},{48:[1,484]},e(qe,[2,187]),e(He,[2,194]),{13:f,16:u,44:39,55:40,82:x,87:p,139:289,172:291,255:154,257:155,266:290,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,320:485},{13:f,16:u,39:[1,487],44:136,45:ae,46:488,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,282:486,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(Xr,[2,460]),{13:f,16:u,44:136,45:ae,46:489,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(Ve,[2,464]),{13:f,16:u,44:136,45:ae,46:490,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(Ve,[2,466]),e(Fe,[2,40]),e(ir,[2,298]),e(Xt,[2,87]),e(Xt,[2,88]),e(Xt,[2,89]),e(Xt,[2,90]),{13:f,16:u,55:492,82:x,172:493,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,311:494,312:ue,315:491},e(Fe,[2,41]),e(sr,[2,300]),e(Yt,[2,303],{92:495}),{13:f,16:u,31:[1,496],55:414,82:x,171:497,172:415,173:416,174:ar,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:cr},{31:[1,498],89:[1,499]},{29:[1,500]},e(or,[2,372]),{13:f,16:u,48:[2,422],55:194,197:je,223:312,226:502,228:501,229:Hr,307:43,308:g},e(ot,[2,131]),e(ot,[2,126]),e(Tt,[2,22]),e(Tt,[2,290]),{82:[1,503]},{82:[1,504]},{13:f,16:u,44:510,45:ae,55:323,67:321,68:322,74:505,75:506,76:nn,77:320,78:sn,79:509,87:p,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,307:43,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe},e(en,[2,294]),e(on,[2,69]),e(on,[2,70]),e(Le,Ft,{59:197,69:198,20:511,70:Qt}),e(Xe,bt,{58:205,62:206,23:512,63:wt}),{29:[2,375],31:[2,71],84:522,85:a,112:[1,518],150:513,151:514,158:515,159:[1,516],160:[1,517],161:[1,519],163:[1,520],164:[1,521],175:523},e(xt,[2,363],{157:524,335:[1,525]}),e(c,s,{215:10,202:526,205:527,208:528,214:529,44:530,87:p}),e(fr,[2,399],{215:10,205:527,208:528,214:529,44:530,204:531,202:532,13:s,16:s,45:s,197:s,224:s,229:s,308:s,87:p}),{13:f,16:u,44:215,45:lr,55:220,82:x,87:p,89:Ye,172:221,185:351,203:536,212:534,231:ur,233:533,234:535,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(c,s,{215:10,205:527,208:528,214:529,44:530,202:537,87:p}),e(Xe,[2,23],{307:43,267:139,275:146,278:149,55:323,67:447,68:448,44:450,66:538,13:f,16:u,45:tn,87:p,268:le,269:pe,270:Re,271:_e,273:B,274:Z,276:oe,277:ye,279:ge,280:D,283:F,285:k,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe}),e(At,[2,291]),e(At,[2,24]),e(At,[2,25]),{13:f,16:u,44:136,45:ae,46:539,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(At,[2,28]),e(Xe,bt,{58:205,62:206,23:540,63:wt}),e([31,112,232,318,335],[2,105],{192:541,193:[1,542]}),e(Ct,[2,107]),{13:f,16:u,44:215,45:ut,55:220,82:x,87:p,89:Ye,172:221,185:351,187:350,199:543,200:544,231:v,234:349,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(an,[2,132]),e(dr,[2,425]),e(an,[2,133]),{13:f,16:u,44:354,55:355,82:x,87:p,172:357,237:356,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:358,312:ue,313:545},e(ze,[2,54]),e(ze,[2,48]),e(vt,[2,342]),{13:f,16:u,44:39,55:40,87:p,139:546,307:43,308:g},e(vt,[2,68]),e(H,[2,350],{31:cn,112:cn}),e(ze,[2,53]),{13:f,16:u,55:547,307:43,308:g},e(q,[2,333]),e(te,[2,16]),e(_t,[2,152]),e(st,[2,154]),e(st,[2,157]),e(et,[2,159]),e(et,[2,160],{262:389,261:548,39:vr,338:xr}),e(et,[2,161],{262:389,261:549,39:vr,338:xr}),e(ke,[2,163]),{13:f,16:u,44:136,45:ae,46:550,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(qe,[2,178]),e(qe,[2,179]),{13:f,16:u,44:136,45:ae,46:551,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:552,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:553,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{48:[1,554],272:[1,555]},e(qe,[2,184]),e(qe,[2,186]),{314:[1,556]},{48:[1,557]},{48:[2,461]},{48:[2,462]},{48:[1,558]},{48:[2,467],193:[1,561],287:559,288:560},{13:f,16:u,55:194,197:je,223:562,307:43,308:g},e(Nr,[2,224]),e(Nr,[2,225]),e(Nr,[2,226]),{31:[1,563],45:ln,94:564},e(Fe,[2,84]),e(ir,[2,368]),e(Fe,[2,85]),e(sr,[2,370]),e(Yt,[2,373],{170:566}),{48:[1,567]},{48:[2,423],337:[1,568]},e(Tt,[2,35],{83:[1,569]}),e(Tt,[2,36],{81:[1,570]}),e(Er,[2,30],{307:43,267:139,275:146,278:149,77:320,67:321,68:322,55:323,79:509,44:510,75:571,13:f,16:u,45:ae,76:nn,78:sn,87:p,268:le,269:pe,270:Re,271:_e,273:B,274:Z,276:oe,277:ye,279:ge,280:D,283:F,285:k,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe}),e(kt,[2,295]),{45:ae,77:572},{45:ae,77:573},e(kt,[2,33]),e(kt,[2,34]),{31:[2,275],50:574,84:575,85:a},{31:[2,277],51:576,84:577,85:a},e(xt,[2,356]),e(un,[2,357],{152:578,335:[1,579]}),e(ht,[2,74]),{29:rt,57:580},{29:rt,57:581},{13:f,16:u,44:39,55:40,87:p,139:582,307:43,308:g},e(dn,[2,365],{162:583,328:[1,584]}),{13:f,16:u,45:ae,55:323,67:321,68:322,77:320,79:585,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,307:43,308:g,346:I,347:$,348:L,349:W,350:Te,351:xe},{45:[1,586]},e(ht,[2,81]),{29:rt,57:587},e(xt,[2,73]),e(H,[2,362],{29:pt,31:pt,85:pt,112:pt,159:pt,160:pt,161:pt,163:pt,164:pt}),e(fr,[2,112]),e(Ot,[2,401],{206:588}),e(H,[2,405],{209:589,210:590}),e(H,[2,403]),e(H,[2,404]),e(fr,[2,113]),e(fr,[2,400]),{13:f,16:u,44:215,45:lr,48:[1,591],55:220,82:x,87:p,89:Ye,172:221,185:351,203:536,212:592,231:ur,234:535,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(dr,[2,426]),e(Ar,[2,138]),e(Ar,[2,139]),{232:[1,593]},e(At,[2,292]),{47:[1,595],48:[1,594]},e(Ut,[2,9]),e(Ct,[2,392]),e(Ct,[2,393],{44:39,55:40,307:43,195:341,139:342,194:596,190:597,13:f,16:u,87:p,197:It,308:g}),e(Ct,[2,110],{272:[1,598]}),e(hr,[2,397],{201:599,316:600,317:[1,601]}),{314:[1,602]},{29:[1,603]},e(nt,[2,58]),e(ke,[2,445]),e(ke,[2,447]),{48:[1,604],272:[1,605]},{48:[1,606]},{272:[1,607]},{272:[1,608]},e(qe,[2,99]),e(Ve,[2,382]),e([13,16,39,47,48,87,193,197,242,246,250,263,265,272,290,297,298,299,300,301,302,308,314,338,341,342,343,344,345,346],[2,232]),e(qe,[2,188]),e(qe,[2,189]),{48:[1,609]},{48:[2,468]},{289:[1,610]},{13:f,16:u,55:492,82:x,172:493,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,311:494,312:ue,315:611},e(Fe,[2,42]),e(Yt,[2,304]),{13:f,16:u,55:414,82:x,95:612,171:613,172:415,173:416,174:ar,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:cr},{31:[1,614],45:ln,94:615},e(ot,[2,129]),e(Yr,[2,421]),{82:[1,616]},{82:[1,617]},e(kt,[2,296]),e(kt,[2,31]),e(kt,[2,32]),{31:[2,17]},{31:[2,276]},{31:[2,18]},{31:[2,278]},e(H,Kr,{155:330,153:618,154:619,29:gt,31:gt,85:gt,112:gt,159:gt,160:gt,161:gt,163:gt,164:gt}),e(un,[2,358]),e(ht,[2,75]),e(ht,[2,76]),{29:rt,57:620},{13:f,16:u,44:39,55:40,87:p,139:621,307:43,308:g},e(dn,[2,366]),e(ht,[2,79]),{13:f,16:u,44:136,45:ae,46:622,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(ht,[2,91],{336:[1,623]}),e([29,31,85,112,159,160,161,163,164,232,318,335],[2,114],{207:624,193:[1,625]}),e(Ot,[2,117]),{13:f,16:u,44:215,45:lr,55:220,82:x,87:p,89:Ye,172:221,185:351,203:536,211:626,212:627,231:ur,234:535,236:216,237:222,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,309:A,310:de,311:217,312:ue},e(ft,[2,134]),e(dr,[2,427]),e(ft,[2,135]),e(At,[2,26]),{44:628,87:p},e(Ct,[2,106]),e(Ct,[2,394]),e(H,[2,396]),e(hr,[2,111]),e(hr,[2,398]),{13:f,16:u,44:39,55:40,87:p,139:342,186:629,190:340,195:341,197:It,307:43,308:g},e(Ir,[2,217]),e(H,Lt,{144:248,140:630,143:631,31:[2,343]}),e(qe,[2,97]),e(Ve,[2,380]),e(qe,[2,180]),{13:f,16:u,44:136,45:ae,46:632,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},{13:f,16:u,44:136,45:ae,46:633,55:133,67:132,68:134,77:131,82:x,87:p,172:135,224:O,238:121,239:122,243:123,247:124,251:125,255:154,257:155,259:126,263:se,264:130,265:G,266:137,267:139,268:le,269:pe,270:Re,271:_e,273:B,274:Z,275:146,276:oe,277:ye,278:149,279:ge,280:D,283:F,285:k,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:m,346:I,347:$,348:L,349:W,350:Te,351:xe},e(qe,[2,190]),{290:[1,634]},{314:[1,635]},{13:f,16:u,48:[1,636],55:414,82:x,171:637,172:415,173:416,174:ar,255:154,257:155,291:150,294:ee,295:J,296:X,297:N,298:z,299:K,300:j,301:we,302:Ee,303:be,304:Ie,305:S,306:h,307:43,308:g,312:cr},e(fn,[2,305]),e(Fe,[2,86]),e(Yt,[2,374]),e(Tt,[2,37]),e(Tt,[2,38]),e(xt,[2,72]),e(xt,[2,360]),e(ht,[2,77]),{29:rt,57:638},{47:[1,639]},{29:[2,376]},e(Ot,[2,402]),e(Ot,[2,115],{215:10,208:528,214:529,44:530,205:640,13:s,16:s,45:s,197:s,224:s,229:s,308:s,87:p}),e(Ot,[2,118],{272:[1,641]}),e(pr,[2,407],{213:642,319:643,317:[1,644]}),{48:[1,645]},{318:[1,646]},{31:[1,647]},{31:[2,344]},{48:[1,648]},{48:[1,649]},{291:650,303:be,304:Ie,305:S,306:h},e(Xt,[2,218]),e(Yt,[2,44]),e(fn,[2,306]),e(ht,[2,78]),{44:651,87:p},e(Ot,[2,116]),e(H,[2,406]),e(pr,[2,119]),e(pr,[2,408]),e(c,s,{215:10,205:527,208:528,214:529,44:530,202:652,87:p}),e(At,[2,27]),e(hr,[2,230]),e(hn,[2,345],{141:653,335:[1,654]}),e(qe,[2,181]),e(qe,[2,182]),{48:[2,191]},{48:[1,655]},{318:[1,656]},e(H,Lt,{144:248,142:657,143:658,31:pn,112:pn}),e(hn,[2,346]),e(ht,[2,80]),e(pr,[2,231]),e(vt,[2,67]),e(vt,[2,348])],defaultActions:{5:[2,240],6:[2,241],7:[2,242],9:[2,239],24:[2,1],25:[2,2],26:[2,244],87:[2,282],94:[2,384],100:[2,45],109:[2,325],166:[2,458],263:[2,439],336:[2,258],337:[2,101],487:[2,461],488:[2,462],560:[2,468],574:[2,17],575:[2,276],576:[2,18],577:[2,278],623:[2,376],631:[2,344],650:[2,191]},parseError:function(Q,ne){if(ne.recoverable)this.trace(Q);else{var fe=new Error(Q);throw fe.hash=ne,fe}},parse:function(Q){var ne=this,fe=[0],Ce=[null],Ae=[],T=this.table,Je="",E=0,Rt=0,br=2,wr=1,_r=Ae.slice.call(arguments,1),Be=Object.create(this.lexer),lt={yy:{}};for(var Dt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Dt)&&(lt.yy[Dt]=this.yy[Dt]);Be.setInput(Q,lt.yy),lt.yy.lexer=Be,lt.yy.parser=this,typeof Be.yylloc>"u"&&(Be.yylloc={});var Wt=Be.yylloc;Ae.push(Wt);var Vr=Be.options&&Be.options.ranges;typeof lt.yy.parseError=="function"?this.parseError=lt.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var Sr=function(){var Zt;return Zt=Be.lex()||wr,typeof Zt!="number"&&(Zt=ne.symbols_[Zt]||Zt),Zt},$e,Ue,Pe,Ze,Qe={},Tr,yt,vn,Rr;;){if(Ue=fe[fe.length-1],this.defaultActions[Ue]?Pe=this.defaultActions[Ue]:(($e===null||typeof $e>"u")&&($e=Sr()),Pe=T[Ue]&&T[Ue][$e]),typeof Pe>"u"||!Pe.length||!Pe[0]){var Mr="";Rr=[];for(Tr in T[Ue])this.terminals_[Tr]&&Tr>br&&Rr.push("'"+this.terminals_[Tr]+"'");Be.showPosition?Mr="Parse error on line "+(E+1)+`:
43
+ `+Be.showPosition()+`
44
+ Expecting `+Rr.join(", ")+", got '"+(this.terminals_[$e]||$e)+"'":Mr="Parse error on line "+(E+1)+": Unexpected "+($e==wr?"end of input":"'"+(this.terminals_[$e]||$e)+"'"),this.parseError(Mr,{text:Be.match,token:this.terminals_[$e]||$e,line:Be.yylineno,loc:Wt,expected:Rr})}if(Pe[0]instanceof Array&&Pe.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Ue+", token: "+$e);switch(Pe[0]){case 1:fe.push($e),Ce.push(Be.yytext),Ae.push(Be.yylloc),fe.push(Pe[1]),$e=null,Rt=Be.yyleng,Je=Be.yytext,E=Be.yylineno,Wt=Be.yylloc;break;case 2:if(yt=this.productions_[Pe[1]][1],Qe.$=Ce[Ce.length-yt],Qe._$={first_line:Ae[Ae.length-(yt||1)].first_line,last_line:Ae[Ae.length-1].last_line,first_column:Ae[Ae.length-(yt||1)].first_column,last_column:Ae[Ae.length-1].last_column},Vr&&(Qe._$.range=[Ae[Ae.length-(yt||1)].range[0],Ae[Ae.length-1].range[1]]),Ze=this.performAction.apply(Qe,[Je,Rt,E,lt.yy,Pe[1],Ce,Ae].concat(_r)),typeof Ze<"u")return Ze;yt&&(fe=fe.slice(0,-1*yt*2),Ce=Ce.slice(0,-1*yt),Ae=Ae.slice(0,-1*yt)),fe.push(this.productions_[Pe[1]][0]),Ce.push(Qe.$),Ae.push(Qe._$),vn=T[fe[fe.length-2]][fe[fe.length-1]],fe.push(vn);break;case 3:return!0}}return!0}},gr=requireWildcard().Wildcard,mr="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Cn=mr+"type",An=mr+"first",Nn=mr+"rest",gn=mr+"nil",yr="http://www.w3.org/2001/XMLSchema#",mn=yr+"integer",yn=yr+"decimal",bn=yr+"double",Pn=yr+"boolean",Nt="",wn="",_n="";function Ke(Y){return Y.toLowerCase()}function Pt(Y,Q){return Y.push(Q),Y}function Bt(Y,Q){return Y.push.apply(Y,Q),Y}function Oe(Y){Y||(Y={});for(var Q=1,ne=arguments.length,fe;Q<ne&&(fe=arguments[Q]||{});Q++)for(var Ce in fe)Y[Ce]=fe[Ce];return Y}function at(){for(var Y=[],Q=0,ne=arguments.length;Q<ne;Q++)Y=Y.concat.apply(Y,arguments[Q]);return Y}function er(Y){if(Y[0]==="<"&&(Y=Y.substring(1,Y.length-1)),/^[a-z][a-z0-9.+-]*:/i.test(Y))return Y;if(!De.base)throw new Error("Cannot resolve relative IRI "+Y+" because no base IRI was set.");switch(Nt!==De.base&&(Nt=De.base,wn=Nt.replace(/[^\/:]*$/,""),_n=Nt.match(/^(?:[a-z]+:\/*)?[^\/]*/)[0]),Y[0]){case void 0:return Nt;case"#":return Nt+Y;case"?":return Nt.replace(/(?:\?.*)?$/,Y);case"/":return _n+Y;default:return wn+Y}}function $r(Y){if(Y){var Q=Y[0];if(Q==="?"||Q==="$")return De.factory.variable(Y.substr(1))}return Y}function We(Y,Q){return{type:"operation",operator:Y,args:Q||[]}}function zt(Y,Q){var ne={expression:Y==="*"?new gr:Y};if(Q)for(var fe in Q)ne[fe]=Q[fe];return ne}function qt(Y,Q){return{type:"path",pathType:Y,items:Q}}function Dr(Y,Q){for(var ne=0,fe=Q.length,Ce;ne<fe&&(Ce=Q[ne]);ne++)Y=We(Ce[0],[Y,Ce[1]]);return Y}function $t(Y,Q){var ne=[],fe=[],Ce=Y.length,Ae,T={};if(!Ce)return null;for(var Je=0;Je<Ce&&(Ae=Y[Je]);Je++)(Ae.named?fe:ne).push(Ae.iri);return T[Q||"from"]={default:ne,named:fe},T}function Vt(Y){return parseInt(Y,10)}function Fr(Y){return Y.type==="group"&&Y.patterns.length===1?Y.patterns[0]:Y}function ct(Y,Q){return Q&&Q.termType!=="NamedNode"&&(Q=De.factory.namedNode(Q)),De.factory.literal(Y,Q)}function $n(Y,Q){return De.factory.literal(Y,Q)}function Lr(Y,Q,ne){if(!("termType"in Q))throw new Error("Nested triples cannot contain paths");return De.factory.quad(Y,Q,ne)}function mt(Y,Q,ne,fe){var Ce={};return Y!=null&&(Ce.subject=Y),Q!=null&&(Ce.predicate=Q),ne!=null&&(Ce.object=ne),fe!=null&&(Ce.annotations=fe),Ce}function tr(Y){return typeof Y=="string"?Y.startsWith("e_")?De.factory.blankNode(Y):De.factory.blankNode("e_"+Y):De.factory.blankNode("g_"+Sn++)}var Sn=0;De._resetBlanks=function(){Sn=0};var Dn=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\(.)/g,Fn={"\\":"\\","'":"'",'"':'"',t:" ",b:"\b",n:`
45
+ `,r:"\r",f:"\f"},Ln=/[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/,jr=String.fromCharCode;function Tn(Y,Q){Y=Y.substring(Q,Y.length-Q);try{Y=Y.replace(Dn,function(ne,fe,Ce,Ae){var T;if(fe){if(T=parseInt(fe,16),isNaN(T))throw new Error;return jr(T)}else if(Ce){if(T=parseInt(Ce,16),isNaN(T))throw new Error;return T<65535?jr(T):jr(55296+((T-=65536)>>10),56320+(T&1023))}else{var Je=Fn[Ae];if(!Je)throw new Error;return Je}})}catch{return""}if(Ln.exec(Y))throw new Error("Invalid unicode codepoint of surrogate pair without corresponding codepoint in "+Y);return Y}function jn(Y){var Q=tr(),ne=Q,fe=[],Ce,Ae=[];Y.forEach(function(Rt){fe.push(Rt.entity),Bt(Ae,Rt.triples)});for(var T=0,Je=0,E=fe.length,Ce=Array(E*2);T<E;)Ce[Je++]=mt(ne,De.factory.namedNode(An),fe[T]),Ce[Je++]=mt(ne,De.factory.namedNode(Nn),ne=++T<E?tr():De.factory.namedNode(gn));return{entity:Q,triples:Bt(Ce,Ae)}}function Un(Y){var Q=tr();return{entity:Q,triples:Y.map(function(ne){return Oe(mt(Q),ne)})}}function Ur(Y,Q,ne){var fe=[],Ce=[];return Q.forEach(function(Ae){let T=null;Ae.annotation&&(T=Ae.annotation,Ae=Ae.object),fe.push(mt(null,Y,Ae.entity,T)),Bt(Ce,Ae.triples)}),at(fe,ne||[],Ce)}function Mt(Y){return Y.variable?Y.variable.value:Y.value||Y.expression.value}function kr(Y){if(!Y)return[];if(Y.type==="aggregate")return[Y];if(Y.type==="operation"){const Q=[];for(const ne of Y.args)Q.push(...kr(ne));return Q}return[]}function kn(Y){const Q=new Set,ne=function(fe){fe&&(fe.termType==="Variable"?Q.add(fe):fe.type==="operation"&&fe.args.forEach(ne))};return ne(Y),Q}function Or(Y,Q=1,ne=[]){for(const fe of Y)Q>0&&fe instanceof Array?Or(fe,Q-1,ne):ne.push(fe);return ne}function Br(Y){return Y.termType==="Variable"}function Rn(Y){if(Y.triples){const Q=[];for(const ne of Y.triples)Br(ne.subject)&&Q.push(ne.subject.value),Br(ne.predicate)&&Q.push(ne.predicate.value),Br(ne.object)&&Q.push(ne.object.value);return Q}else if(Y.patterns){const Q=[];for(const ne of Y.patterns)Q.push(...Rn(ne));return Q}return[]}function On(Y){const Q=Y.slice().sort(),ne=[];for(let fe=0;fe<Q.length-1;fe++)Q[fe+1]==Q[fe]&&ne.push(Q[fe]);return ne}function rr(Y){if(!De.sparqlStar)throw new Error("SPARQL-star support is not enabled");return Y}function En(Y,Q,ne){for(const fe of Q){const Ce=mt("subject"in fe?fe.subject:Y,fe.predicate,fe.object);ne.push(Ce),fe.annotations&&En(Lr(Y,fe.predicate,fe.object),fe.annotations,ne)}}function zr(Y){if(De.sparqlStar){const Q=[];return Y.forEach(ne=>{const fe=mt(ne.subject,ne.predicate,ne.object);Q.push(fe),ne.annotations&&En(Lr(ne.subject,ne.predicate,ne.object),ne.annotations,Q)}),Q}return Y}function In(Y){for(const Q of Y){if(Q.type==="graph"&&Q.name.termType==="Variable")throw new Error("Detected illegal variable in GRAPH");if(Q.type==="bgp"||Q.type==="graph"){for(const ne of Q.triples)if(ne.subject.termType==="Variable"||ne.predicate.termType==="Variable"||ne.object.termType==="Variable")throw new Error("Detected illegal variable in BGP")}}return Y}function qr(Y){for(const Q of Y)if(Q.type==="bgp"){for(const ne of Q.triples)if(ne.subject.termType==="BlankNode"||ne.predicate.termType==="BlankNode"||ne.object.termType==="BlankNode")throw new Error("Detected illegal blank node in BGP")}return Y}var Bn=(function(){var Y={EOF:1,parseError:function(ne,fe){if(this.yy.parser)this.yy.parser.parseError(ne,fe);else throw new Error(ne)},setInput:function(Q,ne){return this.yy=ne||this.yy||{},this._input=Q,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var Q=this._input[0];this.yytext+=Q,this.yyleng++,this.offset++,this.match+=Q,this.matched+=Q;var ne=Q.match(/(?:\r\n?|\n).*/g);return ne?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),Q},unput:function(Q){var ne=Q.length,fe=Q.split(/(?:\r\n?|\n)/g);this._input=Q+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-ne),this.offset-=ne;var Ce=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),fe.length-1&&(this.yylineno-=fe.length-1);var Ae=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:fe?(fe.length===Ce.length?this.yylloc.first_column:0)+Ce[Ce.length-fe.length].length-fe[0].length:this.yylloc.first_column-ne},this.options.ranges&&(this.yylloc.range=[Ae[0],Ae[0]+this.yyleng-ne]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).
46
+ `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},less:function(Q){this.unput(this.match.slice(Q))},pastInput:function(){var Q=this.matched.substr(0,this.matched.length-this.match.length);return(Q.length>20?"...":"")+Q.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var Q=this.match;return Q.length<20&&(Q+=this._input.substr(0,20-Q.length)),(Q.substr(0,20)+(Q.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var Q=this.pastInput(),ne=new Array(Q.length+1).join("-");return Q+this.upcomingInput()+`
47
+ `+ne+"^"},test_match:function(Q,ne){var fe,Ce,Ae;if(this.options.backtrack_lexer&&(Ae={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(Ae.yylloc.range=this.yylloc.range.slice(0))),Ce=Q[0].match(/(?:\r\n?|\n).*/g),Ce&&(this.yylineno+=Ce.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:Ce?Ce[Ce.length-1].length-Ce[Ce.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+Q[0].length},this.yytext+=Q[0],this.match+=Q[0],this.matches=Q,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(Q[0].length),this.matched+=Q[0],fe=this.performAction.call(this,this.yy,this,ne,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),fe)return fe;if(this._backtrack){for(var T in Ae)this[T]=Ae[T];return!1}return!1},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var Q,ne,fe,Ce;this._more||(this.yytext="",this.match="");for(var Ae=this._currentRules(),T=0;T<Ae.length;T++)if(fe=this._input.match(this.rules[Ae[T]]),fe&&(!ne||fe[0].length>ne[0].length)){if(ne=fe,Ce=T,this.options.backtrack_lexer){if(Q=this.test_match(fe,Ae[T]),Q!==!1)return Q;if(this._backtrack){ne=!1;continue}else return!1}else if(!this.options.flex)break}return ne?(Q=this.test_match(ne,Ae[Ce]),Q!==!1?Q:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text.
48
+ `+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var ne=this.next();return ne||this.lex()},begin:function(ne){this.conditionStack.push(ne)},popState:function(){var ne=this.conditionStack.length-1;return ne>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(ne){return ne=this.conditionStack.length-1-Math.abs(ne||0),ne>=0?this.conditionStack[ne]:"INITIAL"},pushState:function(ne){this.begin(ne)},stateStackSize:function(){return this.conditionStack.length},options:{flex:!0,"case-insensitive":!0},performAction:function(ne,fe,Ce,Ae){switch(Ce){case 0:break;case 1:return 12;case 2:return 15;case 3:return 41;case 4:return 325;case 5:return 326;case 6:return 45;case 7:return 47;case 8:return 48;case 9:return 39;case 10:return 24;case 11:return 28;case 12:return 29;case 13:return 31;case 14:return 32;case 15:return 36;case 16:return 53;case 17:return 327;case 18:return 63;case 19:return 64;case 20:return 70;case 21:return 73;case 22:return 76;case 23:return 78;case 24:return 81;case 25:return 83;case 26:return 85;case 27:return 193;case 28:return 100;case 29:return 328;case 30:return 121;case 31:return 329;case 32:return 330;case 33:return 110;case 34:return 331;case 35:return 109;case 36:return 332;case 37:return 333;case 38:return 113;case 39:return 115;case 40:return 116;case 41:return 131;case 42:return 123;case 43:return 126;case 44:return 128;case 45:return 132;case 46:return 112;case 47:return 334;case 48:return 335;case 49:return 159;case 50:return 161;case 51:return 164;case 52:return 174;case 53:return 160;case 54:return 336;case 55:return 163;case 56:return 312;case 57:return 314;case 58:return 317;case 59:return 318;case 60:return 272;case 61:return 197;case 62:return 337;case 63:return 338;case 64:return 229;case 65:return 340;case 66:return 263;case 67:return 224;case 68:return 231;case 69:return 232;case 70:return 242;case 71:return 246;case 72:return 290;case 73:return 341;case 74:return 342;case 75:return 343;case 76:return 344;case 77:return 345;case 78:return 250;case 79:return 346;case 80:return 265;case 81:return 276;case 82:return 277;case 83:return 268;case 84:return 269;case 85:return 270;case 86:return 271;case 87:return 347;case 88:return 348;case 89:return 273;case 90:return 274;case 91:return 350;case 92:return 349;case 93:return 351;case 94:return 279;case 95:return 280;case 96:return 283;case 97:return 285;case 98:return 289;case 99:return 293;case 100:return 296;case 101:return 13;case 102:return 16;case 103:return 308;case 104:return 309;case 105:return 87;case 106:return 292;case 107:return 82;case 108:return 294;case 109:return 295;case 110:return 297;case 111:return 298;case 112:return 299;case 113:return 300;case 114:return 301;case 115:return 302;case 116:return"EXPONENT";case 117:return 303;case 118:return 304;case 119:return 305;case 120:return 306;case 121:return 89;case 122:return 310;case 123:return 6;case 124:return"INVALID";case 125:console.log(fe.yytext);break}},rules:[/^(?:\s+|(#[^\n\r]*))/i,/^(?:BASE)/i,/^(?:PREFIX)/i,/^(?:SELECT)/i,/^(?:DISTINCT)/i,/^(?:REDUCED)/i,/^(?:\()/i,/^(?:AS)/i,/^(?:\))/i,/^(?:\*)/i,/^(?:CONSTRUCT)/i,/^(?:WHERE)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:DESCRIBE)/i,/^(?:ASK)/i,/^(?:FROM)/i,/^(?:NAMED)/i,/^(?:GROUP)/i,/^(?:BY)/i,/^(?:HAVING)/i,/^(?:ORDER)/i,/^(?:ASC)/i,/^(?:DESC)/i,/^(?:LIMIT)/i,/^(?:OFFSET)/i,/^(?:VALUES)/i,/^(?:;)/i,/^(?:LOAD)/i,/^(?:SILENT)/i,/^(?:INTO)/i,/^(?:CLEAR)/i,/^(?:DROP)/i,/^(?:CREATE)/i,/^(?:ADD)/i,/^(?:TO)/i,/^(?:MOVE)/i,/^(?:COPY)/i,/^(?:INSERT((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)WHERE)/i,/^(?:WITH)/i,/^(?:DELETE)/i,/^(?:INSERT)/i,/^(?:USING)/i,/^(?:DEFAULT)/i,/^(?:GRAPH)/i,/^(?:ALL)/i,/^(?:\.)/i,/^(?:OPTIONAL)/i,/^(?:SERVICE)/i,/^(?:BIND)/i,/^(?:UNDEF)/i,/^(?:MINUS)/i,/^(?:UNION)/i,/^(?:FILTER)/i,/^(?:<<)/i,/^(?:>>)/i,/^(?:\{\|)/i,/^(?:\|\})/i,/^(?:,)/i,/^(?:a)/i,/^(?:\|)/i,/^(?:\/)/i,/^(?:\^)/i,/^(?:\?)/i,/^(?:\+)/i,/^(?:!)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:\|\|)/i,/^(?:&&)/i,/^(?:=)/i,/^(?:!=)/i,/^(?:<)/i,/^(?:>)/i,/^(?:<=)/i,/^(?:>=)/i,/^(?:IN)/i,/^(?:NOT)/i,/^(?:-)/i,/^(?:BOUND)/i,/^(?:BNODE)/i,/^(?:(RAND|NOW|UUID|STRUUID))/i,/^(?:(LANG|DATATYPE|IRI|URI|ABS|CEIL|FLOOR|ROUND|STRLEN|STR|UCASE|LCASE|ENCODE_FOR_URI|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|MD5|SHA1|SHA256|SHA384|SHA512|isIRI|isURI|isBLANK|isLITERAL|isNUMERIC))/i,/^(?:(SUBJECT|PREDICATE|OBJECT|isTRIPLE))/i,/^(?:(LANGMATCHES|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|STRLANG|STRDT|sameTerm))/i,/^(?:CONCAT)/i,/^(?:COALESCE)/i,/^(?:IF)/i,/^(?:TRIPLE)/i,/^(?:REGEX)/i,/^(?:SUBSTR)/i,/^(?:REPLACE)/i,/^(?:EXISTS)/i,/^(?:COUNT)/i,/^(?:SUM|MIN|MAX|AVG|SAMPLE)/i,/^(?:GROUP_CONCAT)/i,/^(?:SEPARATOR)/i,/^(?:\^\^)/i,/^(?:true|false)/i,/^(?:(<(?:[^<>\"\{\}\|\^`\\\u0000-\u0020])*>))/i,/^(?:((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:))/i,/^(?:(((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:)((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|:|[0-9]|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))*(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%)))))?)))/i,/^(?:(_:(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?))/i,/^(?:([\?\$]((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])*)))/i,/^(?:(@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*))/i,/^(?:([0-9]+))/i,/^(?:([0-9]*\.[0-9]+))/i,/^(?:([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+)))/i,/^(?:(\+([0-9]+)))/i,/^(?:(\+([0-9]*\.[0-9]+)))/i,/^(?:(\+([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:(-([0-9]+)))/i,/^(?:(-([0-9]*\.[0-9]+)))/i,/^(?:(-([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:([eE][+-]?[0-9]+))/i,/^(?:('(?:(?:[^\u0027\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*'))/i,/^(?:("(?:(?:[^\u0022\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*"))/i,/^(?:('''(?:(?:'|'')?(?:[^'\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*'''))/i,/^(?:("""(?:(?:"|"")?(?:[^\"\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*"""))/i,/^(?:(\((\u0020|\u0009|\u000D|\u000A)*\)))/i,/^(?:(\[(\u0020|\u0009|\u000D|\u000A)*\]))/i,/^(?:$)/i,/^(?:.)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125],inclusive:!0}}};return Y})();Pr.lexer=Bn;function De(){this.yy={}}return De.prototype=Pr,Pr.Parser=De,new De})();return SparqlParser_1=n,SparqlParser_1}var SparqlGenerator,hasRequiredSparqlGenerator;function requireSparqlGenerator(){if(hasRequiredSparqlGenerator)return SparqlGenerator;hasRequiredSparqlGenerator=1;var n="http://www.w3.org/2001/XMLSchema#integer",e="http://www.w3.org/2001/XMLSchema#string";function t(u){this._options=u=u||{};var p=u.prefixes||{};this._prefixByIri={};var g=[];for(var y in p){var w=p[y];a(w)&&(this._prefixByIri[w]=y,g.push(w))}var _=g.join("|").replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&");this._prefixRegex=new RegExp("^("+_+")([a-zA-Z][\\-_a-zA-Z0-9]*)$"),this._usedPrefixes={},this._sparqlStar=u.sparqlStar,this._indent=a(u.indent)?u.indent:" ",this._newline=a(u.newline)?u.newline:`
49
+ `,this._explicitDatatype=!!u.explicitDatatype}t.prototype.toQuery=function(u){var p="";return u.queryType&&(p+=u.queryType.toUpperCase()+" "),u.reduced&&(p+="REDUCED "),u.distinct&&(p+="DISTINCT "),u.variables?p+=d(u.variables,void 0,function(g){return/^[?$]/.test(g)?g:c(g)?this.toEntity(g):"("+this.toExpression(g.expression)+" AS "+o(g.variable)+")"},this)+" ":u.template&&(p+=this.group(u.template,!0)+this._newline),u.from&&(p+=this.graphs("FROM ",u.from.default)+this.graphs("FROM NAMED ",u.from.named)),u.where&&(p+="WHERE "+this.group(u.where,!0)+this._newline),u.updates&&(p+=d(u.updates,";"+this._newline,this.toUpdate,this)),u.group&&(p+="GROUP BY "+d(u.group,void 0,function(g){var y=c(g.expression)?this.toEntity(g.expression):"("+this.toExpression(g.expression)+")";return g.variable?"("+y+" AS "+o(g.variable)+")":y},this)+this._newline),u.having&&(p+="HAVING ("+d(u.having,void 0,this.toExpression,this)+")"+this._newline),u.order&&(p+="ORDER BY "+d(u.order,void 0,function(g){var y="("+this.toExpression(g.expression)+")";return g.descending?"DESC "+y:y},this)+this._newline),Number.isInteger(u.offset)&&(p+="OFFSET "+u.offset+this._newline),Number.isInteger(u.limit)&&(p+="LIMIT "+u.limit+this._newline),u.values&&(p+=this.values(u)),p=this.baseAndPrefixes(u)+p,p.trim()},t.prototype.baseAndPrefixes=function(u){var p=u.base?"BASE <"+u.base+">"+this._newline:"",g="";for(var y in u.prefixes)(this._options.allPrefixes||this._usedPrefixes[y])&&(g+="PREFIX "+y+": <"+u.prefixes[y]+">"+this._newline);return p+g},t.prototype.toPattern=function(u){var p=u.type||u instanceof Array&&"array"||(u.subject&&u.predicate&&u.object?"triple":"");if(!(p in this))throw new Error("Unknown entry type: "+p);return this[p](u)},t.prototype.triple=function(u){return this.toEntity(u.subject)+" "+this.toEntity(u.predicate)+" "+this.toEntity(u.object)+"."},t.prototype.array=function(u){return d(u,this._newline,this.toPattern,this)},t.prototype.bgp=function(u){return this.encodeTriples(u.triples)},t.prototype.encodeTriples=function(u){if(!u.length)return"";for(var p=[],g=void 0,y=void 0,w=0;w<u.length;w++){var _=u[w];l(_.subject,g)?l(_.predicate,y)?p.push(","):(y=_.predicate,p.push(";"+this._newline,this._indent,this.toEntity(y))):(g&&p.push("."+this._newline),g=_.subject,y=_.predicate,p.push(this.toEntity(g)," ",this.toEntity(y))),p.push(" ",this.toEntity(_.object))}return p.push("."),p.join("")},t.prototype.graph=function(u){return"GRAPH "+this.toEntity(u.name)+" "+this.group(u)},t.prototype.graphs=function(u,p){return!p||p.length===0?"":d(p,"",function(g){return u+this.toEntity(g)+this._newline},this)},t.prototype.group=function(u,p){return u=p!==!0?this.array(u.patterns||u.triples):this.toPattern(u.type!=="group"?u:u.patterns),u.indexOf(this._newline)===-1?"{ "+u+" }":"{"+this._newline+this.indent(u)+this._newline+"}"},t.prototype.query=function(u){return this.toQuery(u)},t.prototype.filter=function(u){return"FILTER("+this.toExpression(u.expression)+")"},t.prototype.bind=function(u){return"BIND("+this.toExpression(u.expression)+" AS "+o(u.variable)+")"},t.prototype.optional=function(u){return"OPTIONAL "+this.group(u)},t.prototype.union=function(u){return d(u.patterns,this._newline+"UNION"+this._newline,function(p){return this.group(p,!0)},this)},t.prototype.minus=function(u){return"MINUS "+this.group(u)},t.prototype.values=function(u){var p=Object.keys(u.values.reduce(function(w,_){for(var R in _)w[R]=!0;return w},{})),g,y;return p.length===1?g=y="":(g="(",y=")"),"VALUES "+g+p.join(" ")+y+" {"+this._newline+d(u.values,this._newline,function(w){return" "+g+d(p,void 0,function(_){return w[_]?this.toEntity(w[_]):"UNDEF"},this)+y},this)+this._newline+"}"},t.prototype.service=function(u){return"SERVICE "+(u.silent?"SILENT ":"")+this.toEntity(u.name)+" "+this.group(u)},t.prototype.toExpression=function(u){if(c(u))return this.toEntity(u);switch(u.type.toLowerCase()){case"aggregate":return u.aggregation.toUpperCase()+"("+(u.distinct?"DISTINCT ":"")+this.toExpression(u.expression)+(typeof u.separator=="string"?'; SEPARATOR = "'+u.separator.replace(r,i)+'"':"")+")";case"functioncall":return this.toEntity(u.function)+"("+d(u.args,", ",this.toExpression,this)+")";case"operation":var p=u.operator.toUpperCase(),g=u.args||[];switch(u.operator.toLowerCase()){case"<":case">":case">=":case"<=":case"&&":case"||":case"=":case"!=":case"+":case"-":case"*":case"/":return(c(g[0])?this.toEntity(g[0]):"("+this.toExpression(g[0])+")")+" "+p+" "+(c(g[1])?this.toEntity(g[1]):"("+this.toExpression(g[1])+")");case"!":return"!("+this.toExpression(g[0])+")";case"uplus":return"+("+this.toExpression(g[0])+")";case"uminus":return"-("+this.toExpression(g[0])+")";case"notin":p="NOT IN";case"in":return this.toExpression(g[0])+" "+p+"("+(a(g[1])?g[1]:d(g[1],", ",this.toExpression,this))+")";case"notexists":p="NOT EXISTS";case"exists":return p+" "+this.group(g[0],!0);default:return p+"("+d(g,", ",this.toExpression,this)+")"}default:throw new Error("Unknown expression type: "+u.type)}},t.prototype.toEntity=function(u){if(c(u))switch(u.termType){case"Wildcard":return"*";case"Variable":return o(u);case"BlankNode":return"_:"+u.value;case"Literal":var p=u.value||"",g=u.language||"",y=u.datatype;if(u='"'+p.replace(r,i)+'"',g)u+="@"+g;else if(y){if(!this._explicitDatatype)switch(y.value){case e:return u;case n:if(/^\d+$/.test(p))return p+" "}u+="^^"+this.encodeIRI(y.value)}return u;case"Quad":if(!this._sparqlStar)throw new Error("SPARQL* support is not enabled");return u.graph&&u.graph.termType!=="DefaultGraph"?"<< GRAPH "+this.toEntity(u.graph)+" { "+this.toEntity(u.subject)+" "+this.toEntity(u.predicate)+" "+this.toEntity(u.object)+" } >>":"<< "+this.toEntity(u.subject)+" "+this.toEntity(u.predicate)+" "+this.toEntity(u.object)+" >>";default:return this.encodeIRI(u.value)}else{var w=u.items.map(this.toEntity,this),_=u.pathType;switch(_){case"^":case"!":return _+w[0];case"*":case"+":case"?":return"("+w[0]+_+")";default:return"("+w.join(_)+")"}}};var r=/["\\\t\n\r\b\f]/g,i=function(u){return s[u]},s={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};t.prototype.encodeIRI=function(u){var p=this._prefixRegex.exec(u);if(p){var g=this._prefixByIri[p[1]];return this._usedPrefixes[g]=!0,g+":"+p[2]}return"<"+u+">"},t.prototype.toUpdate=function(u){switch(u.type||u.updateType){case"load":return"LOAD"+(u.source?" "+this.toEntity(u.source):"")+(u.destination?" INTO GRAPH "+this.toEntity(u.destination):"");case"insert":return"INSERT DATA "+this.group(u.insert,!0);case"delete":return"DELETE DATA "+this.group(u.delete,!0);case"deletewhere":return"DELETE WHERE "+this.group(u.delete,!0);case"insertdelete":return(u.graph?"WITH "+this.toEntity(u.graph)+this._newline:"")+(u.delete.length?"DELETE "+this.group(u.delete,!0)+this._newline:"")+(u.insert.length?"INSERT "+this.group(u.insert,!0)+this._newline:"")+(u.using?this.graphs("USING ",u.using.default):"")+(u.using?this.graphs("USING NAMED ",u.using.named):"")+"WHERE "+this.group(u.where,!0);case"add":case"copy":case"move":return u.type.toUpperCase()+" "+(u.silent?"SILENT ":"")+(u.source.default?"DEFAULT":this.toEntity(u.source.name))+" TO "+this.toEntity(u.destination.name);case"create":case"clear":case"drop":return u.type.toUpperCase()+(u.silent?" SILENT ":" ")+(u.graph.default?"DEFAULT":u.graph.named?"NAMED":u.graph.all?"ALL":"GRAPH "+this.toEntity(u.graph.name));default:throw new Error("Unknown update query type: "+u.type)}},t.prototype.indent=function(u){return u.replace(/^/gm,this._indent)};function o(u){return"?"+u.value}function a(u){return typeof u=="string"}function c(u){return typeof u.termType=="string"}function l(u,p){if(!u||!c(u)||!p||!c(p)||u.termType!==p.termType)return!1;switch(u.termType){case"Literal":return u.value===p.value&&u.language===p.language&&l(u.datatype,p.datatype);case"Quad":return l(u.subject,p.subject)&&l(u.predicate,p.predicate)&&l(u.object,p.object)&&l(u.graph,p.graph);default:return u.value===p.value}}function d(u,p,g,y){return u.map(g,y).join(a(p)?p:" ")}function f(u={}){return{stringify:function(p){var g=Object.create(u);return g.prefixes=p.prefixes,new t(g).toQuery(p)},createGenerator:function(){return new t(u)}}}return SparqlGenerator={Generator:f},SparqlGenerator}var rdfDataFactory={},BlankNode={},hasRequiredBlankNode;function requireBlankNode(){if(hasRequiredBlankNode)return BlankNode;hasRequiredBlankNode=1,Object.defineProperty(BlankNode,"__esModule",{value:!0}),BlankNode.BlankNode=void 0;let n=class{constructor(t){this.termType="BlankNode",this.value=t}equals(t){return!!t&&t.termType==="BlankNode"&&t.value===this.value}};return BlankNode.BlankNode=n,BlankNode}var DataFactory={},DefaultGraph={},hasRequiredDefaultGraph;function requireDefaultGraph(){if(hasRequiredDefaultGraph)return DefaultGraph;hasRequiredDefaultGraph=1,Object.defineProperty(DefaultGraph,"__esModule",{value:!0}),DefaultGraph.DefaultGraph=void 0;let n=class{constructor(){this.termType="DefaultGraph",this.value=""}equals(t){return!!t&&t.termType==="DefaultGraph"}};return DefaultGraph.DefaultGraph=n,n.INSTANCE=new n,DefaultGraph}var Literal={},NamedNode={},hasRequiredNamedNode;function requireNamedNode(){if(hasRequiredNamedNode)return NamedNode;hasRequiredNamedNode=1,Object.defineProperty(NamedNode,"__esModule",{value:!0}),NamedNode.NamedNode=void 0;let n=class{constructor(t){this.termType="NamedNode",this.value=t}equals(t){return!!t&&t.termType==="NamedNode"&&t.value===this.value}};return NamedNode.NamedNode=n,NamedNode}var hasRequiredLiteral;function requireLiteral(){if(hasRequiredLiteral)return Literal;hasRequiredLiteral=1,Object.defineProperty(Literal,"__esModule",{value:!0}),Literal.Literal=void 0;const n=requireNamedNode();let e=class Wr{constructor(r,i){this.termType="Literal",this.value=r,typeof i=="string"?(this.language=i,this.datatype=Wr.RDF_LANGUAGE_STRING):i?(this.language="",this.datatype=i):(this.language="",this.datatype=Wr.XSD_STRING)}equals(r){return!!r&&r.termType==="Literal"&&r.value===this.value&&r.language===this.language&&this.datatype.equals(r.datatype)}};return Literal.Literal=e,e.RDF_LANGUAGE_STRING=new n.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),e.XSD_STRING=new n.NamedNode("http://www.w3.org/2001/XMLSchema#string"),Literal}var Quad={},hasRequiredQuad;function requireQuad(){if(hasRequiredQuad)return Quad;hasRequiredQuad=1,Object.defineProperty(Quad,"__esModule",{value:!0}),Quad.Quad=void 0;let n=class{constructor(t,r,i,s){this.termType="Quad",this.value="",this.subject=t,this.predicate=r,this.object=i,this.graph=s}equals(t){return!!t&&(t.termType==="Quad"||!t.termType)&&this.subject.equals(t.subject)&&this.predicate.equals(t.predicate)&&this.object.equals(t.object)&&this.graph.equals(t.graph)}};return Quad.Quad=n,Quad}var Variable={},hasRequiredVariable;function requireVariable(){if(hasRequiredVariable)return Variable;hasRequiredVariable=1,Object.defineProperty(Variable,"__esModule",{value:!0}),Variable.Variable=void 0;let n=class{constructor(t){this.termType="Variable",this.value=t}equals(t){return!!t&&t.termType==="Variable"&&t.value===this.value}};return Variable.Variable=n,Variable}var hasRequiredDataFactory;function requireDataFactory(){if(hasRequiredDataFactory)return DataFactory;hasRequiredDataFactory=1,Object.defineProperty(DataFactory,"__esModule",{value:!0}),DataFactory.DataFactory=void 0;const n=requireBlankNode(),e=requireDefaultGraph(),t=requireLiteral(),r=requireNamedNode(),i=requireQuad(),s=requireVariable();let o=0,a=class{constructor(l){this.blankNodeCounter=0,l=l||{},this.blankNodePrefix=l.blankNodePrefix||`df_${o++}_`}namedNode(l){return new r.NamedNode(l)}blankNode(l){return new n.BlankNode(l||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(l,d){return new t.Literal(l,d)}variable(l){return new s.Variable(l)}defaultGraph(){return e.DefaultGraph.INSTANCE}quad(l,d,f,u){return new i.Quad(l,d,f,u||this.defaultGraph())}fromTerm(l){switch(l.termType){case"NamedNode":return this.namedNode(l.value);case"BlankNode":return this.blankNode(l.value);case"Literal":return l.language?this.literal(l.value,l.language):l.datatype.equals(t.Literal.XSD_STRING)?this.literal(l.value):this.literal(l.value,this.fromTerm(l.datatype));case"Variable":return this.variable(l.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(l.subject),this.fromTerm(l.predicate),this.fromTerm(l.object),this.fromTerm(l.graph))}}fromQuad(l){return this.fromTerm(l)}resetBlankNodeCounter(){this.blankNodeCounter=0}};return DataFactory.DataFactory=a,DataFactory}var hasRequiredRdfDataFactory;function requireRdfDataFactory(){return hasRequiredRdfDataFactory||(hasRequiredRdfDataFactory=1,(function(n){var e=rdfDataFactory&&rdfDataFactory.__createBinding||(Object.create?(function(r,i,s,o){o===void 0&&(o=s);var a=Object.getOwnPropertyDescriptor(i,s);(!a||("get"in a?!i.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,a)}):(function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]})),t=rdfDataFactory&&rdfDataFactory.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(n,"__esModule",{value:!0}),t(requireBlankNode(),n),t(requireDataFactory(),n),t(requireDefaultGraph(),n),t(requireLiteral(),n),t(requireNamedNode(),n),t(requireQuad(),n),t(requireVariable(),n)})(rdfDataFactory)),rdfDataFactory}var sparql,hasRequiredSparql;function requireSparql(){if(hasRequiredSparql)return sparql;hasRequiredSparql=1;const{Parser:n}=requireSparqlParser(),{Generator:e}=requireSparqlGenerator(),{Wildcard:t}=requireWildcard(),{DataFactory:r}=requireRdfDataFactory();function i({prefixes:s,baseIRI:o,factory:a,pathOnly:c,sparqlStar:l,skipValidation:d,skipUngroupedVariableCheck:f}={}){const u={};for(const g in s??{})u[g]=s[g];const p=new n;return p.parse=function(){return n.base=o||"",n.prefixes=Object.create(u),n.factory=a||new r,n.sparqlStar=!!l,n.pathOnly=!!c,n.skipValidation=!!d||!!f,n.prototype.parse.apply(p,arguments)},p._resetBlanks=n._resetBlanks,p}return sparql={Parser:i,Generator:e,Wildcard:t},sparql}var sparqlExports=requireSparql();class ExpressionBuilder{constructor(e=new UriResolverImpl){this.uriResolver=e}setTableContext(e){this.tableContext=e}getUriContext(){if(this.tableContext)return{baseUri:this.tableContext.baseUri,tableRegistry:this.tableContext.tableRegistry,tableNameRegistry:this.tableContext.tableNameRegistry}}buildWhereClause(e,t){const r=this.buildExpression(e,t);return r?`FILTER(${r})`:""}extractSubjectConstraint(e,t){const r=this.extractSubjectConstraintInternal(e,t);return r?.values?.length?r:null}isLinkColumn(e){return this.uriResolver.isLinkColumn(e)}formatLinkValue(e,t,r){const i=String(e);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);if(this.uriResolver.isAbsoluteUri(s))return i;const o=this.getUriContext();try{return`<${this.uriResolver.resolveLink(s,t,o)}>`}catch(a){const c=r.config?.name??"unknown",l=t?.name??"unknown";if(this.isPartialTemplateError(a))return{partial:!0,id:s};throw new Error(`[ExpressionBuilder] Failed to resolve URI for ${c}.${l}: ${a}`)}}if(i.startsWith("<"))return i;try{const s=this.getUriContext();return`<${this.uriResolver.resolveLink(i,t,s)}>`}catch(s){const o=r.config?.name??"unknown",a=t?.name??"unknown";if(this.isPartialTemplateError(s))return{partial:!0,id:i};throw new Error(`[ExpressionBuilder] Failed to resolve URI for ${o}.${a}: ${s}`)}}isPartialTemplateError(e){const t=String(e);return t.includes("Missing required fields for template")||t.includes("Unresolved URI template variable")}isPartialLinkValue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.partial===!0&&typeof e.id=="string"}formatPartialLinkCondition(e,t,r){if(!this.isPartialLinkValue(t))return;const i=t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(r==="=")return`STRENDS(STR(${e}), "#${i}")`;if(r==="!=")return`!STRENDS(STR(${e}), "#${i}")`}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{field:t||e,transforms:r}}getTemplateVariableFields(e){const t=e.config?.subjectTemplate??"";return t?Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(r=>this.parseTemplateVariable(r[1]).field))):[]}getMissingLocatorVariables(e){const t=new Set(["id","index","yyyy","MM","dd","HH","mm","ss","timestamp","date"]);return this.getTemplateVariableFields(e).filter(r=>!t.has(r))}buildMissingLocatorError(e){const t=e.config?.subjectTemplate??"",r=this.getMissingLocatorVariables(e);return new Error(`Cannot resolve subjectTemplate '${t}': missing required variable(s) [${r.join(", ")}] in query condition. Add eq(table.${r[0]}, value) to your where clause.`)}formatSubjectValue(e,t,r){const i=String(e??"");if(i.startsWith("<")&&i.endsWith(">")){const o=i.slice(1,-1);if(this.uriResolver.isAbsoluteUri(o))return i;const a=o.startsWith("#")?o.slice(1):o;try{return`<${this.uriResolver.resolveSubject(t,{id:a})}>`}catch(c){throw this.getMissingLocatorVariables(t).length>0?this.buildMissingLocatorError(t):c}}if(this.uriResolver.isAbsoluteUri(i))return`<${i}>`;const s=i.startsWith("#")?i.slice(1):i;try{return`<${this.uriResolver.resolveSubject(t,{id:s})}>`}catch(o){throw this.getMissingLocatorVariables(t).length>0?this.buildMissingLocatorError(t):o}}isDrizzleSQL(e){return!e||typeof e!="object"?!1:e.constructor?.[Symbol.for("drizzle:entityKind")]==="SQL"||Array.isArray(e.queryChunks)&&typeof e.getSQL=="function"}buildExpression(e,t){if(!e||typeof e!="object")return"";if(this.isDrizzleSQL(e))throw new Error("Drizzle-ORM operators are not supported. Please use the operators provided by drizzle-solid.");switch(e.type){case"logical_expr":return this.buildLogicalExpression(e,t);case"unary_expr":return this.buildUnaryExpression(e,t);case"binary_expr":return this.buildBinaryExpression(e,t);default:return""}}buildLogicalExpression(e,t){if(!e.expressions||e.expressions.length===0)return"";const r=e.expressions.map(s=>this.buildExpression(s,t)).filter(s=>s.length>0);if(r.length===0)return"";const i=e.operator==="OR"?" || ":" && ";return`(${r.join(i)})`}extractSubjectConstraintInternal(e,t){if(!e||typeof e!="object"||this.isDrizzleSQL(e))return null;if(e.type==="binary_expr")return this.extractSubjectConstraintFromBinary(e,t);if(e.type==="logical_expr"&&e.operator==="AND"&&Array.isArray(e.expressions)){const r=this.extractExactSubjectConstraintFromLogical(e,t);if(r)return r;let i=null;const s=[];for(const o of e.expressions){const a=this.extractSubjectConstraintInternal(o,t);if(a?.values?.length){i=i===null?[...a.values]:i.filter(c=>new Set(a.values).has(c)),a.remainingCondition&&s.push(a.remainingCondition);continue}s.push(o)}return i?.length?s.length===0?{values:i}:s.length===1?{values:i,remainingCondition:s[0]}:{values:i,remainingCondition:new LogicalExpression("AND",s)}:null}return null}extractSubjectConstraintFromBinary(e,t){if(e.operator!=="IN"||!Array.isArray(e.right)||e.right.length<=1)return null;const r=this.resolveColumnName(e.left);if(!r)return null;const i=t.columns[r],s=r==="id",o=s&&i?getPredicateForColumn(i,t):null,a=s&&o==="@id";if(!(r==="subject"||r==="@id"||a))return null;const l=[];for(const d of e.right){const f=this.formatSubjectValue(d,t,a);if(typeof f!="string"||!f.startsWith("<")||!f.endsWith(">"))return null;l.push(f.slice(1,-1))}return l.length>1?{values:l}:null}extractExactSubjectConstraintFromLogical(e,t){if(!(t.config?.subjectTemplate??"").includes("{"))return null;const i=new Set(["index","yyyy","MM","dd","HH","mm","ss","timestamp","date"]),s=this.getTemplateVariableFields(t).filter(d=>!i.has(d));if(s.length===0)return null;const o=new Map,a=[];for(const d of e.expressions){const f=d;if(f.type!=="binary_expr"||f.operator!=="="){a.push(d);continue}const u=this.resolveColumnName(f.left);if(!u||!s.includes(u)&&u!=="id"&&u!=="@id"&&u!=="subject"){a.push(d);continue}o.set(u,f.right)}if(!o.has("id")&&!o.has("@id")&&!o.has("subject"))return null;const c={};for(const d of s){if(!o.has(d))return null;c[d]=o.get(d)}o.has("@id")?c["@id"]=o.get("@id"):o.has("subject")?c["@id"]=o.get("subject"):c.id=o.get("id");const l=this.uriResolver.resolveSubject(t,c);return a.length===0?{values:[l]}:a.length===1?{values:[l],remainingCondition:a[0]}:{values:[l],remainingCondition:new LogicalExpression("AND",a)}}buildUnaryExpression(e,t){const r=e.operator;if(r==="NOT")return`!(${this.buildExpression(e.value,t)})`;const i=this.resolveColumnName(e.value);if(!i)return"";const s=t.columns[i],o=i==="id",a=o&&s?getPredicateForColumn(s,t):null,d=i==="subject"||i==="@id"||o&&a==="@id"?"?subject":`?${i}`;if(r==="IS NULL")return`!(BOUND(${d}))`;if(r==="IS NOT NULL")return`BOUND(${d})`;if(r==="EXISTS"||r==="NOT EXISTS"){const u=`EXISTS { ${String(e.value)} }`;return r==="NOT EXISTS"?`!(${u})`:u}return""}buildBinaryExpression(e,t){const r=this.resolveColumnName(e.left);if(!r)return"";const i=t.columns[r],s=r==="id",o=s&&i?getPredicateForColumn(i,t):null,a=s&&o==="@id",c=r==="subject"||r==="@id"||a,l=c?"?subject":`?${r}`,d=this.isLinkColumn(i);let f=e.right;if(e.operator==="IN"||e.operator==="NOT IN"){if(!Array.isArray(f)||f.length===0)return e.operator==="IN"?"false":"true";if(c){const _=f.map(b=>this.formatSubjectValue(b,t,a)).join(", "),R=`${l} IN(${_})`;return e.operator==="NOT IN"?`!(${R})`:R}const p=f.map(_=>d?this.formatLinkValue(_,i,t):formatValue(_,i,this.uriResolver,this.getUriContext()));if(p.some(_=>this.isPartialLinkValue(_))){const R=`(${p.map(b=>{if(this.isPartialLinkValue(b)){const P=b.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`STRENDS(STR(${l}), "#${P}")`}const C=Array.isArray(b)?b.join(", "):b;return`(${l} = ${C})`}).join(" || ")})`;return e.operator==="NOT IN"?`!(${R})`:R}const y=p.join(", "),w=`${l} IN(${y})`;return e.operator==="NOT IN"?`!(${w})`:w}if(e.operator==="REGEX"){const p=f.pattern??f,g=f.flags??"";return`REGEX(STR(${l}), "${p}", "${g}")`}if(e.operator==="LIKE"){let p=String(f).replace(/[.+^${}()|[\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return`REGEX(STR(${l}), "^${p}$", "i")`}if(e.operator==="ILIKE"){let p=String(f).replace(/[.+^${}()|[\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return`REGEX(STR(${l}), "^${p}$", "i")`}if(e.operator==="BETWEEN"||e.operator==="NOT BETWEEN"){if(!Array.isArray(f)||f.length!==2)return"";const[p,g]=f,y=formatValue(p,i,this.uriResolver,this.getUriContext()),w=formatValue(g,i,this.uriResolver,this.getUriContext()),_=`(${l} >= ${y} && ${l} <= ${w})`;return e.operator==="NOT BETWEEN"?`!${_}`:_}let u;if(c)u=this.formatSubjectValue(f,t,a);else if(d){const p=this.formatLinkValue(f,i,t),g=this.formatPartialLinkCondition(l,p,e.operator);if(g)return g;u=this.isPartialLinkValue(p)?`"${p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:p}else u=formatValue(f,i,this.uriResolver,this.getUriContext());return`(${l} ${e.operator} ${u})`}resolveColumnName(e){return typeof e=="string"?e.includes(".")?e.split(".")[1]:e:e&&typeof e=="object"&&"name"in e?e.name:e&&typeof e=="object"&&"column"in e?e.column:""}}class SelectBuilder{constructor(e,t=new UriResolverImpl){this.generator=new sparqlExports.Generator,this.prefixes=e,this.uriResolver=t,this.expressionBuilder=new ExpressionBuilder(t)}setTableContext(e){this.tableContext=e,this.expressionBuilder.setTableContext(e)}convertSelect(e,t,r,i,s=!0){const o={queryType:"SELECT",variables:this.buildSelectVariables(e,t),where:this.buildWherePatterns(e,t,r,i,s),type:"query",prefixes:this.prefixes};return i&&i.length>0&&!r&&(o.from={default:i.map(c=>({termType:"NamedNode",value:c})),named:[]}),typeof e.limit=="number"&&(o.limit=e.limit),typeof e.offset=="number"&&(o.offset=e.offset),Array.isArray(e.orderBy)&&e.orderBy.length>0&&(o.order=e.orderBy.map(c=>({expression:{termType:"Variable",value:c.column},descending:c.direction==="desc"}))),Array.isArray(e.groupBy)&&e.groupBy.length>0&&(o.group=e.groupBy.map(c=>({expression:{termType:"Variable",value:c}}))),Array.isArray(e.having)&&e.having.length>0&&(o.having=e.having),e.distinct&&(o.distinct=!0),{type:"SELECT",query:this.generator.stringify(o),prefixes:this.prefixes}}convertSelectPlan(e,t,r,i=!0){const s=e.orderBy?.map(c=>{const l=c.reference?.column??c.rawColumn;if(l)return{column:l,direction:c.direction}}).filter(c=>!!c),o=e.groupBy?.map(c=>c.column),a={select:e.select,columns:e.selectAll?"*":void 0,where:e.conditionTree??e.where,limit:e.limit,offset:e.offset,orderBy:s,groupBy:o,having:this.buildHavingExpressions(e),distinct:e.distinct};return this.convertSelect(a,e.baseTable,t,r,i)}buildHavingExpressions(e){if(!e.having)return;const t=this.buildHavingExpression(e.having,e.select,e.baseTable);if(!t)return;const r=Object.entries(this.prefixes).map(([d,f])=>`PREFIX ${d}: <${f}>`).join(`
50
+ `),i=e.groupBy?.map(d=>`?${d.column}`)??[],s=i.length>0?i.join(" "):"?subject",o=i.length>0?` GROUP BY ${i.join(" ")}`:"",a=`${r}
51
+ SELECT ${s} WHERE { ?subject ?predicate ?object . }${o} HAVING (${t})`;return new sparqlExports.Parser({skipUngroupedVariableCheck:!0}).parse(a).having}buildHavingExpression(e,t,r){switch(e.type){case"logical_expr":return this.buildHavingLogicalExpression(e,t,r);case"unary_expr":return this.buildHavingUnaryExpression(e,t,r);case"binary_expr":return this.buildHavingBinaryExpression(e,t,r);default:return""}}buildHavingLogicalExpression(e,t,r){const i=e.operator==="OR"?" || ":" && ",s=(e.expressions??[]).map(o=>this.buildHavingExpression(o,t,r)).filter(o=>o.length>0);return s.length===0?"":`(${s.join(i)})`}buildHavingUnaryExpression(e,t,r){const i=e.operator.toUpperCase();if(i==="NOT"){const o=this.buildHavingExpression(e.value,t,r);return o?`!(${o})`:""}if(i==="EXISTS"||i==="NOT EXISTS"){const o=`EXISTS { ${String(e.value)} }`;return i==="NOT EXISTS"?`!(${o})`:o}const s=this.buildHavingOperand(e.value,t,r);return s?i==="IS NULL"?`!(BOUND(${s}))`:i==="IS NOT NULL"?`BOUND(${s})`:"":""}buildHavingBinaryExpression(e,t,r){const i=this.buildHavingOperand(e.left,t,r);if(!i)return"";const s=e.operator.toUpperCase();if(s==="BETWEEN"||s==="NOT BETWEEN"){const a=Array.isArray(e.right)?e.right:[];if(a.length!==2)return"";const c=this.buildHavingOperand(a[0],t,r),l=this.buildHavingOperand(a[1],t,r),d=`(${i} >= ${c} && ${i} <= ${l})`;return s==="NOT BETWEEN"?`!${d}`:d}if(s==="IN"||s==="NOT IN"){const c=(Array.isArray(e.right)?e.right:[]).map(d=>this.buildHavingOperand(d,t,r)).join(", "),l=`${i} IN (${c})`;return s==="NOT IN"?`!(${l})`:l}const o=this.buildHavingOperand(e.right,t,r);return o?`${i} ${e.operator} ${o}`:""}buildHavingOperand(e,t,r){return e instanceof SelectionAliasExpression?this.buildHavingAliasOperand(e.alias,t,r):typeof e=="string"&&t&&e in t?this.buildHavingAliasOperand(e,t,r):e instanceof PodColumnBase?`?${resolveColumn(e,r).name}`:e&&typeof e=="object"&&"name"in e?`?${resolveColumn(e,r).name}`:typeof e=="string"&&r.columns[e]?`?${resolveColumn(e,r).name}`:String(formatValue(e,void 0,this.uriResolver,this.getUriContext()))}buildHavingAliasOperand(e,t,r){const i=t?.[e];return i?isAggregateExpression(i)?this.buildAggregateOperand(i,r):i instanceof PodColumnBase||typeof i=="string"||i&&typeof i=="object"&&"name"in i?`?${resolveColumn(i,r).name}`:`?${e}`:`?${e}`}buildAggregateOperand(e,t){const r=e.distinct?"DISTINCT ":"";if(!e.column)return`${e.func.toUpperCase()}(*)`;const i=resolveColumn(e.column,t);return`${e.func.toUpperCase()}(${r}?${i.name})`}getUriContext(){if(this.tableContext)return{baseUri:this.tableContext.baseUri,tableRegistry:this.tableContext.tableRegistry,tableNameRegistry:this.tableContext.tableNameRegistry}}convertSimpleSelect(e,t,r,i=!0){const s=e.table;s.config.type;const o={queryType:"SELECT",variables:[{termType:"Variable",value:"subject"}],where:this.buildWherePatterns(e,s,t,r,i),type:"query",prefixes:this.prefixes};return r&&r.length>0&&!t&&(o.from={default:r.map(a=>({termType:"NamedNode",value:a})),named:[]}),Object.keys(s.columns).forEach(a=>{const c=s.columns[a],l=getPredicateForColumn(c,s);l&&l!=="@id"&&o.variables.push({termType:"Variable",value:a})}),typeof e.limit=="number"&&(o.limit=e.limit),typeof e.offset=="number"&&(o.offset=e.offset),e.orderBy&&e.orderBy.length>0&&(o.order=e.orderBy.map(a=>({expression:{termType:"Variable",value:a.column},descending:a.direction==="desc"}))),e.distinct&&(o.distinct=!0),{type:"SELECT",query:this.generator.stringify(o),prefixes:this.prefixes}}buildSelectVariables(e,t){const r=e.select,i=Array.isArray(e.groupBy)&&e.groupBy.length>0;let s=!1;if(r&&typeof r=="object"&&Object.keys(r).length>0){const d=Object.values(r);s=d.length>0&&d.every(f=>isAggregateExpression(f))}const a=!s&&(!i||i&&e.groupBy.includes("subject"))?[{termType:"Variable",value:"subject"}]:[],c=new Set(["subject"]);for(const[d,f]of Object.entries(t.columns))getPredicateForColumn(f,t)==="@id"&&c.add(d);if(r&&typeof r=="object"&&Object.keys(r).length>0){const d=Object.entries(r).filter(([f])=>!c.has(f)).map(([f,u])=>this.buildSelectEntry(f,u,t));return a.concat(d)}if(e.columns==="*"||!e.columns){const d=Object.keys(t.columns).filter(f=>!c.has(f)).map(f=>({termType:"Variable",value:f}));return a.concat(d)}const l=e.columns.filter(d=>{const f=typeof d=="string"?d:d.name;return!c.has(f)}).map(d=>({termType:"Variable",value:typeof d=="string"?d:d.name}));return a.concat(l)}buildSelectEntry(e,t,r){if(isAggregateExpression(t))return this.buildAggregateSelectEntry(e,t,r);const s=resolveColumn(t,r).name;return e===s?{termType:"Variable",value:s}:{expression:{termType:"Variable",value:s},variable:{termType:"Variable",value:e}}}buildAggregateSelectEntry(e,t,r){const i=t.func,s=t.column?{termType:"Variable",value:resolveColumn(t.column,r).name}:new sparqlExports.Wildcard;return{expression:{type:"aggregate",aggregation:i,distinct:!!t.distinct,expression:s},variable:{termType:"Variable",value:e}}}buildWherePatterns(e,t,r,i,s=!0){const o=[],a=e.where?this.expressionBuilder.extractSubjectConstraint(e.where,t):null,c=a?a.remainingCondition:e.where;a?.values?.length&&o.push({type:"values",values:a.values.map(g=>({"?subject":{termType:"NamedNode",value:g}}))}),o.push({type:"bgp",triples:[{subject:{termType:"Variable",value:"subject"},predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:t.config.type}}]});const l=[],d=[],f=new Set;if(c&&typeof c=="object"){const g=y=>{!y||typeof y!="object"||(y.left&&(typeof y.left=="string"?f.add(y.left):y.left.name&&f.add(y.left.name)),y.value&&(typeof y.value=="string"?f.add(y.value):y.value.name?f.add(y.value.name):typeof y.value=="object"&&g(y.value)),y.expressions&&Array.isArray(y.expressions)&&y.expressions.forEach(g))};g(c)}const u=e.select;let p=null;if(u&&typeof u=="object"&&Object.keys(u).length>0){p=new Set;const g=y=>y?typeof y=="string"?y:y.name?y.name:isAggregateExpression(y)&&y.column?g(y.column):null:null;for(const[y,w]of Object.entries(u)){p.add(y);const _=g(w);_&&p.add(_)}if(f.forEach(y=>p.add(y)),Array.isArray(e.orderBy))for(const y of e.orderBy)y.column&&p.add(y.column);if(Array.isArray(e.groupBy))for(const y of e.groupBy){const w=g(y);w&&p.add(w)}}if(Object.entries(t.columns).forEach(([g,y])=>{if(p&&!p.has(g))return;const w=getPredicateForColumn(y,t);if(w==="@id")return;const _={termType:"Variable",value:"subject"},R={termType:"Variable",value:g},b=y.options?.inverse,C={subject:b?R:_,predicate:{termType:"NamedNode",value:w},object:b?_:R};b?d.push(C):y.options?.required||f.has(g)?l.push(C):d.push(C)}),l.length>0&&o.push({type:"bgp",triples:l}),d.forEach(g=>{o.push({type:"optional",patterns:[{type:"bgp",triples:[g]}]})}),c){const g=this.expressionBuilder.buildWhereClause(c,t);if(g)try{const w=`${Object.entries(this.prefixes).map(([b,C])=>`PREFIX ${b}: <${C}>`).join(`
52
+ `)}
53
+ SELECT * WHERE { ${g} }`,R=new sparqlExports.Parser().parse(w);if(R.where){const b=R.where.find(C=>C.type==="filter");b&&o.push(b)}}catch(y){console.warn("Failed to parse filter string into AST:",g,y)}}return r?[{type:"graph",name:{termType:"NamedNode",value:r},patterns:o}]:s&&this.uriResolver.getResourceMode(t)==="document"&&(!i||i.length===0)?[{type:"graph",name:{termType:"Variable",value:"g"},patterns:o}]:o}}const XSD$5="http://www.w3.org/2001/XMLSchema#";class DefaultHandler{constructor(){this.name="default"}canHandle(e){const t=e.dataType;return t==="string"||t==="integer"||t==="boolean"||t==="datetime"}formatValue(e,t,r){switch(t.dataType){case"string":return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$5}string`}};case"integer":return{termType:"Literal",value:String(Number(e)),datatype:{termType:"NamedNode",value:`${XSD$5}integer`}};case"boolean":return{termType:"Literal",value:String(!!e),datatype:{termType:"NamedNode",value:`${XSD$5}boolean`}};case"datetime":return{termType:"Literal",value:(e instanceof Date?e:new Date(e)).toISOString(),datatype:{termType:"NamedNode",value:`${XSD$5}dateTime`}};default:return{termType:"Literal",value:String(e)}}}parseValue(e,t){const r=e.datatype?.value??"";switch(t.dataType){case"integer":return parseInt(e.value,10);case"boolean":return e.value==="true";case"datetime":return new Date(e.value);default:return r.includes("#integer")||r.includes("#int")?parseInt(e.value,10):r.includes("#boolean")?e.value==="true":r.includes("#dateTime")?new Date(e.value):e.value}}buildTriples(e,t,r,i,s,o){const a=this.formatValue(r,i);return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:a}]}}}class UriHandler{constructor(){this.name="uri"}canHandle(e){return e.dataType==="uri"||e.isLink()}toUriContext(e){if(e)return{baseUri:e.baseUri,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry,record:e.record,currentTable:e.currentTable}}formatValue(e,t,r){const i=String(e),s=this.toUriContext(r);return{termType:"NamedNode",value:(r?.uriResolver??new UriResolverImpl).resolveLink(i,t,s)}}parseValue(e,t){return e.value}buildTriples(e,t,r,i,s,o){const a=this.formatValue(r,i,o);return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:a}]}}}const XSD$4="http://www.w3.org/2001/XMLSchema#";class ArrayHandler{constructor(){this.name="array"}canHandle(e){return e.options?.isArray===!0||e.dataType==="array"}formatValue(e,t,r){if(!Array.isArray(e))throw new Error("Array column requires array value");const i=t.options?.baseType??"string";return e.map(s=>this.formatSingleValue(s,i))}formatSingleValue(e,t){switch(t){case"string":return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$4}string`}};case"integer":return{termType:"Literal",value:String(Number(e)),datatype:{termType:"NamedNode",value:`${XSD$4}integer`}};case"boolean":return{termType:"Literal",value:String(!!e),datatype:{termType:"NamedNode",value:`${XSD$4}boolean`}};case"datetime":return{termType:"Literal",value:(e instanceof Date?e:new Date(e)).toISOString(),datatype:{termType:"NamedNode",value:`${XSD$4}dateTime`}};case"uri":return{termType:"NamedNode",value:String(e)};default:return{termType:"Literal",value:String(e)}}}parseValue(e,t){const r=t.options?.baseType??"string",i=e.datatype?.value??"";switch(r){case"integer":return parseInt(e.value,10);case"boolean":return e.value==="true";case"datetime":return new Date(e.value);case"uri":return e.value;default:return i.includes("#integer")?parseInt(e.value,10):i.includes("#boolean")?e.value==="true":i.includes("#dateTime")?new Date(e.value):e.value}}buildTriples(e,t,r,i,s,o){let a;return Array.isArray(r)?a=r:typeof r=="string"&&r.includes(",")?a=r.split(",").map(d=>d.trim()).filter(Boolean):a=[r],{triples:this.formatValue(a,i).map(d=>({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:d}))}}}const XSD$3="http://www.w3.org/2001/XMLSchema#";class InverseHandler{constructor(){this.name="inverse"}canHandle(e){return e.options?.inverse===!0}toUriContext(e){if(e)return{baseUri:e.baseUri,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry,record:e.record,currentTable:e.currentTable}}formatValue(e,t,r){if(t.options?.linkTarget||t.dataType==="uri"||t.isLink?.()){const i=String(e),s=this.toUriContext(r);return{termType:"NamedNode",value:(r?.uriResolver??new UriResolverImpl).resolveLink(i,t,s)}}return this.isUri(e)?{termType:"NamedNode",value:String(e)}:{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$3}string`}}}isUri(e){return typeof e!="string"?!1:e.startsWith("http://")||e.startsWith("https://")}parseValue(e,t){return e.value}buildTriples(e,t,r,i,s,o){return{triples:(Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(l=>l.trim()).filter(Boolean):[r]).map(l=>({subject:this.formatValue(l,i,o),predicate:{termType:"NamedNode",value:t},object:{termType:"NamedNode",value:e}}))}}}const XSD$2="http://www.w3.org/2001/XMLSchema#";class InlineObjectHandler{constructor(){this.name="inline"}canHandle(e){if(e.dataType==="object"||e.dataType==="json")return!0;if(e.dataType==="array"){const t=e.elementType||e.options?.baseType;return t==="object"||t==="json"}return!1}formatValue(e,t,r){return typeof e=="string"?{termType:"NamedNode",value:e}:{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$2}json`}}}parseValue(e,t){if(e.datatype?.value?.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.termType==="NamedNode",e.value}buildTriples(e,t,r,i,s,o){const a=[],c=[];return(Array.isArray(r)?r:[r]).forEach((d,f)=>{if(!d||typeof d!="object")return;const u=d,p=o.resolveInlineChildUri(e,i.name,u,f);a.push({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:{termType:"NamedNode",value:p}});const g=this.buildChildTriples(p,u,s,o);c.push(...g)}),{triples:a,childTriples:c}}buildChildTriples(e,t,r,i){const s=[],o=i.getNamespaceUri(r);return Object.entries(t).forEach(([a,c])=>{if(a==="id"||a==="@id"||c==null)return;const l=this.resolvePredicateUri(a,o);(Array.isArray(c)?[c]:[c]).forEach(f=>{const u=this.formatChildValue(f);s.push({subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:l},object:u})})}),s}resolvePredicateUri(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:t?`${t}${e}`:`http://example.org/${e}`}formatChildValue(e){if(e==null)return{termType:"Literal",value:""};if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return{termType:"NamedNode",value:e};if(typeof e=="number"){const t=Number.isInteger(e)?`${XSD$2}integer`:`${XSD$2}decimal`;return{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:t}}}return typeof e=="boolean"?{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$2}boolean`}}:e instanceof Date?{termType:"Literal",value:e.toISOString(),datatype:{termType:"NamedNode",value:`${XSD$2}dateTime`}}:typeof e=="object"?{termType:"Literal",value:JSON.stringify(e),datatype:{termType:"NamedNode",value:`${XSD$2}json`}}:{termType:"Literal",value:String(e),datatype:{termType:"NamedNode",value:`${XSD$2}string`}}}}class HandlerRegistry{constructor(){this.handlers=[],this.register(new InlineObjectHandler),this.register(new InverseHandler),this.register(new ArrayHandler),this.register(new UriHandler),this.register(new DefaultHandler)}register(e){this.handlers.push(e)}getHandler(e){for(const t of this.handlers)if(t.canHandle(e))return t;throw new Error(`No handler found for column: ${e.name} (type: ${e.dataType})`)}getAllHandlers(){return[...this.handlers]}}const handlerRegistry=new HandlerRegistry,RDF_TYPE="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",XSD$1="http://www.w3.org/2001/XMLSchema#";class TripleBuilderImpl{constructor(e){this.uriResolver=e??new UriResolverImpl}setTableRegistry(e,t){this.tableRegistry=e,this.tableNameRegistry=t}setBaseUri(e){this.baseUri=e}createContext(e,t){return{resolveInlineChildUri:this.resolveInlineChildUri.bind(this),getNamespaceUri:this.getNamespaceUri.bind(this),uriResolver:this.uriResolver,baseUri:this.baseUri,tableRegistry:this.tableRegistry,tableNameRegistry:this.tableNameRegistry,record:e,currentTable:t}}buildInsert(e,t,r,i){const s=handlerRegistry.getHandler(t),o=this.getPredicateUri(t,i),a=this.createContext(i?.__currentRecord,i);return s.buildTriples(e,o,r,t,i,a)}buildDelete(e,t,r,i=""){const s=this.getPredicateUri(t,r),o=`old_${t.name}${i}`;return t.dataType==="object"||t.dataType==="json"?this.buildInlineDeleteTriples(e,s,t.name,i):t.options?.inverse?{triples:[{subject:{termType:"Variable",value:o},predicate:{termType:"NamedNode",value:s},object:{termType:"NamedNode",value:e}}]}:{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:s},object:{termType:"Variable",value:o}}]}}buildInlineDeleteTriples(e,t,r,i){const s=`old_${r}${i}`,o=`op_${r}${i}`,a=`oo_${r}${i}`;return{triples:[{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:t},object:{termType:"Variable",value:s}}],childTriples:[{subject:{termType:"Variable",value:s},predicate:{termType:"Variable",value:o},object:{termType:"Variable",value:a}}]}}buildTypeTriple(e,t){return{subject:{termType:"NamedNode",value:e},predicate:{termType:"NamedNode",value:RDF_TYPE},object:{termType:"NamedNode",value:t}}}toN3Strings(e){return e.map(t=>{const r=this.termToN3(t.subject),i=this.termToN3(t.predicate),s=this.termToN3(t.object);return`${r} ${i} ${s} .`})}termToN3(e){switch(e.termType){case"NamedNode":return`<${e.value}>`;case"Variable":return`?${e.value}`;case"BlankNode":return`_:${e.value}`;case"Literal":{if(e.value.includes(`
54
+ `)||e.value.includes("\r")){let i=e.value;if(i=i.replace(/"""/g,'"\\"\\""'),i.endsWith('"')){const s=i.match(/"*$/),o=s?s[0].length:0;o>0&&(i=i.slice(0,-o)+'\\"'.repeat(o))}if(e.language)return`"""${i}"""@${e.language}`;if(e.datatype){const s=e.datatype.value;return s===`${XSD$1}string`?`"""${i}"""`:s===`${XSD$1}integer`?e.value:`"""${i}"""^^<${s}>`}return`"""${i}"""`}const r=e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(e.language)return`"${r}"@${e.language}`;if(e.datatype){const i=e.datatype.value;return i===`${XSD$1}string`?`"${r}"`:i===`${XSD$1}integer`?e.value:`"${r}"^^<${i}>`}return`"${r}"`}default:return`"${e.value}"`}}buildN3Patch(e,t,r=[]){const i=g=>g.trim().endsWith(".")?g.trim():`${g.trim()} .`,s=e.map(i),o=t.map(i),a=r.map(i),c=s.length>0,l=a.length>0,d=c?` solid:delete {
55
+ ${s.map(g=>` ${g}`).join(`
56
+ `)}
57
+ };
58
+ `:"",f=o.length>0?` solid:insert {
59
+ ${o.map(g=>` ${g}`).join(`
60
+ `)}
61
+ };
62
+ `:"",u=l?` solid:where {
63
+ ${a.map(g=>` ${g}`).join(`
64
+ `)}
65
+ }.
66
+ `:"",p=`@prefix solid: <http://www.w3.org/ns/solid/terms#>.
67
+ _:patch a solid:InsertDeletePatch;
68
+ `;if(!c&&!l){const g=f.endsWith(`;
69
+ `)?f.replace(/;\n$/,`.
70
+ `):f||` solid:insert { }.
71
+ `;return`${p}${g}`}return`${p}${d}${f}${u}`.replace(/;\n$/,`.
72
+ `)}getPredicateUri(e,t){if(e.options?.predicate==="@id")return"@id";if(e.options?.predicate)return e.options.predicate;const r=t.config?.namespace;return r?`${typeof r=="string"?r:r.uri}${e.name}`:`http://example.org/${e.name}`}formatValue(e,t){if(e==null)return'""';if(!t)return this.formatValueByInference(e);const i=handlerRegistry.getHandler(t).formatValue(e,t);return Array.isArray(i)?i.map(s=>this.termToN3(s)):this.termToN3(i)}formatValueByInference(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?`<${e}>`:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e=="number"?Number.isInteger(e)?String(e):`"${e}"^^<${XSD$1}decimal>`:typeof e=="boolean"?`"${e}"^^<${XSD$1}boolean>`:e instanceof Date?`"${e.toISOString()}"^^<${XSD$1}dateTime>`:typeof e=="object"?`"${JSON.stringify(e).replace(/"/g,'\\"')}"^^<${XSD$1}json>`:`"${String(e)}"`}resolveInlineChildUri(e,t,r,i){const s=typeof r["@id"]=="string"?r["@id"]:typeof r.id=="string"?r.id:void 0;if(s)return s;const o=e.indexOf("#"),a=o>=0?e.slice(0,o):e;return`${a.endsWith("#")?a:`${a}#`}${t}-${i+1}`}getNamespaceUri(e){const t=e.config?.namespace;if(t)return typeof t=="string"?t:t.uri}}new TripleBuilderImpl(new UriResolverImpl);function getDocumentUriFromSubjectUri(n){const e=n.indexOf("#");return e!==-1?n.substring(0,e):n}class UpdateBuilder{constructor(e,t=new UriResolverImpl){this.toSparqlJsTriple=r=>r,this.generator=new sparqlExports.Generator,this.prefixes=e,this.uriResolver=t,this.tripleBuilder=new TripleBuilderImpl(t)}setTableContext(e){this.tableContext=e,this.tripleBuilder.setTableRegistry(e.tableRegistry,e.tableNameRegistry),e.baseUri&&this.tripleBuilder.setBaseUri(e.baseUri)}getUriContext(e,t){if(!(!this.tableContext&&!e&&!t))return{baseUri:this.tableContext?.baseUri,tableRegistry:this.tableContext?.tableRegistry,tableNameRegistry:this.tableContext?.tableNameRegistry,record:e,currentTable:t}}resolveLinkTerm(e,t,r,i){const s=String(e??"").replace(/^<|>$/g,"");if(this.uriResolver.isAbsoluteUri(s))return s;try{return this.uriResolver.resolveLink(s,t,this.getUriContext(i,r))}catch(o){const a=r.config?.name??"unknown",c=t?.name??"unknown";throw new Error(`[UpdateBuilder] Failed to resolve URI for ${a}.${c}: ${o}`)}}formatValueOrThrow(e,t,r,i){try{return formatValue(e,t,this.uriResolver,this.getUriContext(i,r))}catch(s){const o=r.config?.name??"unknown",a=t?.name??"unknown";throw new Error(`[UpdateBuilder] Failed to resolve URI for ${o}.${a}: ${s}`)}}convertInsert(e,t,r){if(!t&&!e)throw new Error("INSERT operation requires a target table");let i,s;if(Array.isArray(e)){if(i=e,!t)throw new Error("INSERT operation requires a target table");s=t}else i=e.rows,s=e.table;const o=new Set,a=[];for(const f of i)f.id&&(o.has(f.id)?a.push(f.id):o.add(f.id));if(a.length>0)throw new Error(`Duplicate IDs found in insert data: ${a.join(", ")}`);const c=this.buildInsertTriples(i,s),l=[];if(r){const f={type:"bgp",triples:c};l.push({updateType:"insert",insert:[{type:"graph",name:{termType:"NamedNode",value:r},patterns:[f]}]})}else{const f={};for(const u of c)if(u.subject&&u.subject.termType==="NamedNode"){const p=getDocumentUriFromSubjectUri(u.subject.value);f[p]||(f[p]=[]),f[p].push(u)}else f.__default__||(f.__default__=[]),f.__default__.push(u);for(const u in f){const g={type:"bgp",triples:f[u]};u==="__default__"?l.push({updateType:"insert",insert:[g]}):l.push({updateType:"insert",insert:[{type:"graph",name:{termType:"NamedNode",value:u},patterns:[g]}]})}}if(l.length===0)throw new Error("No valid insert statements generated");const d={type:"update",prefixes:this.prefixes,updates:l};return{type:"INSERT",query:this.generator.stringify(d),prefixes:this.prefixes}}buildInsertTriples(e,t){const r=[],i=t.config.type;for(const s of e){const o=generateSubjectUri(s,t,this.uriResolver),a={termType:"NamedNode",value:o};t.__currentRecord=s;try{r.push({subject:a,predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:i}}),Object.entries(s).forEach(([c,l])=>{if(c==="id"||l===void 0||l===null)return;const d=t.columns[c];if(!d)return;const f=getPredicateForColumn(d,t);if(d.dataType==="object"||d.dataType==="json"||d.dataType==="array"&&(d.elementType==="object"||d.options?.baseType==="object")){const y=this.tripleBuilder.buildInsert(o,d,l,t);r.push(...y.triples.map(this.toSparqlJsTriple),...y.childTriples?.map(this.toSparqlJsTriple)??[]);return}if(d.options?.inverse){(Array.isArray(l)?l:[l]).forEach(w=>{const _=this.resolveLinkTerm(w,d,t,s);r.push({subject:{termType:"NamedNode",value:_},predicate:{termType:"NamedNode",value:f},object:a})});return}const p=this.formatValueOrThrow(l,d,t,s),g=this.parseTermString(p);r.push({subject:a,predicate:{termType:"NamedNode",value:f},object:g})})}finally{delete t.__currentRecord}}return r}convertUpdate(e,t,r,i){const s=this.extractSubjectRecords(t);if(s.length===0)throw new Error("UPDATE operation requires an id or @id condition to target a specific resource");const o=[];for(const c of s){const l=generateSubjectUri(c,r,this.uriResolver),f={termType:"NamedNode",value:i||getDocumentUriFromSubjectUri(l)},{deleteTriples:u,insertTriples:p,whereTriples:g}=this.buildUpdatePartsForRecord(l,e,r),y={type:"bgp",triples:u},w={type:"bgp",triples:g.length>0?g:u};if(u.length>0&&o.push({updateType:"insertdelete",delete:[{type:"graph",name:f,patterns:[y]}],insert:[],where:[{type:"graph",name:f,patterns:[w]}]}),p.length>0){const _={type:"bgp",triples:p};o.push({updateType:"insert",insert:[{type:"graph",name:f,patterns:[_]}]})}}if(o.length===0)throw new Error("No valid update statements generated for provided data");const a={type:"update",prefixes:this.prefixes,updates:o};return{type:"UPDATE",query:this.generator.stringify(a),prefixes:this.prefixes}}convertDelete(e,t,r){const i=[];let s=[],o=[];const a=this.extractSubjectRecords(e);if(a.length===0)if(r){const l={termType:"NamedNode",value:r};s.push({subject:{termType:"Variable",value:"s"},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}),o.push({subject:{termType:"Variable",value:"s"},predicate:{termType:"NamedNode",value:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"},object:{termType:"NamedNode",value:t.config.type}});const d={updateType:"insertdelete",delete:[{type:"graph",name:l,patterns:[{type:"bgp",triples:s}]}],insert:[],where:[{type:"graph",name:l,patterns:[{type:"bgp",triples:o}]}]};i.push(d)}else throw new Error("DELETE operation in Document Mode requires specific resource IDs or an explicit target graph.");else for(const l of a){const d=generateSubjectUri(l,t,this.uriResolver),u={termType:"NamedNode",value:r||getDocumentUriFromSubjectUri(d)},_={updateType:"insertdelete",delete:[{type:"graph",name:u,patterns:[{type:"bgp",triples:[{subject:{termType:"NamedNode",value:d},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}]}]}],insert:[],where:[{type:"graph",name:u,patterns:[{type:"bgp",triples:[{subject:{termType:"NamedNode",value:d},predicate:{termType:"Variable",value:"p"},object:{termType:"Variable",value:"o"}}]}]}]};i.push(_)}if(i.length===0)throw new Error("No valid delete statements generated");const c={type:"update",prefixes:this.prefixes,updates:i};return{type:"DELETE",query:this.generator.stringify(c),prefixes:this.prefixes}}buildUpdatePartsForRecord(e,t,r){const i=[],s=[],o=[];return Object.entries(t).forEach(([a,c],l)=>{const d=r.columns[a];if(!d)return;const f=getPredicateForColumn(d,r),u=`old_${a}_${l}`,p=d.dataType==="object"||d.dataType==="json"||d.dataType==="array"&&(d.elementType==="object"||d.options?.baseType==="object"),g={termType:"NamedNode",value:e},y={termType:"NamedNode",value:f},w={termType:"Variable",value:u};if(p){const _={termType:"Variable",value:`p_${u}`},R={termType:"Variable",value:`o_${u}`},b={subject:g,predicate:y,object:w},C={subject:w,predicate:_,object:R};if(i.push(b,C),o.push(b,C),c!=null){const P=this.tripleBuilder.buildInsert(e,d,c,r);s.push(...P.triples.map(this.toSparqlJsTriple),...P.childTriples?.map(this.toSparqlJsTriple)??[])}return}if(d.options?.inverse){const _={subject:w,predicate:y,object:g};if(i.push(_),o.push(_),c!=null){const R=this.resolveLinkTerm(c,d,r,t);s.push({subject:{termType:"NamedNode",value:R},predicate:y,object:g})}}else{const _={subject:g,predicate:y,object:w};if(i.push(_),o.push(_),c!=null){const R=this.formatValueOrThrow(c,d,r,t),b=this.parseTermString(R);s.push({subject:g,predicate:y,object:b})}}}),{deleteTriples:i,insertTriples:s,whereTriples:o}}parseTermString(e){if(typeof e!="string")return{termType:"Literal",value:String(e)};if(e.startsWith("<"))return{termType:"NamedNode",value:e.slice(1,-1)};if(e.startsWith("_:"))return{termType:"BlankNode",value:e.slice(2)};if(e.startsWith('"')){const t=e.lastIndexOf('"'),r=e.slice(1,t),i=e.slice(t+1);let s,o;if(i.startsWith("^^")){const a=i.slice(2);s={termType:"NamedNode",value:a.startsWith("<")?a.slice(1,-1):a}}else i.startsWith("@")&&(o=i.slice(1));return{termType:"Literal",value:r,datatype:s,language:o}}return{termType:"Literal",value:e}}extractSubjectRecords(e){if(!e)return[];if(this.isQueryCondition(e)){const t=this.findConditionValue(e,"id"),r=this.findConditionValue(e,"@id"),i={};return r&&(i["@id"]=r),t&&(i.id=t),Object.keys(i).length>0?[i]:[]}return typeof e=="object"&&(e.id||e["@id"])?[e]:[]}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e}findConditionValue(e,t){if(e.type==="binary_expr"&&e.operator==="="){const r=e.left,i=e.right;let s;if(typeof r=="string"?s=r.includes(".")?r.split(".")[1]:r:r&&typeof r=="object"&&"name"in r?s=r.name:r&&typeof r=="object"&&"column"in r&&(s=r.column),s===t&&i!=null)return typeof i=="object"&&"value"in i?i.value:i}if(e.type==="logical_expr"){const r=e.expressions||e.conditions||[];for(const i of r){const s=this.findConditionValue(i,t);if(s!==void 0)return s}}}}class ASTToSPARQLConverter{constructor(e,t,r){this.podUrl=e,this.webId=t,this.prefixes={rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",schema:"https://schema.org/",foaf:"http://xmlns.com/foaf/0.1/",dc:"http://purl.org/dc/terms/",solid:"http://www.w3.org/ns/solid/terms#",ldp:"http://www.w3.org/ns/ldp#",xsd:"http://www.w3.org/2001/XMLSchema#"},this.uriResolver=r??new UriResolverImpl(e),this.selectBuilder=new SelectBuilder(this.prefixes,this.uriResolver),this.updateBuilder=new UpdateBuilder(this.prefixes,this.uriResolver),this.expressionBuilder=new ExpressionBuilder(this.uriResolver)}setTableRegistry(e,t,r){this.tableContext={tableRegistry:e,tableNameRegistry:t,baseUri:r},this.selectBuilder.setTableContext(this.tableContext),this.expressionBuilder.setTableContext(this.tableContext),this.updateBuilder.setTableContext(this.tableContext)}convertSelect(e,t,r,i,s=!0){return this.selectBuilder.convertSelect(e,t,r,i,s)}buildWhereClauseForCondition(e,t){return this.expressionBuilder.buildWhereClause(e,t)}convertSelectPlan(e,t,r,i=!0){return this.selectBuilder.convertSelectPlan(e,t,r,i)}convertSimpleSelect(e,t,r,i=!0){return this.selectBuilder.convertSimpleSelect(e,t,r,i)}convertInsert(e,t,r){return this.updateBuilder.convertInsert(e,t,r)}convertUpdate(e,t,r,i){return this.updateBuilder.convertUpdate(e,t,r,i)}convertDelete(e,t,r){return this.updateBuilder.convertDelete(e,t,r)}getPrefixes(){return this.prefixes}addPrefix(e,t){this.prefixes[e]=t}getPredicateForColumnPublic(e,t){return getPredicateForColumn(e,t)}formatLiteralValue(e,t){return formatValue(e,t)}generateSubjectUri(e,t){return generateSubjectUri(e,t,this.uriResolver)}parseDrizzleAST(e,t){return{type:"select",columns:"*",where:this.parseWhereClause(e)}}parseWhereClause(e){return{}}}class TypeIndexDiscovery{constructor(e,t,r){this.manager=e,this.podUrl=t,this.uriResolver=r??new UriResolverImpl(t)}setPodUrl(e){this.podUrl=e}getPodUrl(){return typeof this.manager.getConfig=="function"?this.manager.getConfig().podUrl||this.podUrl:this.podUrl}async register(e,t){if(!e.shouldRegisterTypeIndex?.())return;e.config.name??JSON.stringify(e.config);const i=this.getRdfClass(e),s=e._.config?.isPublic?"public":"private";this.uriResolver.getResourceMode(e);let o=e.getContainerPath()||"/data/";const a=this.getPodUrl();let c=`${a.replace(/\/$/,"")}${o}`;const l=this.resolveTableResource(e);if(l.mode==="ldp"){const f=l.containerUrl,u=a.replace(/\/$/,"");f.startsWith(u)&&(o=f.substring(u.length),c=f.replace(/\/$/,"")+"/")}const d={rdfClass:i,containerPath:o,forClass:e.config.name,instanceContainer:c,visibility:s};try{const f=await this.manager.discoverSpecificType(i);f&&f.instanceContainer!==c&&console.warn(`[TypeIndexDiscovery] ⚠️ TypeIndex has different path for ${e.config.name}:
73
+ - TypeIndex: ${f.instanceContainer}
74
+ - Configured: ${c}
75
+ Updating TypeIndex to use configured path...`),await this.manager.registerType(d)}catch(f){this.handleRegistrationError(f,d,s)}}async discover(e,t){const r=[],i=await this.manager.discoverSpecificTypes([e]);for(const s of i)r.push({container:s.instanceContainer??s.containerPath,shapes:[],source:"typeindex"});return r}async isRegistered(e){return!!await this.manager.discoverSpecificType(e)}getRdfClass(e){return typeof e.config.type=="string"?e.config.type:e.config.type.value||String(e.config.type)}resolveTableResource(e){const t=e.getResourcePath?.()??e.config.base,r=e.getContainerPath()||"/data/";return{mode:"ldp",containerUrl:this.toAbsolute(r),resourceUrl:this.toAbsolute(t??r)}}toAbsolute(e){if(e.startsWith("http"))return e;const t=this.getPodUrl(),r=t.endsWith("/")?t:`${t}/`,i=e.startsWith("/")?e.slice(1):e;return`${r}${i}`}async handleRegistrationError(e,t,r){if((e instanceof Error?e.message:String(e)).includes("TypeIndex not found")){console.warn("[TypeIndexDiscovery] TypeIndex missing. Attempting to create.");try{const s=await this.manager.createTypeIndex(r==="public");await this.manager.registerType(t,s)}catch(s){console.warn("[TypeIndexDiscovery] Unable to create TypeIndex. Continuing without registration.",s)}}else console.warn("[TypeIndexDiscovery] TypeIndex registration failed. Continuing without registration.",e)}}const INTEROP={NS:"http://www.w3.org/ns/solid/interop#",ApplicationRegistration:"http://www.w3.org/ns/solid/interop#ApplicationRegistration",DataRegistration:"http://www.w3.org/ns/solid/interop#DataRegistration",AccessGrant:"http://www.w3.org/ns/solid/interop#AccessGrant",DataGrant:"http://www.w3.org/ns/solid/interop#DataGrant",RegistrySet:"http://www.w3.org/ns/solid/interop#RegistrySet",DataRegistry:"http://www.w3.org/ns/solid/interop#DataRegistry",hasRegistrySet:"http://www.w3.org/ns/solid/interop#hasRegistrySet",hasDataRegistry:"http://www.w3.org/ns/solid/interop#hasDataRegistry",hasDataRegistration:"http://www.w3.org/ns/solid/interop#hasDataRegistration",registeredShapeTree:"http://www.w3.org/ns/solid/interop#registeredShapeTree",registeredBy:"http://www.w3.org/ns/solid/interop#registeredBy",hasAccessGrant:"http://www.w3.org/ns/solid/interop#hasAccessGrant",hasDataGrant:"http://www.w3.org/ns/solid/interop#hasDataGrant",scopeOfGrant:"http://www.w3.org/ns/solid/interop#scopeOfGrant",dataOwner:"http://www.w3.org/ns/solid/interop#dataOwner",registeredShapeTreeProp:"http://www.w3.org/ns/solid/interop#registeredShapeTree"},SHAPETREES={NS:"http://www.w3.org/ns/shapetrees#",ShapeTree:"http://www.w3.org/ns/shapetrees#ShapeTree",expectsType:"http://www.w3.org/ns/shapetrees#expectsType",shape:"http://www.w3.org/ns/shapetrees#shape"},UDFS={NS:"https://vocab.undefineds.co/",subjectTemplate:"https://vocab.undefineds.co/subjectTemplate"},ns={prefix:"interop",uri:INTEROP.NS},registrySetSchema=solidSchema({id:id(),hasDataRegistry:uri("hasDataRegistry").array().predicate(INTEROP.hasDataRegistry),hasAgentRegistry:uri("hasAgentRegistry").array().predicate("http://www.w3.org/ns/solid/interop#hasAgentRegistry")},{type:INTEROP.RegistrySet,namespace:ns}),dataRegistrySchema=solidSchema({id:id(),hasDataRegistration:uri("hasDataRegistration").array().predicate(INTEROP.hasDataRegistration)},{type:INTEROP.DataRegistry,namespace:ns}),dataRegistrationSchema=solidSchema({id:id(),registeredShapeTree:uri("registeredShapeTree").predicate(INTEROP.registeredShapeTree),registeredBy:uri("registeredBy").predicate(INTEROP.registeredBy),registeredAt:string$2("registeredAt").predicate("http://www.w3.org/ns/solid/interop#registeredAt"),subjectTemplate:string$2("subjectTemplate").predicate(UDFS.subjectTemplate)},{type:INTEROP.DataRegistration,namespace:ns}),applicationRegistrationSchema=solidSchema({id:id(),registeredAgent:uri("registeredAgent").predicate("http://www.w3.org/ns/solid/interop#registeredAgent"),hasAccessGrant:uri("hasAccessGrant").predicate(INTEROP.hasAccessGrant)},{type:INTEROP.ApplicationRegistration,namespace:ns}),accessGrantSchema=solidSchema({id:id(),grantedBy:uri("grantedBy").predicate("http://www.w3.org/ns/solid/interop#grantedBy"),grantedAt:string$2("grantedAt").predicate("http://www.w3.org/ns/solid/interop#grantedAt"),grantee:uri("grantee").predicate("http://www.w3.org/ns/solid/interop#grantee"),hasDataGrant:uri("hasDataGrant").array().predicate(INTEROP.hasDataGrant)},{type:INTEROP.AccessGrant,namespace:ns}),dataGrantSchema=solidSchema({id:id(),registeredShapeTree:uri("registeredShapeTree").predicate(INTEROP.registeredShapeTree),hasDataRegistration:uri("hasDataRegistration").predicate(INTEROP.hasDataRegistration),scopeOfGrant:uri("scopeOfGrant").predicate(INTEROP.scopeOfGrant),accessMode:uri("accessMode").array().predicate("http://www.w3.org/ns/solid/interop#accessMode"),dataOwner:uri("dataOwner").predicate(INTEROP.dataOwner)},{type:INTEROP.DataGrant,namespace:ns});var link,hasRequiredLink;function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;var n=/^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i,e=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/\s|\uFEFF|\xA0/,r=/\r?\n[\x20\x09]+/g,i=/[;,"]/,s=/[;,"]|\s/,o=/^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/,a={IDLE:1,URI:2,ATTR:4};function c(g){return g.replace(e,"")}function l(g){return t.test(g)}function d(g,y){for(;l(g[y]);)y++;return y}function f(g){return s.test(g)||!o.test(g)}function u(g,y){return Object.keys(g).length===Object.keys(y).length&&Object.keys(g).every(w=>w in y&&g[w]===y[w])}class p{constructor(y){this.refs=[],y&&this.parse(y)}rel(y){for(var w=[],_=y.toLowerCase(),R=0;R<this.refs.length;R++)typeof this.refs[R].rel=="string"&&this.refs[R].rel.toLowerCase()===_&&w.push(this.refs[R]);return w}get(y,w){y=y.toLowerCase(),w=w.toLowerCase();for(var _=[],R=0;R<this.refs.length;R++)typeof this.refs[R][y]=="string"&&this.refs[R][y].toLowerCase()===w&&_.push(this.refs[R]);return _}set(y){return this.refs.push(y),this}setUnique(y){return this.refs.some(w=>u(w,y))||this.refs.push(y),this}has(y,w){y=y.toLowerCase(),w=w.toLowerCase();for(var _=0;_<this.refs.length;_++)if(typeof this.refs[_][y]=="string"&&this.refs[_][y].toLowerCase()===w)return!0;return!1}parse(y,b){b=b||0,y=b?y.slice(b):y,y=c(y).replace(r,"");for(var _=a.IDLE,R=y.length,b=0,C=null;b<R;)if(_===a.IDLE){if(l(y[b])){b++;continue}else if(y[b]==="<"){C!=null&&(C.rel!=null?this.refs.push(...p.expandRelations(C)):this.refs.push(C));var P=y.indexOf(">",b);if(P===-1)throw new Error("Expected end of URI delimiter at offset "+b);C={uri:y.slice(b+1,P)},b=P,_=a.URI}else throw new Error('Unexpected character "'+y[b]+'" at offset '+b);b++}else if(_===a.URI)if(l(y[b])){b++;continue}else if(y[b]===";")_=a.ATTR,b++;else if(y[b]===",")_=a.IDLE,b++;else throw new Error('Unexpected character "'+y[b]+'" at offset '+b);else if(_===a.ATTR){if(y[b]===";"||l(y[b])){b++;continue}var P=y.indexOf("=",b);P===-1&&(P=y.indexOf(";",b)),P===-1&&(P=y.length);var H=c(y.slice(b,P)).toLowerCase(),M="";if(b=P+1,b=d(y,b),y[b]==='"')for(b++;b<R;){if(y[b]==='"'){b++;break}y[b]==="\\"&&b++,M+=y[b],b++}else{for(var P=b+1;!i.test(y[P])&&P<R;)P++;M=y.slice(b,P),b=P}switch(C[H]&&p.isSingleOccurenceAttr(H)||(H[H.length-1]==="*"?C[H]=p.parseExtendedValue(M):(M=H==="type"?M.toLowerCase():M,C[H]!=null?Array.isArray(C[H])?C[H].push(M):C[H]=[C[H],M]:C[H]=M)),y[b]){case",":_=a.IDLE;break;case";":_=a.ATTR;break}b++}else throw new Error('Unknown parser state "'+_+'"');return C!=null&&(C.rel!=null?this.refs.push(...p.expandRelations(C)):this.refs.push(C)),C=null,this}toString(){for(var y=[],w="",_=null,R=0;R<this.refs.length;R++)_=this.refs[R],w=Object.keys(this.refs[R]).reduce(function(b,C){return C==="uri"?b:b+"; "+p.formatAttribute(C,_[C])},"<"+_.uri+">"),y.push(w);return y.join(", ")}}return p.isCompatibleEncoding=function(g){return n.test(g)},p.parse=function(g,y){return new p().parse(g,y)},p.isSingleOccurenceAttr=function(g){return g==="rel"||g==="type"||g==="media"||g==="title"||g==="title*"},p.isTokenAttr=function(g){return g==="rel"||g==="type"||g==="anchor"},p.escapeQuotes=function(g){return g.replace(/"/g,'\\"')},p.expandRelations=function(g){var y=g.rel.split(" ");return y.map(function(w){var _=Object.assign({},g);return _.rel=w,_})},p.parseExtendedValue=function(g){var y=/([^']+)?(?:'([^']*)')?(.+)/.exec(g);return{language:y[2].toLowerCase(),encoding:p.isCompatibleEncoding(y[1])?null:y[1].toLowerCase(),value:p.isCompatibleEncoding(y[1])?decodeURIComponent(y[3]):y[3]}},p.formatExtendedAttribute=function(g,y){var w=(y.encoding||"utf-8").toUpperCase(),_=y.language||"en",R="";return Buffer.isBuffer(y.value)&&p.isCompatibleEncoding(w)?R=y.value.toString(w):Buffer.isBuffer(y.value)?R=y.value.toString("hex").replace(/[0-9a-f]{2}/gi,"%$1"):R=encodeURIComponent(y.value),g+"="+w+"'"+_+"'"+R},p.formatAttribute=function(g,y){return Array.isArray(y)?y.map(w=>p.formatAttribute(g,w)).join("; "):g[g.length-1]==="*"||typeof y!="string"?p.formatExtendedAttribute(g,y):(p.isTokenAttr(g)?y=f(y)?'"'+p.escapeQuotes(y)+'"':p.escapeQuotes(y):f(y)&&(y=encodeURIComponent(y),y=y.replace(/%20/g," ").replace(/%2C/g,",").replace(/%3B/g,";"),y='"'+y+'"'),g+"="+y)},link=p,link}class InruptClientError extends Error{}const PROBLEM_DETAILS_MIME="application/problem+json",DEFAULT_TYPE=new URL("about:blank");function asUrl$1(n,e){if(n!==void 0)try{return new URL(n,e)}catch{}}function buildProblemDetails(n){let e,t,r,i,s;if(n.headers.get("Content-Type")===PROBLEM_DETAILS_MIME)try{const o=JSON.parse(n.body),a=asUrl$1(o.type,n.url);a!==void 0&&(e=a),typeof o.title=="string"&&(t=o.title),typeof o.status=="number"&&(r=o.status),typeof o.detail=="string"&&(i=o.detail);const c=asUrl$1(o.instance,n.url);c!==void 0&&(s=c)}catch{}return Object.freeze({type:e??DEFAULT_TYPE,title:t??n.statusText,status:r??n.status,detail:i,instance:s})}class ClientHttpError extends InruptClientError{constructor(e,t,r,i){if(super(r,i),e.status>=200&&e.status<400)throw new InruptClientError(`A ClientHttpError cannot be built from a success response, got ${e.status} ${e.statusText}`);this.errorResponse=Object.freeze({status:e.status,statusText:e.statusText,headers:e.headers,url:e.url,body:t,ok:!1}),this.details=buildProblemDetails(this.errorResponse)}get response(){return this.errorResponse}get problemDetails(){return this.details}}function hasResourceInfo(n){const e=n;return typeof e=="object"&&typeof e.internal_resourceInfo=="object"}function hasServerResourceInfo(n){const e=n;return typeof e=="object"&&typeof e.internal_resourceInfo=="object"&&typeof e.internal_resourceInfo.linkedResources=="object"}function hasChangelog(n){const e=n;return typeof e.internal_changeLog=="object"&&Array.isArray(e.internal_changeLog.additions)&&Array.isArray(e.internal_changeLog.deletions)}class SolidClientError extends Error{}function internal_toIriString(n){return typeof n=="string"?n:n.value}function normalizeUrl(n,e={}){const t=new URL(n);return t.pathname=t.pathname.replace(/\/\/+/g,"/"),e.trailingSlash===!1&&t.pathname.slice(-1)==="/"&&(t.pathname=t.pathname.slice(0,t.pathname.length-1)),e.trailingSlash===!0&&t.pathname.slice(-1)!=="/"&&(t.pathname=`${t.pathname}/`),t.href}var linkExports=requireLink();const LinkHeader=getDefaultExportFromCjs(linkExports);function internal_parseResourceInfo(n){var e,t,r,i,s;const o=(t=(e=n.headers.get("Content-Type"))===null||e===void 0?void 0:e.split(";"))!==null&&t!==void 0?t:[],a=o.length>0&&["text/turtle","application/ld+json"].includes(o[0]),c={sourceIri:n.url,isRawData:!a,contentLocation:(r=n.headers.get("Content-Location"))!==null&&r!==void 0?r:void 0,contentType:(i=n.headers.get("Content-Type"))!==null&&i!==void 0?i:void 0,linkedResources:{},location:(s=n.headers.get("Location"))!==null&&s!==void 0?s:void 0},l=n.headers.get("Link");if(l){const f=LinkHeader.parse(l),u=f.get("rel","acl");u.length===1&&(c.aclUrl=new URL(u[0].uri,c.sourceIri).href),c.linkedResources=f.refs.reduce((p,g)=>{var y,w;return(y=p[w=g.rel])!==null&&y!==void 0||(p[w]=[]),p[g.rel].push(new URL(g.uri,c.sourceIri).href),p},c.linkedResources)}const d=n.headers.get("WAC-Allow");return d&&(c.permissions=parseWacAllowHeader(d)),c}function parseWacAllowHeader(n){function e(r){const i=r.split(" ");return i.includes("write")?{read:i.includes("read"),append:!0,write:!0,control:i.includes("control")}:{read:i.includes("read"),append:i.includes("append"),write:!1,control:i.includes("control")}}function t(r,i){const s=r.split(",").map(a=>a.split("=")).filter(a=>a.length===2&&a[0].trim()===i);if(s.length!==1)return"";const o=s[0][1].trim();return o.charAt(0)!=='"'||o.charAt(o.length-1)!=='"'?"":o.substring(1,o.length-1)}return{user:e(t(n,"user")),public:e(t(n,"public"))}}function internal_isUnsuccessfulResponse(n){return!n.ok}function internal_isAuthenticationFailureResponse(n){return n.status===401||n.status===403}const ldp={BasicContainer:"http://www.w3.org/ns/ldp#BasicContainer",Resource:"http://www.w3.org/ns/ldp#Resource"};function responseToResourceInfo(n,e={ignoreAuthenticationErrors:!1}){if(internal_isUnsuccessfulResponse(n)&&(!internal_isAuthenticationFailureResponse(n)||!e.ignoreAuthenticationErrors))throw new FetchError(`Fetching the metadata of the Resource at [${n.url}] failed: [${n.status}] [${n.statusText}].`,n);return{internal_resourceInfo:internal_parseResourceInfo(n)}}function getContentType(n){var e;return(e=n.internal_resourceInfo.contentType)!==null&&e!==void 0?e:null}function getSourceUrl(n){return hasResourceInfo(n)?n.internal_resourceInfo.sourceIri:null}class FetchError extends SolidClientError{constructor(e,t,r){super(e),this.response=t,typeof r=="string"?this.httpError=new ClientHttpError(t,r,e):this.httpError=new ClientHttpError(t,"",e)}get statusCode(){return this.response.status}get statusText(){return this.response.statusText}get problemDetails(){return this.httpError.problemDetails}}const getTurtleParser=()=>{const n=[],e=[],t=[];return{onQuad:r=>{n.push(r)},onError:r=>{t.push(r)},onComplete:r=>{e.push(r)},parse:(r,i)=>{getParser(getSourceUrl(i)).parse(r,(s,o)=>{s?t.forEach(a=>a(s)):o?n.forEach(a=>a(o)):e.forEach(a=>a())})}}};function getParser(n){return new N3Parser({format:"text/turtle",baseIRI:n})}async function triplesToTurtle(n,e){const t="text/turtle",r=new N3Writer({format:t,prefixes:e?.prefixes}),i=n.map(a=>DataFactory$1.quad(a.subject,a.predicate,a.object,void 0));return r.addQuads(i),await new Promise((a,c)=>{r.end((l,d)=>{l?c(l):a(d)})})}const localNodeSkolemPrefix="https://inrupt.com/.well-known/sdk-local-node/",{freeze}=Object;function isLocalNodeIri(n){return n.substring(0,localNodeSkolemPrefix.length)===localNodeSkolemPrefix}function getLocalNodeName(n){return n.substring(localNodeSkolemPrefix.length)}function getLocalNodeIri(n){return`${localNodeSkolemPrefix}${n}`}function isBlankNodeId(n){return typeof n=="string"&&n.substring(0,2)==="_:"}function getBlankNodeValue(n){return n.substring(2)}function getBlankNodeId(n){return`_:${n.value}`}const xmlSchemaTypes={boolean:"http://www.w3.org/2001/XMLSchema#boolean",dateTime:"http://www.w3.org/2001/XMLSchema#dateTime",date:"http://www.w3.org/2001/XMLSchema#date",time:"http://www.w3.org/2001/XMLSchema#time",decimal:"http://www.w3.org/2001/XMLSchema#decimal",integer:"http://www.w3.org/2001/XMLSchema#integer",string:"http://www.w3.org/2001/XMLSchema#string",langString:"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"};function serializeBoolean(n){return n?"true":"false"}function deserializeBoolean(n){return n==="true"||n==="1"?!0:n==="false"||n==="0"?!1:null}function serializeTime(n){let e,t;if(n.millisecond&&(n.millisecond<10?e=`00${n.millisecond}`:n.millisecond<100?e=`0${n.millisecond}`:e=n.millisecond),typeof n.timezoneHourOffset=="number"){const r=Math.abs(n.timezoneHourOffset)<10?`0${Math.abs(n.timezoneHourOffset)}`:Math.abs(n.timezoneHourOffset);t=n.timezoneHourOffset>=0?`+${r}`:`-${r}`,n.timezoneMinuteOffset?t=`${t}:${n.timezoneMinuteOffset<10?`0${n.timezoneMinuteOffset}`:n.timezoneMinuteOffset}`:t+=":00"}return`${n.hour<10?`0${n.hour}`:n.hour}:${n.minute<10?`0${n.minute}`:n.minute}:${n.second<10?`0${n.second}`:n.second}${n.millisecond?`.${e}`:""}${t||""}`}function deserializeTime(n){if(!/\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const[t,r]=splitTimeFromTimezone(n),[i,s,o]=t.split(":");let a=Number.parseInt(i,10),c=Number.parseInt(s,10);const[l,d]=o.split("."),f=Number.parseInt(l,10),u=d?Number.parseInt(d,10):void 0;c>=60&&(a+=1,c-=60);const p={hour:a,minute:c,second:f};if(typeof u=="number"&&(p.millisecond=u),typeof r=="string"){const[g,y]=getTimezoneOffsets(r);if(typeof g!="number"||g>24||typeof y!="number"||y>59)return null;p.timezoneHourOffset=g,p.timezoneMinuteOffset=y}return p}function serializeDatetime(n){return n.toISOString()}function deserializeDatetime(n){if(!/-?\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const[t,r]=n.split("T"),[i,s]=t.charAt(0)==="-"?[-1,t.substring(1)]:[1,t],[o,a,c]=s.split("-"),l=Number.parseInt(o,10)*i,d=Number.parseInt(a,10)-1,f=Number.parseInt(c,10),[u,p]=splitTimeFromTimezone(r),[g,y]=typeof p=="string"?getTimezoneOffsets(p):[0,0],[w,_,R]=u.split(":"),b=Number.parseInt(w,10)+g,C=Number.parseInt(_,10)+y,[P,H]=R.split("."),M=Number.parseInt(P,10),re=H?Number.parseInt(H,10):0,he=new Date(Date.UTC(l,d,f,b,C,M,re));return l>=0&&l<100&&he.setUTCFullYear(he.getUTCFullYear()-1900),he}function serializeDate(n){const e=n.getFullYear(),t=n.getMonth()+1,r=n.getDate(),[,i]=splitTimeFromTimezone(n.toISOString());return`${e}-${String(t).padStart(2,"0")}-${String(r).padStart(2,"0")}${i}`}function deserializeDate(n){if(!/-?\d{4,}-\d\d-\d\d(Z|(\+|-)\d\d:\d\d)?/.test(n))return null;const t=n,[r,i]=t.charAt(0)==="-"?[-1,t.substring(1)]:[1,t],[s,o,a]=i.split("-"),c=a.length>2?a.substring(0,2):a,l=Number.parseInt(s,10)*r,d=Number.parseInt(o,10)-1,f=Number.parseInt(c,10),u=12,p=new Date(Date.UTC(l,d,f,u));return l>=0&&l<100&&p.setUTCFullYear(p.getUTCFullYear()-1900),p}function splitTimeFromTimezone(n){if(n.endsWith("Z"))return[n.substring(0,n.length-1),"Z"];const e=n.split("+"),t=n.split("-");return e.length===1&&t.length===1?[e[0],void 0]:e.length>t.length?[e[0],`+${e[1]}`]:[t[0],`-${t[1]}`]}function getTimezoneOffsets(n){if(n==="Z")return[0,0];const e=n.charAt(0)==="+"?1:-1,[t,r]=n.substring(1).split(":"),i=Number.parseInt(t,10),s=Number.parseInt(r,10);return[i*e,s*e]}function serializeDecimal(n){return n.toString()}function deserializeDecimal(n){const e=Number.parseFloat(n);return Number.isNaN(e)?null:e}function serializeInteger(n){return n.toString()}function deserializeInteger(n){const e=Number.parseInt(n,10);return Number.isNaN(e)?null:e}function normalizeLocale(n){return n.toLowerCase()}function isNamedNode(n){return isTerm(n)&&n.termType==="NamedNode"}function isLiteral(n){return isTerm(n)&&n.termType==="Literal"}function isTerm(n){return n!==null&&typeof n=="object"&&typeof n.termType=="string"&&typeof n.value=="string"&&typeof n.equals=="function"}function isLocalNode(n){return isNamedNode(n)&&isLocalNodeIri(n.value)}function internal_isValidUrl(n){const e=internal_toIriString(n);if(typeof URL!="function")return!0;try{return new URL(e),!0}catch{return!1}}function resolveIriForLocalNode(n,e){return DataFactory$1.namedNode(resolveLocalIri(getLocalNodeName(n.value),e))}function resolveLocalIri(n,e){if(typeof URL!="function")throw new Error("The URL interface is not available, so an IRI cannot be determined.");const t=new URL(e);return t.hash=n,t.href}function addRdfJsQuadToDataset(n,e){var t;if(!["NamedNode","DefaultGraph"].includes(e.graph.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.graph.termType}] as their Graph node.`);const i=e.graph.termType==="DefaultGraph"?"default":e.graph.value,s=(t=n.graphs[i])!==null&&t!==void 0?t:{};return freeze({...n,graphs:freeze({...n.graphs,[i]:addRdfJsQuadToGraph(s,e)})})}function addRdfJsQuadToGraph(n,e){var t;if(!["NamedNode","BlankNode"].includes(e.subject.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.subject.termType}] as their Subject node.`);const i=e.subject.termType==="BlankNode"?`_:${e.subject.value}`:e.subject.value,s=(t=n[i])!==null&&t!==void 0?t:{type:"Subject",url:i,predicates:{}};return freeze({...n,[i]:addRdfJsQuadToSubject(s,e)})}function addRdfJsQuadToSubject(n,e){return freeze({...n,predicates:addRdfJsQuadToPredicates(n.predicates,e)})}function addRdfJsQuadToPredicates(n,e){var t;if(!["NamedNode"].includes(e.predicate.termType))throw new Error(`Cannot parse Quads with nodes of type [${e.predicate.termType}] as their Predicate node.`);const i=e.predicate.value,s=(t=n[i])!==null&&t!==void 0?t:{};return freeze({...n,[i]:addRdfJsQuadToObjects(s,e)})}function addRdfJsQuadToObjects(n,e){var t,r,i,s,o,a,c,l;if(e.object.termType==="NamedNode"){const d=freeze([...(t=n.namedNodes)!==null&&t!==void 0?t:[],e.object.value]);return freeze({...n,namedNodes:d})}if(e.object.termType==="Literal"){if(e.object.datatype.value===xmlSchemaTypes.langString){const u=e.object.language.toLowerCase(),p=freeze([...(i=(r=n.langStrings)===null||r===void 0?void 0:r[u])!==null&&i!==void 0?i:[],e.object.value]),g=freeze({...(s=n.langStrings)!==null&&s!==void 0?s:{},[u]:p});return freeze({...n,langStrings:g})}const d=freeze([...(a=(o=n.literals)===null||o===void 0?void 0:o[e.object.datatype.value])!==null&&a!==void 0?a:[],e.object.value]),f=freeze({...(c=n.literals)!==null&&c!==void 0?c:{},[e.object.datatype.value]:d});return freeze({...n,literals:f})}if(e.object.termType==="BlankNode"){const d=freeze([...(l=n.blankNodes)!==null&&l!==void 0?l:[],getBlankNodeId(e.object)]);return freeze({...n,blankNodes:d})}throw new Error(`Objects of type [${e.object.termType}] are not supported.`)}function toRdfJsQuads(n,e={}){var t;const r=[],i=(t=e.dataFactory)!==null&&t!==void 0?t:DataFactory$1;return Object.keys(n.graphs).forEach(s=>{const o=n.graphs[s],a=s==="default"?i.defaultGraph():i.namedNode(s);Object.keys(o).forEach(c=>{const{predicates:l}=o[c],d=isBlankNodeId(c)?i.blankNode(getBlankNodeValue(c)):i.namedNode(c);r.push(...subjectToRdfJsQuads(l,d,a,e))})}),r}function subjectToRdfJsQuads(n,e,t,r={}){var i;const s=[],o=(i=r.dataFactory)!==null&&i!==void 0?i:DataFactory$1;return Object.keys(n).forEach(a=>{var c,l,d,f;const u=o.namedNode(a),p=(c=n[a].langStrings)!==null&&c!==void 0?c:{},g=(l=n[a].namedNodes)!==null&&l!==void 0?l:[],y=(d=n[a].literals)!==null&&d!==void 0?d:{},w=(f=n[a].blankNodes)!==null&&f!==void 0?f:[];Object.keys(y).forEach(b=>{const C=o.namedNode(b);y[b].forEach(H=>{const M=o.literal(H,C);s.push(o.quad(e,u,M,t))})}),Object.keys(p).forEach(b=>{p[b].forEach(P=>{const H=o.literal(P,b);s.push(o.quad(e,u,H,t))})}),g.forEach(b=>{const C=o.namedNode(b);s.push(o.quad(e,u,C,t))}),w.forEach(b=>{if(isBlankNodeId(b)){const C=o.blankNode(getBlankNodeValue(b));s.push(o.quad(e,u,C,t))}else{const C=o.blankNode(),P=o.quad(e,u,C,t),H=subjectToRdfJsQuads(b,C,t);s.push(P),s.push(...H)}})}),s}function fromRdfJsDataset(n){const e={graphs:{default:{}},type:"Dataset"};return Array.from(n).reduce((t,r)=>addRdfJsQuadToDataset(t,r),e)}function internal_getReadableValue(n){var e,t,r,i,s,o,a,c;if(isNamedNode(n))return`<${n.value}> (URL)`;if(isLiteral(n)){if(!isNamedNode(n.datatype))return`[${n.value}] (RDF/JS Literal of unknown type)`;let l;switch(n.datatype.value){case xmlSchemaTypes.boolean:return l=(t=(e=deserializeBoolean(n.value))===null||e===void 0?void 0:e.valueOf())!==null&&t!==void 0?t:`Invalid data: \`${n.value}\``,`${l} (boolean)`;case xmlSchemaTypes.dateTime:return l=(i=(r=deserializeDatetime(n.value))===null||r===void 0?void 0:r.toUTCString())!==null&&i!==void 0?i:`Invalid data: \`${n.value}\``,`${l} (datetime)`;case xmlSchemaTypes.decimal:return l=(o=(s=deserializeDecimal(n.value))===null||s===void 0?void 0:s.toString())!==null&&o!==void 0?o:`Invalid data: \`${n.value}\``,`${l} (decimal)`;case xmlSchemaTypes.integer:return l=(c=(a=deserializeInteger(n.value))===null||a===void 0?void 0:a.toString())!==null&&c!==void 0?c:`Invalid data: \`${n.value}\``,`${l} (integer)`;case xmlSchemaTypes.langString:return`"${n.value}" (${n.language} string)`;case xmlSchemaTypes.string:return`"${n.value}" (string)`;default:return`[${n.value}] (RDF/JS Literal of type: \`${n.datatype.value}\`)`}}return n.termType==="BlankNode"?`[${n.value}] (RDF/JS BlankNode)`:n.termType==="Quad"?"??? (nested RDF* Quad)":n.termType==="Variable"?`?${n.value} (RDF/JS Variable)`:n}function internal_throwIfNotThing(n){if(!isThing(n))throw new ThingExpectedError(n)}function internal_addAdditionsToChangeLog(n,e){const t=hasChangelog(n)?n.internal_changeLog:{additions:[],deletions:[]},[r,i]=e.filter(s=>!containsBlankNode(s)).reduce(([s,o],a)=>typeof o.find(l=>l.equals(a))<"u"?[s,o.filter(l=>!l.equals(a))]:[s.concat(a),o],[t.additions,t.deletions]);return freeze({...n,internal_changeLog:{additions:r,deletions:i}})}function internal_addDeletionsToChangeLog(n,e){const t=hasChangelog(n)?n.internal_changeLog:{additions:[],deletions:[]},[r,i]=e.filter(s=>!containsBlankNode(s)).reduce(([s,o],a)=>typeof s.find(l=>l.equals(a))<"u"?[s.filter(l=>!l.equals(a)),o]:[s,o.concat(a)],[t.additions,t.deletions]);return freeze({...n,internal_changeLog:{additions:r,deletions:i}})}function internal_withChangeLog(n){return hasChangelog(n)?n:freeze({...n,internal_changeLog:{additions:[],deletions:[]}})}function containsBlankNode(n){return n.subject.termType==="BlankNode"||n.object.termType==="BlankNode"}function getUrl(n,e){var t,r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e),o=(i=(r=(t=n.predicates[s])===null||t===void 0?void 0:t.namedNodes)===null||r===void 0?void 0:r[0])!==null&&i!==void 0?i:null;return o===null?null:isLocalNodeIri(o)?`#${getLocalNodeName(o)}`:o}function getUrlAll(n,e){var t,r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e);return(i=(r=(t=n.predicates[s])===null||t===void 0?void 0:t.namedNodes)===null||r===void 0?void 0:r.map(o=>isLocalNodeIri(o)?`#${getLocalNodeName(o)}`:o))!==null&&i!==void 0?i:[]}const getIriAll=getUrlAll;function getStringNoLocale(n,e){return internal_throwIfNotThing(n),getLiteralOfType(n,e,xmlSchemaTypes.string)}function getNamedNodeAll(n,e){return getIriAll(n,e).map(r=>DataFactory$1.namedNode(r))}function getLiteralAll(n,e){var t,r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e);let a=[];const c=(r=(t=n.predicates[o])===null||t===void 0?void 0:t.langStrings)!==null&&r!==void 0?r:{},l=Object.keys(c);for(const u of l){const g=c[u].map(y=>DataFactory$1.literal(y,u));a=a.concat(g)}const d=(s=(i=n.predicates[o])===null||i===void 0?void 0:i.literals)!==null&&s!==void 0?s:{},f=Object.keys(d);for(const u of f){const p=d[u],g=DataFactory$1.namedNode(u),y=p.map(w=>DataFactory$1.literal(w,g));a=a.concat(y)}return a}function getTermAll(n,e){var t,r;internal_throwIfNotThing(n);const i=getNamedNodeAll(n,e),s=getLiteralAll(n,e),o=internal_toIriString(e),c=((r=(t=n.predicates[o])===null||t===void 0?void 0:t.blankNodes)!==null&&r!==void 0?r:[]).map(d=>{const f=isBlankNodeId(d)?getBlankNodeValue(d):void 0;return DataFactory$1.blankNode(f)});return i.concat(s).concat(c)}function getLiteralOfType(n,e,t){var r,i,s,o;if(!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e);return(o=(s=(i=(r=n.predicates[a])===null||r===void 0?void 0:r.literals)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[0])!==null&&o!==void 0?o:null}function getThing(n,e,t={}){var r;if(!internal_isValidUrl(e)&&!e.match(/^_:/))throw new ValidThingUrlExpectedError(e);const i=typeof t.scope<"u"?internal_toIriString(t.scope):"default",s=(r=n.graphs[i])!==null&&r!==void 0?r:{},o=internal_toIriString(e),a=isLocalNodeIri(o)&&hasServerResourceInfo(n)?resolveLocalIri(getLocalNodeName(o),getSourceUrl(n)):o,c=s[a];return typeof c>"u"?null:c}function getThingAll(n,e={acceptBlankNodes:!1}){var t;const r=typeof e.scope<"u"?internal_toIriString(e.scope):"default",i=(t=n.graphs[r])!==null&&t!==void 0?t:{};return Object.values(i).filter(s=>!isBlankNodeId(s.url)||e.acceptBlankNodes)}function setThing(n,e){var t;const r=isThingLocal(e)&&hasServerResourceInfo(n)?resolveLocalIri(getLocalNodeName(e.url),getSourceUrl(n)):e.url,i=n.graphs.default,s=freeze({...i,[r]:freeze({...e,url:r})}),o=freeze({...n.graphs,default:s}),a=DataFactory$1.namedNode(r),c=(t=n.graphs.default[r])===null||t===void 0?void 0:t.predicates,l=typeof c<"u"?subjectToRdfJsQuads(c,a,DataFactory$1.defaultGraph()):[],d=subjectToRdfJsQuads(e.predicates,a,DataFactory$1.defaultGraph());return internal_addAdditionsToChangeLog(internal_addDeletionsToChangeLog(freeze({...n,graphs:o}),l),d)}function createThing(n={}){var e;if(typeof n.url<"u"){const{url:s}=n;if(!internal_isValidUrl(s))throw new ValidThingUrlExpectedError(s);return freeze({type:"Subject",predicates:freeze({}),url:s})}const t=(e=n.name)!==null&&e!==void 0?e:generateName(),r=getLocalNodeIri(t);return freeze({type:"Subject",predicates:freeze({}),url:r})}function isThing(n){return typeof n=="object"&&n!==null&&typeof n.type=="string"&&n.type==="Subject"}function asUrl(n,e){if(isThingLocal(n)){if(typeof e>"u")throw new Error("The URL of a Thing that has not been persisted cannot be determined without a base URL.");return resolveLocalIri(getLocalNodeName(n.url),e)}return n.url}const asIri=asUrl;function thingAsMarkdown(n){let e="";isThingLocal(n)?e+=`## Thing (no URL yet — identifier: \`#${getLocalNodeName(n.url)}\`)
76
+ `:e+=`## Thing: ${n.url}
77
+ `;const t=Object.keys(n.predicates);if(t.length===0)e+=`
78
+ <empty>
79
+ `;else for(const r of t){e+=`
80
+ Property: ${r}
81
+ `;const i=getTermAll(n,r);e+=i.reduce((s,o)=>`${s}- ${internal_getReadableValue(o)}
82
+ `,"")}return e}function isThingLocal(n){return isLocalNodeIri(n.url)}class ThingExpectedError extends SolidClientError{constructor(e){const t=`Expected a Thing, but received: [${e}].`;super(t),this.receivedValue=e}}class ValidPropertyUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL to identify a property, but received: [${t}].`;super(r),this.receivedProperty=t}}class ValidValueUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL value, but received: [${t}].`;super(r),this.receivedValue=t}}class ValidThingUrlExpectedError extends SolidClientError{constructor(e){const t=isNamedNode(e)?e.value:e,r=`Expected a valid URL to identify a Thing, but received: [${t}].`;super(r),this.receivedValue=t}}const generateName=()=>v4();function normalizeServerSideIri(n){const e=new URL(n);return e.hash="",e.href}function createSolidDataset(){return freeze({type:"Dataset",graphs:{default:{}}})}async function responseToSolidDataset(n,e={}){if(internal_isUnsuccessfulResponse(n)){const d=await n.clone().text();throw new FetchError(`Fetching the SolidDataset at [${n.url}] failed: [${n.status}] [${n.statusText}] ${d}.`,n,d)}const t=responseToResourceInfo(n),r={"text/turtle":getTurtleParser(),...e.parsers},i=getContentType(t);if(i===null)throw new Error(`Could not determine the content type of the Resource at [${getSourceUrl(t)}].`);const s=i.split(";")[0],o=r[s];if(typeof o>"u")throw new Error(`The Resource at [${getSourceUrl(t)}] has a MIME type of [${s}], but the only parsers available are for the following MIME types: [${Object.keys(r).join(", ")}].`);const a=await n.text(),c=await new Promise((d,f)=>{const u=new N3Store;o.onError(p=>{f(new Error(`Encountered an error parsing the Resource at [${getSourceUrl(t)}] with content type [${i}]: ${p}`))}),o.onQuad(p=>{u.add(p)}),o.onComplete(()=>{d(u)}),o.parse(a,t)}),l=freeze(fromRdfJsDataset(c));return freeze({...l,...t})}async function getSolidDataset(n,e){var t,r;const i=normalizeUrl(internal_toIriString(n)),s=Object.keys((t=e?.parsers)!==null&&t!==void 0?t:{}),o=s.length>0?s.join(", "):"text/turtle",a=await((r=e?.fetch)!==null&&r!==void 0?r:fetch)(i,{headers:{Accept:o}});if(internal_isUnsuccessfulResponse(a)){const l=await a.clone().text();throw new FetchError(`Fetching the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${l}.`,a,l)}return await responseToSolidDataset(a,e)}async function prepareSolidDatasetUpdate(n){const e=n.internal_changeLog.deletions.length>0?`DELETE DATA {${(await triplesToTurtle(n.internal_changeLog.deletions.map(getNamedNodesForLocalNodes))).trim()}};`:"",t=n.internal_changeLog.additions.length>0?`INSERT DATA {${(await triplesToTurtle(n.internal_changeLog.additions.map(getNamedNodesForLocalNodes))).trim()}};`:"";return{method:"PATCH",body:`${e} ${t}`,headers:{"Content-Type":"application/sparql-update"}}}async function prepareSolidDatasetCreation(n,e){return{method:"PUT",body:await triplesToTurtle(toRdfJsQuads(n).map(getNamedNodesForLocalNodes),e),headers:{"Content-Type":"text/turtle","If-None-Match":"*",Link:`<${ldp.Resource}>; rel="type"`}}}async function saveSolidDatasetAt(n,e,t){var r;const i=normalizeUrl(internal_toIriString(n)),s=internal_withChangeLog(e),o=isUpdate(s,i)?await prepareSolidDatasetUpdate(s):await prepareSolidDatasetCreation(s,t),a=await((r=t?.fetch)!==null&&r!==void 0?r:fetch)(i,o);if(internal_isUnsuccessfulResponse(a)){const f=isUpdate(s,i)?`The changes that were sent to the Pod are listed below.
83
+
84
+ ${changeLogAsMarkdown(s)}`:`The SolidDataset that was sent to the Pod is listed below.
85
+
86
+ ${solidDatasetAsMarkdown(s)}`,u=await a.clone().text();throw new FetchError(`Storing the Resource at [${i}] failed: [${a.status}] [${a.statusText}] ${u}.
87
+
88
+ ${f}`,a,u)}const c={...internal_parseResourceInfo(a),isRawData:!1},l=freeze({...e,internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:c});return resolveLocalIrisInSolidDataset(l)}async function createContainerAt(n,e={}){var t,r;const i=normalizeUrl(internal_toIriString(n),{trailingSlash:!0}),s=await((t=e.fetch)!==null&&t!==void 0?t:fetch)(i,{method:"PUT",body:e.initialContent?await triplesToTurtle(toRdfJsQuads(e.initialContent).map(getNamedNodesForLocalNodes)):void 0,headers:{Accept:"text/turtle","Content-Type":"text/turtle","If-None-Match":"*",Link:`<${ldp.BasicContainer}>; rel="type"`}});if(internal_isUnsuccessfulResponse(s)){const c=e.initialContent===void 0?"empty":"non-empty",l=await s.clone().text();throw new FetchError(`Creating the ${c} Container at [${n}] failed: [${s.status}] [${s.statusText}] ${l}.`,s,l)}const o=internal_parseResourceInfo(s);return freeze({...(r=e.initialContent)!==null&&r!==void 0?r:createSolidDataset(),internal_changeLog:{additions:[],deletions:[]},internal_resourceInfo:o})}function isSourceIriEqualTo(n,e){return normalizeServerSideIri(n.internal_resourceInfo.sourceIri)===normalizeServerSideIri(e)}function isUpdate(n,e){return hasChangelog(n)&&hasResourceInfo(n)&&typeof n.internal_resourceInfo.sourceIri=="string"&&isSourceIriEqualTo(n,e)}function solidDatasetAsMarkdown(n){let e="";hasResourceInfo(n)?e+=`# SolidDataset: ${getSourceUrl(n)}
89
+ `:e+=`# SolidDataset (no URL yet)
90
+ `;const t=getThingAll(n);return t.length===0?e+=`
91
+ <empty>
92
+ `:t.forEach(r=>{e+=`
93
+ ${thingAsMarkdown(r)}`,hasChangelog(n)&&(e+=`
94
+ ${getReadableChangeLogSummary(n,r)}
95
+ `)}),e}function changeLogAsMarkdown(n){if(!hasResourceInfo(n))return"This is a newly initialized SolidDataset, so there is no source to compare it to.";if(!hasChangelog(n)||n.internal_changeLog.additions.length===0&&n.internal_changeLog.deletions.length===0)return`## Changes compared to ${getSourceUrl(n)}
96
+
97
+ This SolidDataset has not been modified since it was fetched from ${getSourceUrl(n)}.
98
+ `;let e=`## Changes compared to ${getSourceUrl(n)}
99
+ `;const t=sortChangeLogByThingAndProperty(n);return Object.keys(t).forEach(r=>{e+=`
100
+ ### Thing: ${r}
101
+ `;const i=t[r];Object.keys(i).forEach(s=>{e+=`
102
+ Property: ${s}
103
+ `;const{deleted:o}=i[s],{added:a}=i[s];o.length>0&&(e+=`- Removed:
104
+ `,e+=o.reduce((c,l)=>`${c} - ${internal_getReadableValue(l)}
105
+ `,"")),a.length>0&&(e+=`- Added:
106
+ `,e+=a.reduce((c,l)=>`${c} - ${internal_getReadableValue(l)}
107
+ `,""))})}),e}function sortChangeLogByThingAndProperty(n){const e=Object.create(null);return n.internal_changeLog.deletions.forEach(t=>{var r,i,s;const o=isLocalNode(t.subject)?resolveIriForLocalNode(t.subject,getSourceUrl(n)):t.subject;if(!isNamedNode(o)||!isNamedNode(t.predicate))return;const a=internal_toIriString(o),c=internal_toIriString(t.predicate);(r=e[a])!==null&&r!==void 0||(e[a]=Object.create(null)),(i=(s=e[a])[c])!==null&&i!==void 0||(s[c]={added:[],deleted:[]}),e[a][c].deleted.push(t.object)}),n.internal_changeLog.additions.forEach(t=>{var r,i,s;const o=isLocalNode(t.subject)?resolveIriForLocalNode(t.subject,getSourceUrl(n)):t.subject;if(!isNamedNode(o)||!isNamedNode(t.predicate))return;const a=internal_toIriString(o),c=internal_toIriString(t.predicate);(r=e[a])!==null&&r!==void 0||(e[a]=Object.create(null)),(i=(s=e[a])[c])!==null&&i!==void 0||(s[c]={added:[],deleted:[]}),e[a][c].added.push(t.object)}),e}function getReadableChangeLogSummary(n,e){const t=DataFactory$1.namedNode(e.url),r=n.internal_changeLog.additions.reduce((a,c)=>c.subject.equals(t)?a+1:a,0),i=n.internal_changeLog.deletions.reduce((a,c)=>c.subject.equals(t)?a+1:a,0),s=r===1?"1 new value added":`${r} new values added`,o=i===1?"1 value removed":`${i} values removed`;return`(${s} / ${o})`}function getNamedNodesForLocalNodes(n){const e=isNamedNode(n.subject)?getNamedNodeFromLocalNode(n.subject):n.subject,t=isNamedNode(n.object)?getNamedNodeFromLocalNode(n.object):n.object;return DataFactory$1.quad(e,n.predicate,t,n.graph)}function getNamedNodeFromLocalNode(n){return isLocalNodeIri(n.value)?DataFactory$1.namedNode(`#${getLocalNodeName(n.value)}`):n}function resolveLocalIrisInSolidDataset(n){const e=getSourceUrl(n),t=n.graphs.default,i=Object.keys(t).reduce((o,a)=>{const c=resolveLocalIrisInThing(o[a],e),l=isLocalNodeIri(a)?`${e}#${getLocalNodeName(a)}`:a,d={...o};return delete d[a],d[l]=c,freeze(d)},t),s=freeze({...n.graphs,default:i});return freeze({...n,graphs:s})}function resolveLocalIrisInThing(n,e){const r=Object.keys(n.predicates).reduce((i,s)=>{var o;const a=(o=i[s].namedNodes)!==null&&o!==void 0?o:[];if(a.every(d=>!isLocalNodeIri(d)))return i;const c=freeze(a.map(d=>isLocalNodeIri(d)?`${e}#${getLocalNodeName(d)}`:d)),l=freeze({...i[s],namedNodes:c});return freeze({...i,[s]:l})},n.predicates);return freeze({...n,predicates:r,url:isLocalNodeIri(n.url)?`${e}#${getLocalNodeName(n.url)}`:n.url})}const addUrl=(n,e,t)=>{var r,i;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);const s=internal_toIriString(e),o=(r=n.predicates[s])!==null&&r!==void 0?r:{},a=(i=o.namedNodes)!==null&&i!==void 0?i:[];let c;isNamedNode(t)?c=t.value:typeof t=="string"?c=t:isThingLocal(t)?c=t.url:c=asIri(t);const l=freeze(a.concat(internal_toIriString(c))),d=freeze({...o,namedNodes:l}),f=freeze({...n.predicates,[s]:d});return freeze({...n,predicates:f})},addIri=addUrl,addBoolean=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeBoolean(t),xmlSchemaTypes.boolean)),addDatetime=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDatetime(t),xmlSchemaTypes.dateTime)),addDate=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDate(t),xmlSchemaTypes.date)),addTime=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeTime(t),xmlSchemaTypes.time)),addDecimal=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeDecimal(t),xmlSchemaTypes.decimal)),addInteger=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,serializeInteger(t),xmlSchemaTypes.integer));function addStringWithLocale(n,e,t,r){var i,s,o;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),c=normalizeLocale(r),l=(i=n.predicates[a])!==null&&i!==void 0?i:{},d=(s=l.langStrings)!==null&&s!==void 0?s:{},f=(o=d[c])!==null&&o!==void 0?o:[],u=freeze(f.concat(t)),p=freeze({...d,[c]:u}),g=freeze({...l,langStrings:p}),y=freeze({...n.predicates,[a]:g});return freeze({...n,predicates:y})}const addStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),addLiteralOfType(n,e,t,xmlSchemaTypes.string));function addNamedNode(n,e,t){return addUrl(n,e,t.value)}function addLiteral(n,e,t){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);return t.datatype.value===xmlSchemaTypes.langString?addStringWithLocale(n,e,t.value,t.language):addLiteralOfType(n,e,t.value,t.datatype.value)}function addTerm(n,e,t){var r,i;if(t.termType==="NamedNode")return addNamedNode(n,e,t);if(t.termType==="Literal")return addLiteral(n,e,t);if(t.termType==="BlankNode"){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const s=internal_toIriString(e),o=(r=n.predicates[s])!==null&&r!==void 0?r:{},a=(i=o.blankNodes)!==null&&i!==void 0?i:[],c=freeze(a.concat(getBlankNodeId(t))),l=freeze({...o,blankNodes:c}),d=freeze({...n.predicates,[s]:l});return freeze({...n,predicates:d})}throw new Error(`Term type [${t.termType}] is not supported by @inrupt/solid-client.`)}function addLiteralOfType(n,e,t,r){var i,s,o;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),c=(i=n.predicates[a])!==null&&i!==void 0?i:{},l=(s=c.literals)!==null&&s!==void 0?s:{},d=(o=l[r])!==null&&o!==void 0?o:[],f=freeze(d.concat(t)),u=freeze({...l,[r]:f}),p=freeze({...c,literals:u}),g=freeze({...n.predicates,[a]:p});return freeze({...n,predicates:g})}function removeAll(n,e){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const t=internal_toIriString(e),r={...n.predicates};return delete r[t],freeze({...n,predicates:freeze(r)})}const removeUrl=(n,e,t)=>{var r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);const a=isThing(t)?asIri(t):internal_toIriString(t),c=freeze((s=(i=(r=n.predicates[o])===null||r===void 0?void 0:r.namedNodes)===null||i===void 0?void 0:i.filter(f=>f.toLowerCase()!==a.toLowerCase()))!==null&&s!==void 0?s:[]),l=freeze({...n.predicates[o],namedNodes:c}),d=freeze({...n.predicates,[o]:l});return freeze({...n,predicates:d})},removeIri=removeUrl,removeBoolean=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.boolean,r=>deserializeBoolean(r)===t)),removeDatetime=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.dateTime,r=>{var i;return((i=deserializeDatetime(r))===null||i===void 0?void 0:i.getTime())===t.getTime()})),removeDate=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.date,function(r){const i=deserializeDate(r);return i?i.getFullYear()===t.getFullYear()&&i.getMonth()===t.getMonth()&&i.getUTCDate()===t.getUTCDate():!1})),removeTime=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.time,function(r){const i=deserializeTime(r);return i?i.hour===t.hour&&i.minute===t.minute&&i.second===t.second&&i.millisecond===t.millisecond&&i.timezoneHourOffset===t.timezoneHourOffset&&i.timezoneMinuteOffset===t.timezoneMinuteOffset:!1})),removeDecimal=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.decimal,r=>deserializeDecimal(r)===t)),removeInteger=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.integer,r=>deserializeInteger(r)===t));function removeStringWithLocale(n,e,t,r){var i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=internal_toIriString(e),a=(s=(i=n.predicates[o])===null||i===void 0?void 0:i.langStrings)!==null&&s!==void 0?s:{},c=Object.keys(a).find(g=>normalizeLocale(g)===normalizeLocale(r)&&Array.isArray(a[g])&&a[g].length>0);if(typeof c!="string")return n;const l=a[c],d=freeze(l.filter(g=>g!==t)),f=freeze({...a,[c]:d}),u=freeze({...n.predicates[o],langStrings:f}),p=freeze({...n.predicates,[o]:u});return freeze({...n,predicates:p})}const removeStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),removeLiteralMatching(n,e,xmlSchemaTypes.string,r=>r===t));function removeNamedNode(n,e,t){return removeUrl(n,e,t.value)}function removeLiteral(n,e,t){var r,i,s;if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const o=t.datatype.value;if(o===xmlSchemaTypes.langString)return removeStringWithLocale(n,e,t.value,t.language);const a=internal_toIriString(e),c=(r=n.predicates[a])!==null&&r!==void 0?r:{},l=(i=c.literals)!==null&&i!==void 0?i:{},d=(s=l[o])!==null&&s!==void 0?s:[],f=freeze(d.filter(w=>w!==t.value)),u=freeze({...l,[o]:f}),p=freeze({...c,literals:u}),g=freeze({...n.predicates,[a]:p});return freeze({...n,predicates:g})}function removeLiteralMatching(n,e,t,r){var i,s,o;if(!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);const a=internal_toIriString(e),c=(i=n.predicates[a])!==null&&i!==void 0?i:{},l=(s=c.literals)!==null&&s!==void 0?s:{},d=(o=l[t])!==null&&o!==void 0?o:[],f=freeze(d.filter(w=>!r(w))),u=freeze({...l,[t]:f}),p=freeze({...c,literals:u}),g=freeze({...n.predicates,[a]:p});return freeze({...n,predicates:g})}const setUrl=(n,e,t)=>{if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);if(!isThing(t)&&!internal_isValidUrl(t))throw new ValidValueUrlExpectedError(t);return addUrl(removeAll(n,e),e,t)},setIri=setUrl,setBoolean=(n,e,t)=>(internal_throwIfNotThing(n),addBoolean(removeAll(n,e),e,t)),setDatetime=(n,e,t)=>(internal_throwIfNotThing(n),addDatetime(removeAll(n,e),e,t)),setDate=(n,e,t)=>(internal_throwIfNotThing(n),addDate(removeAll(n,e),e,t)),setTime=(n,e,t)=>(internal_throwIfNotThing(n),addTime(removeAll(n,e),e,t)),setDecimal=(n,e,t)=>(internal_throwIfNotThing(n),addDecimal(removeAll(n,e),e,t)),setInteger=(n,e,t)=>(internal_throwIfNotThing(n),addInteger(removeAll(n,e),e,t));function setStringWithLocale(n,e,t,r){return internal_throwIfNotThing(n),addStringWithLocale(removeAll(n,e),e,t,r)}const setStringNoLocale=(n,e,t)=>(internal_throwIfNotThing(n),addStringNoLocale(removeAll(n,e),e,t));function setNamedNode(n,e,t){return internal_throwIfNotThing(n),addNamedNode(removeAll(n,e),e,t)}function setLiteral(n,e,t){return internal_throwIfNotThing(n),addLiteral(removeAll(n,e),e,t)}function setTerm(n,e,t){if(internal_throwIfNotThing(n),!internal_isValidUrl(e))throw new ValidPropertyUrlExpectedError(e);return addTerm(removeAll(n,e),e,t)}function buildThing(n=createThing()){let e=isThing(n)?n:createThing(n);function t(o){return(a,c)=>(e=o(e,a,c),s)}function r(o){return(a,c)=>(e=o(e,a,c),s)}function i(o){return(a,c)=>(e=o(e,a,c),s)}const s={build:()=>e,addUrl:t(addUrl),addIri:t(addIri),addBoolean:t(addBoolean),addDatetime:t(addDatetime),addDate:t(addDate),addTime:t(addTime),addDecimal:t(addDecimal),addInteger:t(addInteger),addStringNoLocale:t(addStringNoLocale),addStringEnglish:(o,a)=>(e=addStringWithLocale(e,o,a,"en"),s),addStringWithLocale:(o,a,c)=>(e=addStringWithLocale(e,o,a,c),s),addNamedNode:t(addNamedNode),addLiteral:t(addLiteral),addTerm:t(addTerm),setUrl:r(setUrl),setIri:r(setIri),setBoolean:r(setBoolean),setDatetime:r(setDatetime),setDate:r(setDate),setTime:r(setTime),setDecimal:r(setDecimal),setInteger:r(setInteger),setStringNoLocale:r(setStringNoLocale),setStringEnglish:(o,a)=>(e=setStringWithLocale(e,o,a,"en"),s),setStringWithLocale:(o,a,c)=>(e=setStringWithLocale(e,o,a,c),s),setNamedNode:r(setNamedNode),setLiteral:r(setLiteral),setTerm:r(setTerm),removeAll:o=>(e=removeAll(e,o),s),removeUrl:i(removeUrl),removeIri:i(removeIri),removeBoolean:i(removeBoolean),removeDatetime:i(removeDatetime),removeDate:i(removeDate),removeTime:i(removeTime),removeDecimal:i(removeDecimal),removeInteger:i(removeInteger),removeStringNoLocale:i(removeStringNoLocale),removeStringEnglish:(o,a)=>buildThing(removeStringWithLocale(e,o,a,"en")),removeStringWithLocale:(o,a,c)=>buildThing(removeStringWithLocale(e,o,a,c)),removeNamedNode:i(removeNamedNode),removeLiteral:i(removeLiteral)};return s}const normalizeRdfClass=n=>n&&(n.startsWith("http://schema.org/")?n.replace("http://schema.org/","https://schema.org/"):n);class InteropDiscovery{constructor(e,t,r){this.webId=e,this.fetchFn=t,this.clientId=r,this.shapeTreeCache=new Map}async ensureRegistrySet(e,t,r){if(!r?.registryPath)throw new Error("Missing registryPath for SAI registry auto-creation.");const i=r.registryPath.endsWith("/")?r.registryPath:`${r.registryPath}/`,s=i.replace(/[^/]+\/$/,""),o=`${i}agents/`,a=`${i}set.ttl`,l=`${a}#set-drizzle-solid`,d=`${i}data-registry.ttl`,u=`${d}#data-registry`;try{s&&s!==i&&await createContainerAt(s,{fetch:this.fetchFn}),await createContainerAt(i,{fetch:this.fetchFn})}catch{}try{await createContainerAt(o,{fetch:this.fetchFn})}catch{}const p=setUrl(createThing({url:u}),"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.DataRegistry);let g;try{g=await getSolidDataset(d,{fetch:this.fetchFn})}catch{g=void 0}if(g){if(!getThing(g,u)){const P=setThing(g,p);await saveSolidDatasetAt(d,P,{fetch:this.fetchFn})}}else{let C=createSolidDataset();C=setThing(C,p),await saveSolidDatasetAt(d,C,{fetch:this.fetchFn})}let y=createThing({url:l});y=setUrl(y,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.RegistrySet),y=addUrl(y,INTEROP.hasDataRegistry,u),y=addUrl(y,"http://www.w3.org/ns/solid/interop#hasAgentRegistry",o);let w;try{w=await getSolidDataset(a,{fetch:this.fetchFn})}catch{w=void 0}if(w){const C=getThing(w,l);if(C){const P=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),H=getPredicateForColumn(registrySetSchema.columns.hasAgentRegistry,registrySetSchema),M=getUrlAll(C,P),re=getUrlAll(C,H);let he=C;if(M.includes(u)||(he=addUrl(he,P,u)),re.includes(o)||(he=addUrl(he,H,o)),he!==C){const V=setThing(w,he);await saveSolidDatasetAt(a,V,{fetch:this.fetchFn})}}else{const P=setThing(w,y);await saveSolidDatasetAt(a,P,{fetch:this.fetchFn})}}else{let C=createSolidDataset();C=setThing(C,y),await saveSolidDatasetAt(a,C,{fetch:this.fetchFn})}const _=setUrl(t,INTEROP.hasRegistrySet,l),R=setThing(e,_),b=this.webId.split("#")[0];return await saveSolidDatasetAt(b,R,{fetch:this.fetchFn}),l}async register(e,t){if(!t?.registryPath)throw new Error("registryPath is required for SAI registration.");const r=typeof e.config.type=="string"?e.config.type:e.config.type.value,i=normalizeRdfClass(r)??r;try{const s=await getSolidDataset(this.webId,{fetch:this.fetchFn}),o=getThing(s,this.webId);if(!o)throw new Error("Profile not found");let a=getUrl(o,INTEROP.hasRegistrySet),c,l;if(a)try{c=await getSolidDataset(a,{fetch:this.fetchFn}),l=getThing(c,a)}catch{c=void 0,l=void 0}if((!a||!l)&&(a=await this.ensureRegistrySet(s,o,t),c=await getSolidDataset(a,{fetch:this.fetchFn}),l=getThing(c,a),!l))throw new Error("RegistrySet not found");if(!t?.force&&(await this.discover(r)).length>0){console.log(`[InteropDiscovery] ${e.config.name} already registered, skipping`);return}const d=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),f=getUrlAll(l,d);if(f.length===0)throw new Error("No DataRegistry found");const u=f[0],p=t?.containerSlug??e.config.name,g=u.endsWith("/")?u:u+"/",y=`${g}${p}/`;try{await getSolidDataset(y,{fetch:this.fetchFn})}catch{await createContainerAt(y,{fetch:this.fetchFn})}const w=`${g}${p}`,_=`${w}#ShapeTree`;let R=createThing({url:_});R=setUrl(R,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",SHAPETREES.ShapeTree),R=setUrl(R,SHAPETREES.expectsType,i),t?.shapeUrl&&(R=setUrl(R,SHAPETREES.shape,t.shapeUrl));let b=createThing({url:w});b=setUrl(b,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",INTEROP.DataRegistration);const C=this.clientId&&/^https?:\/\//.test(this.clientId)?this.clientId:this.webId;b=setUrl(b,INTEROP.registeredBy,C),b=setDatetime(b,"http://www.w3.org/ns/solid/interop#registeredAt",new Date),b=setUrl(b,INTEROP.registeredShapeTree,_);const P=e.getSubjectTemplate();P&&(b=setStringNoLocale(b,UDFS.subjectTemplate,P));let H;try{H=await getSolidDataset(w,{fetch:this.fetchFn})}catch{H=null}let M=H??createSolidDataset(),re=!1;const he=getThing(M,w);if(!he)M=setThing(M,b),re=!0;else{let ce=he;const Se=getUrl(he,INTEROP.registeredBy),me=getUrl(he,INTEROP.registeredShapeTree),Ne=getStringNoLocale(he,UDFS.subjectTemplate);Se||(ce=setUrl(ce,INTEROP.registeredBy,C)),me||(ce=setUrl(ce,INTEROP.registeredShapeTree,_)),!Ne&&P&&(ce=setStringNoLocale(ce,UDFS.subjectTemplate,P)),ce!==he&&(M=setThing(M,ce),re=!0)}getThing(M,_)||(M=setThing(M,R),re=!0),(!H||re)&&await saveSolidDatasetAt(w,M,{fetch:this.fetchFn});let q=await getSolidDataset(u,{fetch:this.fetchFn}),ie=getThing(q,u);if(!ie)throw new Error("Registry Thing missing in Dataset");const U=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema);ie=addUrl(ie,U,w),q=setThing(q,ie),await saveSolidDatasetAt(u,q,{fetch:this.fetchFn}),this.shapeTreeCache.set(_,{expectsType:i,shape:t?.shapeUrl}),console.log(`[InteropDiscovery] Registered ${e.config.name} at ${w}`),console.log(`[InteropDiscovery] -> ShapeTree: ${_}`),console.log(`[InteropDiscovery] -> expectsType: ${i}`),t?.shapeUrl&&console.log(`[InteropDiscovery] -> Shape: ${t.shapeUrl}`)}catch(s){throw console.error("[InteropDiscovery] Registration failed:",s),s}}async discover(e,t){try{const r=[],i=await getSolidDataset(this.webId,{fetch:this.fetchFn}),s=getThing(i,this.webId);if(!s)return[];const o=getUrlAll(s,INTEROP.hasRegistrySet);if(o.length===0)return[];for(const a of o){const c=await this.discoverDataRegistrationsRaw(a,e,t);r.push(...c);const l=await this.discoverAccessGrantsRaw(a,e,t);r.push(...l)}return this.mergeByContainer(r)}catch(r){return console.error("[InteropDiscovery] Discovery failed:",r),[]}}mergeByContainer(e){const t=new Map;for(const r of e){const i=t.get(r.container),s=r.shape?{url:r.shape,shapeTree:r.shapeTree,registeredBy:r.registeredBy,source:r.source}:void 0;i?(s&&!i.shapes.some(o=>o.url===s.url)&&i.shapes.push(s),!i.subjectTemplate&&r.subjectTemplate&&(i.subjectTemplate=r.subjectTemplate)):t.set(r.container,{container:r.container,subjectTemplate:r.subjectTemplate,shapes:s?[s]:[],source:r.source})}return Array.from(t.values())}async discoverDataRegistrationsRaw(e,t,r){const i=[],s=normalizeRdfClass(t)??t;try{const o=await getSolidDataset(e,{fetch:this.fetchFn}),a=getThing(o,e);if(!a)return[];const c=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),l=getUrlAll(a,c);for(const d of l)try{const f=await getSolidDataset(d,{fetch:this.fetchFn}),u=getThing(f,d);if(!u)continue;const p=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema),g=getUrlAll(u,p);for(const y of g){const w=await getSolidDataset(y,{fetch:this.fetchFn}),_=getThing(w,y);if(!_)continue;const R=getPredicateForColumn(dataRegistrationSchema.columns.registeredShapeTree,dataRegistrationSchema),b=getUrl(_,R);if(!b)continue;const C=getPredicateForColumn(dataRegistrationSchema.columns.registeredBy,dataRegistrationSchema),P=getUrl(_,C),H=getStringNoLocale(_,UDFS.subjectTemplate)??void 0;if(r?.appId&&P!==r.appId)continue;const M=await this.resolveShapeTree(b);normalizeRdfClass(M?.expectsType)===s&&i.push({container:y,source:"interop",subjectTemplate:H,shapeTree:b,shape:M?.shape,registeredBy:P??void 0})}}catch(f){console.warn(`[InteropDiscovery] Error checking registry ${d}:`,f)}}catch(o){console.warn(`[InteropDiscovery] Error exploring RegistrySet ${e}:`,o)}return i}async discoverAccessGrantsRaw(e,t,r){if(!this.clientId)return console.warn("[InteropDiscovery] No ClientID available, skipping Access Grant discovery"),[];const i=[],s=normalizeRdfClass(t)??t;try{const o=await getSolidDataset(e,{fetch:this.fetchFn}),a=getThing(o,e);if(!a)return console.warn(`[InteropDiscovery] RegistrySet Thing not found at ${e}`),[];const c=getPredicateForColumn(registrySetSchema.columns.hasAgentRegistry,registrySetSchema),l=getUrlAll(a,c);for(const d of l)try{const f=await getSolidDataset(d,{fetch:this.fetchFn}),u=getThing(f,d);if(!u)continue;const g=getUrlAll(u,"http://www.w3.org/ns/solid/interop#hasApplicationRegistration"),y=getUrlAll(u,"http://www.w3.org/ns/ldp#contains"),w=Array.from(new Set([...g,...y]));for(const _ of w)try{const R=await getSolidDataset(_,{fetch:this.fetchFn}),b=getThingAll(R);for(const C of b){const P=getPredicateForColumn(applicationRegistrationSchema.columns.registeredAgent,applicationRegistrationSchema);if(getUrl(C,P)===this.clientId){const M=getPredicateForColumn(applicationRegistrationSchema.columns.hasAccessGrant,applicationRegistrationSchema),re=getUrlAll(C,M);for(const he of re){let V=getThing(R,he);if(!V){const U=await getSolidDataset(he,{fetch:this.fetchFn}).catch(()=>null);U&&(V=getThing(U,he))}if(!V)continue;const q=getPredicateForColumn(accessGrantSchema.columns.hasDataGrant,accessGrantSchema),ie=getUrlAll(V,q);for(const U of ie){let ce=getThing(R,U);if(!ce){const O=await getSolidDataset(U,{fetch:this.fetchFn}).catch(()=>null);O&&(ce=getThing(O,U))}if(!ce)continue;const Se=getPredicateForColumn(dataGrantSchema.columns.registeredShapeTree,dataGrantSchema),me=getUrl(ce,Se);if(!me)continue;const Ne=getPredicateForColumn(dataGrantSchema.columns.dataOwner,dataGrantSchema),te=getUrl(ce,Ne);if(r?.appId&&te!==r.appId)continue;const ae=await this.resolveShapeTree(me);if(normalizeRdfClass(ae?.expectsType)===s){const O=getPredicateForColumn(dataGrantSchema.columns.hasDataRegistration,dataGrantSchema),se=getUrl(ce,O);console.log(`[InteropDiscovery] Found matching Data Grant: ${U}`),console.log(`[InteropDiscovery] -> ShapeTree: ${me}`),console.log(`[InteropDiscovery] -> Shape: ${ae?.shape}`),console.log(`[InteropDiscovery] -> Data Registration: ${se}`),se&&i.push({container:se,source:"interop",shapeTree:me,shape:ae?.shape,registeredBy:te??void 0})}else console.log(`[InteropDiscovery] ShapeTree mismatch: ${me} vs ${t}`)}}}}}catch{}}catch(f){console.warn(`[InteropDiscovery] Error checking AgentRegistry ${d}:`,f)}}catch(o){console.warn("[InteropDiscovery] Error in AccessGrant discovery:",o)}return i}async isRegistered(e){return(await this.discover(e)).length>0}async discoverByApp(e){try{const i=(await this.discoverAll()).filter(s=>s.registeredBy===e).map(s=>({container:s.container,source:"interop",shapeTree:s.shapeTree,shape:s.shape,registeredBy:s.registeredBy}));return this.mergeByContainer(i)}catch(t){return console.error("[InteropDiscovery] discoverByApp failed:",t),[]}}async discoverAll(){const e=[];try{const t=await getSolidDataset(this.webId,{fetch:this.fetchFn}),r=getThing(t,this.webId);if(!r)return[];const i=getUrlAll(r,INTEROP.hasRegistrySet);for(const s of i)try{const o=await getSolidDataset(s,{fetch:this.fetchFn}),a=getThing(o,s);if(!a)continue;const c=getPredicateForColumn(registrySetSchema.columns.hasDataRegistry,registrySetSchema),l=getUrlAll(a,c);for(const d of l)try{const f=await getSolidDataset(d,{fetch:this.fetchFn}),u=getThing(f,d);if(!u)continue;const p=getPredicateForColumn(dataRegistrySchema.columns.hasDataRegistration,dataRegistrySchema),g=getUrlAll(u,p);for(const y of g)try{const w=await getSolidDataset(y,{fetch:this.fetchFn}),_=getThing(w,y);if(!_)continue;const R=getPredicateForColumn(dataRegistrationSchema.columns.registeredShapeTree,dataRegistrationSchema),b=getUrl(_,R);if(!b)continue;const C=getPredicateForColumn(dataRegistrationSchema.columns.registeredBy,dataRegistrationSchema),P=getUrl(_,C),H=getPredicateForColumn(dataRegistrationSchema.columns.registeredAt,dataRegistrationSchema),M=getUrl(_,H),re=M?new Date(M):void 0,he=getStringNoLocale(_,UDFS.subjectTemplate)??void 0,V=await this.resolveShapeTree(b);e.push({registrationUrl:y,container:y,rdfClass:V?.expectsType??"",shapeTree:b,shape:V?.shape,subjectTemplate:he,registeredBy:P??void 0,registeredAt:re})}catch(w){console.warn(`[InteropDiscovery] Error reading registration ${y}:`,w)}}catch(f){console.warn(`[InteropDiscovery] Error reading registry ${d}:`,f)}}catch(o){console.warn(`[InteropDiscovery] Error reading RegistrySet ${s}:`,o)}}catch(t){console.error("[InteropDiscovery] discoverAll failed:",t)}return e}async checkShapeTreeMatchesClass(e,t){const r=await this.resolveShapeTree(e);return normalizeRdfClass(r?.expectsType)===(normalizeRdfClass(t)??t)}async resolveShapeTree(e){if(this.shapeTreeCache.has(e))return this.shapeTreeCache.get(e);try{const t=await getSolidDataset(e,{fetch:this.fetchFn}),r=getThing(t,e);if(!r)return this.shapeTreeCache.set(e,{}),null;const i=getUrl(r,SHAPETREES.expectsType)??void 0,s=getUrl(r,SHAPETREES.shape)??void 0,o={expectsType:i,shape:s};return this.shapeTreeCache.set(e,o),o}catch(t){return console.warn(`[InteropDiscovery] Failed to fetch ShapeTree ${e}:`,t),this.shapeTreeCache.set(e,{}),null}}}function mergeLocationsByContainer(n){const e=new Map;for(const t of n){const r=e.get(t.container);if(r)for(const i of t.shapes)r.shapes.some(s=>s.url===i.url)||r.shapes.push(i);else e.set(t.container,{container:t.container,subjectPattern:t.subjectPattern,shapes:[...t.shapes],source:t.source})}return Array.from(e.values())}class CompositeDiscovery{constructor(e){this.strategies=e}async register(e,t){const r=[];let i=!1;for(const s of this.strategies)if(!(s instanceof InteropDiscovery&&!t?.registryPath))try{await s.register(e,t),i=!0}catch(o){r.push(o),console.warn("Registration failed with strategy, trying next:",o)}if(!i){const s=r.length>0?` Errors: ${r.map(String).join("; ")}`:"";throw new Error(`Failed to register table with any discovery strategy.${s}`)}}async discover(e,t){const r=[];for(const i of this.strategies)try{const s=await i.discover(e,t);r.push(...s)}catch(s){console.warn("Discovery failed with strategy, trying next:",s)}return mergeLocationsByContainer(r)}async isRegistered(e){for(const t of this.strategies)if(await t.isRegistered(e))return!0;return!1}async discoverAll(){const e=[];for(const t of this.strategies)if(t.discoverAll)try{const r=await t.discoverAll();e.push(...r)}catch(r){console.warn("discoverAll failed with strategy:",r)}return e}async discoverByApp(e){const t=[];for(const r of this.strategies)if(r.discoverByApp)try{const i=await r.discoverByApp(e);t.push(...i)}catch(i){console.warn("discoverByApp failed with strategy:",i)}return mergeLocationsByContainer(t)}}function getContainerUrl(n){try{const e=new URL(n),t=e.pathname.lastIndexOf("/");return t<0?null:(e.pathname=e.pathname.slice(0,t+1),e.search="",e.hash="",e.toString())}catch{const e=n.lastIndexOf("/");return e>0?n.slice(0,e+1):null}}class LdpExecutor{constructor(e,t,r){this.sparqlExecutor=e,this.fetchFn=t,this.uriResolver=r,this.tripleBuilder=new TripleBuilderImpl(r)}setTableRegistry(e,t){this.tripleBuilder.setTableRegistry(e,t)}setBaseUri(e){this.tripleBuilder.setBaseUri(e)}async executeInsert(e,t,r,i={}){i.tableRegistry&&i.tableNameRegistry&&this.setTableRegistry(i.tableRegistry,i.tableNameRegistry);const s=[];if(e.forEach((f,u)=>{const p=this.uriResolver.resolveSubject(t,f,u);t.__currentRecord=f;try{const g=this.tripleBuilder.buildTypeTriple(p,t.config.type);s.push(...this.tripleBuilder.toN3Strings([g])),Object.entries(t.columns??{}).forEach(([y,w])=>{if(f[y]===void 0||f[y]===null||w._virtualId||(w.options?.predicate||w._predicateUri)==="@id")return;const R=this.tripleBuilder.buildInsert(p,w,f[y],t);s.push(...this.tripleBuilder.toN3Strings(R.triples)),R.childTriples&&R.childTriples.length>0&&s.push(...this.tripleBuilder.toN3Strings(R.childTriples))})}finally{delete t.__currentRecord}}),s.length===0)return[];if(this.uriResolver.getResourceMode(t)==="document"){const f=new Map;for(let p=0;p<e.length;p++){const g=e[p],y=this.uriResolver.resolveSubject(t,g,p);t.__currentRecord=g;try{const w=this.uriResolver.getResourceUrl(y),_=[],R=this.tripleBuilder.buildTypeTriple(y,t.config.type);if(_.push(...this.tripleBuilder.toN3Strings([R])),Object.entries(t.columns??{}).forEach(([C,P])=>{if(g[C]===void 0||g[C]===null||P._virtualId||(P.options?.predicate||P._predicateUri)==="@id")return;const M=this.tripleBuilder.buildInsert(y,P,g[C],t);_.push(...this.tripleBuilder.toN3Strings(M.triples)),M.childTriples&&M.childTriples.length>0&&_.push(...this.tripleBuilder.toN3Strings(M.childTriples))}),_.length===0)continue;const b=f.get(w)||{triples:[],hasFragmentSubject:!1};b.triples.push(..._),b.hasFragmentSubject=b.hasFragmentSubject||y.includes("#"),f.set(w,b)}finally{delete t.__currentRecord}}const u=[];for(const[p,g]of f.entries()){const y=g.triples,w=getContainerUrl(p);w&&i.ensureContainerExists&&await i.ensureContainerExists(w);let _=!1;if(!i.skipResourceExistenceCheck){const P=await this.fetchFn(p,{method:"HEAD"});_=P.ok||P.status===405}let R,b;if(i.skipResourceExistenceCheck){const P=`INSERT DATA {
108
+ ${y.join(`
109
+ `)}
110
+ }`;if(R=await this.fetchFn(p,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:P}),b="patch",R.status===404){const H=y.join(`
111
+ `);R=await this.fetchFn(p,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:H}),b="put",R=await this.repairContainerAndRetryPutIfNeeded(R,w,p,H,"text/turtle",i.repairContainerOnWriteFailure)}}else if(_){const P=`INSERT DATA {
112
+ ${y.join(`
113
+ `)}
114
+ }`;R=await this.fetchFn(p,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:P}),b="patch"}else{const P=y.join(`
115
+ `);R=await this.fetchFn(p,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:P}),b="put"}if(![200,201,202,204,205].includes(R.status)){const P=await R.text().catch(()=>"");throw new Error(`Write failed for ${p}: ${R.status} ${R.statusText}${P?` - ${P}`:""}`)}await this.sparqlExecutor.invalidateHttpCache(p);const C=p.lastIndexOf("/");if(C>0){const P=p.slice(0,C+1);await this.sparqlExecutor.invalidateHttpCache(P)}await this.sparqlExecutor.invalidateHttpCache(void 0).catch(()=>{}),u.push({success:!0,source:p,status:R.status,via:b})}return u}const a=getContainerUrl(r);a&&i.ensureContainerExists&&await i.ensureContainerExists(a);const c=`INSERT DATA {
116
+ ${s.join(`
117
+ `)}
118
+ }`;let l=await this.fetchFn(r,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:c});if((l.status===404||l.status===201)&&(i.skipResourceExistenceCheck?!0:await this.fetchFn(r,{method:"HEAD"}).then(u=>!u.ok&&u.status!==405))){let u=await this.fetchFn(r,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});u=await this.repairContainerAndRetryPutIfNeeded(u,a,r,"","text/turtle",i.repairContainerOnWriteFailure),(u.ok||u.status===409||u.status===201)&&(l=await this.fetchFn(r,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:c}))}if(!l.ok){const f=await l.text().catch(()=>""),u=new Error(`SPARQL UPDATE INSERT failed: ${l.status} ${l.statusText}${f?` - ${f}`:""}`);throw u.status=l.status,u}await this.sparqlExecutor.invalidateHttpCache(r);const d=r.lastIndexOf("/");if(d>0){const f=r.slice(0,d+1);await this.sparqlExecutor.invalidateHttpCache(f)}return await this.sparqlExecutor.invalidateHttpCache(void 0).catch(()=>{}),[{success:!0,source:r,status:l.status,via:"sparql-update"}]}async repairContainerAndRetryPutIfNeeded(e,t,r,i,s,o){return!o||!t||!this.isMissingParentContainerResponse(e)?e:(await o(t),await this.fetchFn(r,{method:"PUT",headers:{"Content-Type":s},body:i}))}isMissingParentContainerResponse(e){return e.status===404||e.status===409}async executeUpdate(e,t,r,i){if(!r.length)return[];const s=[],o=this.uriResolver.getResourceMode(e);for(const a of r){const c=o==="document"?this.uriResolver.getResourceUrl(a):i,l=await this.buildUpdatePatchPayload(a,e,t,c);if(!l)continue;const{deleteTriples:d,insertTriples:f,deleteWherePatterns:u}=l,p=Object.entries(t).filter(([b,C])=>C!==void 0);for(const[b]of p){if(b==="@id"||b==="subject")continue;const C=e.columns?.[b];if(!C||C._virtualId||C.options?.predicate==="@id"||!(C.dataType==="object"||C.dataType==="json"||C.dataType==="array"&&(C.elementType==="object"||C.options?.baseType==="object")))continue;const H=this.tripleBuilder.getPredicateUri(C,e),M=await this.fetchExistingObjects(c,a,H);for(const re of M){let he=re;if(!he.startsWith("<")&&!he.startsWith("_:")&&(he=`<${he}>`),d.push(`<${a}> <${H}> ${he} .`),he.startsWith("<")){const V=he.slice(1,-1),q=await this.fetchRecursiveTriplesToDelete(V,e,c);d.push(...q)}}}const g=Array.from(new Set(d)),y=Array.from(new Set(f)),w=g.filter(b=>!y.includes(b)),_=y.filter(b=>!g.includes(b));if(w.length===0&&_.length===0)continue;const R=await this.executeN3Patch(c,w,_,[],u);s.push(...R),await new Promise(b=>setTimeout(b,200))}return s}async executeDelete(e,t,r){const i=[],s=this.uriResolver.getResourceMode(t);for(const o of e)try{const a=s==="document"?this.uriResolver.getResourceUrl(o):r,c=await this.fetchRecursiveTriplesToDelete(o,t,a),l=Array.from(new Set(c));if(l.length>0){const d=await this.executeN3Patch(a,l,[],[]);i.push(...d)}}catch(a){throw console.error(`[DELETE] Failed to delete subject ${o}:`,a),a}return i}async retryWithBackoff(e,t=3){let r=null,i;for(let s=0;s<t;s++)try{const o=await e();if(r=o.response,o.result!==void 0)return{response:r,result:o.result};if(o.fallback){const a=await o.fallback();return{response:r,result:a}}if(!o.shouldRetry)break;await new Promise(a=>setTimeout(a,1e3*(s+1)))}catch(o){i=o,s<t-1&&await new Promise(a=>setTimeout(a,1e3*(s+1)))}return{response:r,lastError:i}}async buildPatchError(e,t,r){const i=e?await e.text().catch(()=>""):"",s=e?e.status:"Network Error",o=e?e.statusText:t instanceof Error?t.message:String(t),a=new Error(`${r} failed: ${s} ${o}${i?` - ${i}`:""}`);return a.status=s,a}async buildUpdatePatchPayload(e,t,r,i){const s=[],o=[],a=[];for(const[c,l]of Object.entries(r)){if(l===void 0||c==="@id"||c==="subject")continue;const d=t.columns?.[c];if(!d||d._virtualId||d.options?.predicate==="@id")continue;if(d.dataType==="object"||d.dataType==="json"||d.dataType==="array"&&(d.elementType==="object"||d.options?.baseType==="object")){if(l!==null){const _=this.tripleBuilder.buildInsert(e,d,l,t);o.push(...this.tripleBuilder.toN3Strings(_.triples)),_.childTriples&&o.push(...this.tripleBuilder.toN3Strings(_.childTriples))}continue}const u=this.tripleBuilder.getPredicateUri(d,t),p=!!d.options?.inverse,g=c.replace(/[^a-zA-Z0-9_]/g,"_");if(p){if(a.push(`?s_${g} <${u}> <${e}> .`),(await this.fetchInverseSubjects(i,e,u)).forEach(R=>{let b=R;!b.startsWith("<")&&!b.startsWith("_:")&&(b=`<${b}>`),s.push(`${b} <${u}> <${e}> .`)}),l!==null){const R=this.tripleBuilder.buildInsert(e,d,l,t);o.push(...this.tripleBuilder.toN3Strings(R.triples))}continue}if(a.push(`<${e}> <${u}> ?o_${g} .`),(await this.fetchExistingObjects(i,e,u)).forEach(_=>{s.push(`<${e}> <${u}> ${_} .`)}),l===null)continue;const w=this.tripleBuilder.buildInsert(e,d,l,t);o.push(...this.tripleBuilder.toN3Strings(w.triples))}return{deleteTriples:s,insertTriples:o,deleteWherePatterns:a}}async executeN3Patch(e,t,r,i=[],s=[]){if(t.length===0&&r.length===0&&s.length===0)return[];const o=this.buildSparqlUpdate(t,r,s),{response:a,result:c,lastError:l}=await this.retryWithBackoff(async()=>{const d=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:o});if(d.ok)return await this.sparqlExecutor.invalidateHttpCache(e),{response:d,result:[{success:!0,source:e,status:d.status,via:"sparql-update"}],shouldRetry:!1};if(d.status===415||d.status===405){const u=s.length>0?[...t,...s]:t,p=s.length>0?s:i;return{response:d,shouldRetry:!1,fallback:()=>this.executeN3PatchInternal(e,u,r,p)}}const f=d.status>=500||d.status===409;return{response:d,shouldRetry:f}});if(c)return c;throw await this.buildPatchError(a,l,"SPARQL UPDATE")}buildSparqlUpdate(e,t,r){const i=[];if(r.length>0)for(const s of r)i.push(`DELETE WHERE {
119
+ ${s}
120
+ }`);return e.length>0&&i.push(`DELETE DATA {
121
+ ${e.join(`
122
+ `)}
123
+ }`),t.length>0&&i.push(`INSERT DATA {
124
+ ${t.join(`
125
+ `)}
126
+ }`),i.join(`;
127
+ `)}async executeN3PatchInternal(e,t,r,i=[]){const s=this.tripleBuilder.buildN3Patch(t,r,i),{response:o,result:a,lastError:c}=await this.retryWithBackoff(async()=>{let l=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"text/n3"},body:s});if(l.status===404){const f=await this.fetchFn(e,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});if(!f.ok&&f.status!==409)throw new Error(`Failed to create resource ${e}: ${f.status} ${f.statusText}`);l=await this.fetchFn(e,{method:"PATCH",headers:{"Content-Type":"text/n3"},body:s})}if(l.ok)return await this.sparqlExecutor.invalidateHttpCache(e),{response:l,result:[{success:!0,source:e,status:l.status,via:"n3"}],shouldRetry:!1};const d=l.status>=500||l.status===409;return{response:l,shouldRetry:d}});if(a)return a;throw await this.buildPatchError(o,c,"N3 PATCH")}formatTerm(e){if(!e)return"";if(e.termType==="NamedNode")return`<${e.value}>`;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType==="Literal"){const r=`"${String(e.value??"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")}"`;if(e.language)return`${r}@${e.language}`;if(e.datatype&&e.datatype.value){if(e.datatype.value==="http://www.w3.org/2001/XMLSchema#integer"||e.datatype.value.endsWith("#integer"))return e.value;if(e.datatype.value!=="http://www.w3.org/2001/XMLSchema#string")return`${r}^^<${e.datatype.value}>`}return r}return String(e.value??e)}async fetchRecursiveTriplesToDelete(e,t,r,i=new Set){if(i.has(e))return[];i.add(e);const s=`SELECT ?p ?o WHERE { <${e}> ?p ?o . }`,o=await this.sparqlExecutor.queryBindings(s,r),a=[],c=[];o.forEach(l=>{const d=l.get("p"),f=l.get("o");if(!(!d||!f)&&(a.push(`<${e}> ${this.formatTerm(d)} ${this.formatTerm(f)} .`),f.termType==="NamedNode")){const u=d.value;for(const[,p]of Object.entries(t.columns)){const g=this.tripleBuilder.getPredicateUri(p,t),y=p.dataType==="object"||p.dataType==="json"||p.dataType==="array"&&(p.elementType==="object"||p.options?.baseType==="object");g===u&&y&&typeof f.value=="string"&&c.push(f.value)}}});for(const l of c){const d=await this.fetchRecursiveTriplesToDelete(l,t,r,i);a.push(...d)}return a}async fetchExistingObjects(e,t,r){const i=`SELECT ?o WHERE { <${t}> <${r}> ?o . }`;return(await this.sparqlExecutor.queryBindings(i,e)).map(o=>{const a=o.get?.("o");return this.formatTerm(a)}).filter(o=>!!o)}async fetchInverseSubjects(e,t,r){const i=`SELECT ?s WHERE { ?s <${r}> <${t}> . }`;return(await this.sparqlExecutor.queryContainer(e,{type:"SELECT",query:i})).map(o=>o.s??o["?s"]).filter(Boolean)}}class LdpStrategy{constructor(e){this.mode="ldp",this.sparqlExecutor=e.sparqlExecutor,this.sparqlConverter=e.sparqlConverter,this.fetchFn=e.fetchFn,this.ldpExecutor=e.ldpExecutor,this.getResolver=e.getResolver,this.listContainerResources=e.listContainerResources,this.findSubjectsForCondition=e.findSubjectsForCondition}async executeSelect(e,t,r){const i=e.baseTable;if(!i)throw new Error("SELECT plan must have a baseTable");const s=this.getResolver(i),o=e.conditionTree,a=await s.resolveSelectSources(i,t,o,f=>this.listContainerResources(f||t));let c;const l=e;if(l._simpleSelectOptions)c=this.sparqlConverter.convertSimpleSelect(l._simpleSelectOptions,void 0,void 0,!1);else if(l._sql){const f=this.sparqlConverter.parseDrizzleAST(l._sql,i);c=this.sparqlConverter.convertSelect(f,i,void 0,void 0,!1)}else c=this.sparqlConverter.convertSelectPlan(e,void 0,void 0,!1);const d=[];for(const f of a)try{const u=await this.sparqlExecutor.queryContainer(f,c);d.push(...u)}catch(u){console.warn(`[LdpStrategy] Failed to query source ${f}:`,u)}return d}async executeInsert(e,t,r){return await this.ldpExecutor.executeInsert(e.rows,e.table,r,{ensureContainerExists:e.ensureContainerExists,repairContainerOnWriteFailure:e.repairContainerOnWriteFailure,skipResourceExistenceCheck:e.skipResourceExistenceCheck,tableRegistry:e.tableRegistry,tableNameRegistry:e.tableNameRegistry})}async executeUpdate(e,t,r){const s=await this.getResolver(e.table).resolveSubjectsForMutation(e.table,e.where,a=>this.findSubjectsForCondition(e.where,e.table,a),()=>this.listContainerResources(t));return s.length===0?[]:await this.ldpExecutor.executeUpdate(e.table,e.data,s,r)}async executeDelete(e,t,r){if(!e.where)return[];const s=await this.getResolver(e.table).resolveSubjectsForMutation(e.table,e.where,a=>this.findSubjectsForCondition(e.where,e.table,a),()=>this.listContainerResources(t));return s.length===0?[]:await this.ldpExecutor.executeDelete(s,e.table,r)}}class SparqlStrategy{constructor(e){this.mode="sparql",this.sparqlExecutor=e.sparqlExecutor,this.sparqlConverter=e.sparqlConverter,this.podUrl=e.podUrl,this.uriResolver=e.uriResolver,this.createQueryEngine=e.createQueryEngine}setPodUrl(e){this.podUrl=e}resolvePodResourceIri(e){if(!e||/^[a-z][a-z0-9+.-]*:/i.test(e))return e;const t=this.podUrl?.trim();if(!t)return e;const r=t.endsWith("/")?t:`${t}/`;if(e.startsWith("/"))return`${r.replace(/\/+$/,"")}${e}`;try{return new URL(e,r).toString()}catch{return e}}resolveTargetGraph(e,t=!1){return e?this.uriResolver.getResourceMode(e)==="document"?t?void 0:this.resolvePodResourceIri(e.config?.containerPath??e.getContainerPath?.()):this.resolvePodResourceIri(e.config?.base):void 0}async executeSelect(e,t,r){const i=e.baseTable,s=this.resolveTargetGraph(i,!0),o=e;let a;const c=s!==void 0;if(o._simpleSelectOptions)a=this.sparqlConverter.convertSimpleSelect(o._simpleSelectOptions,s,void 0,c);else if(o._sql&&e.baseTable){const f=this.sparqlConverter.parseDrizzleAST(o._sql,e.baseTable);a=this.sparqlConverter.convertSelect(f,e.baseTable,s,void 0,c)}else a=this.sparqlConverter.convertSelectPlan(e,s,void 0,c);if(isSameOrigin(r,this.podUrl))return await this.sparqlExecutor.executeQueryWithSource(a,r,r.includes("/sparql")?"sparql":"auto");const{ComunicaSPARQLExecutor:l}=await __vitePreload(async()=>{const{ComunicaSPARQLExecutor:f}=await Promise.resolve().then(()=>sparqlExecutor);return{ComunicaSPARQLExecutor:f}},void 0);return await new l({sources:[r],fetch,logging:!1,createQueryEngine:this.createQueryEngine}).executeQueryWithSource(a,r,r.includes("/sparql")?"sparql":"auto")}async executeInsert(){throw new Error("SPARQL mode INSERT is not supported directly; writes should route through LDP strategy")}async executeUpdate(){throw new Error("SPARQL mode UPDATE is not supported directly; writes should route through LDP strategy")}async executeDelete(){throw new Error("SPARQL mode DELETE is not supported directly; writes should route through LDP strategy")}}class ExecutionStrategyFactoryImpl{constructor(e){this.ldpStrategy=null,this.sparqlStrategy=null,this.deps=e}setPodUrl(e){this.deps.podUrl=e,this.sparqlStrategy?.setPodUrl(e)}getStrategy(e){return e.getSparqlEndpoint?.()?this.getSparqlStrategy():this.getLdpStrategy()}getLdpStrategy(){return this.getLdpStrategyInternal()}getLdpStrategyInternal(){if(!this.ldpStrategy){const e={sparqlExecutor:this.deps.sparqlExecutor,sparqlConverter:this.deps.sparqlConverter,fetchFn:this.deps.sessionFetch,ldpExecutor:this.deps.ldpExecutor,getResolver:this.deps.getResolver,listContainerResources:this.deps.listContainerResources,findSubjectsForCondition:this.deps.findSubjectsForCondition};this.ldpStrategy=new LdpStrategy(e)}return this.ldpStrategy}getSparqlStrategy(){if(!this.sparqlStrategy){const e={sparqlExecutor:this.deps.sparqlExecutor,sparqlConverter:this.deps.sparqlConverter,sessionFetch:this.deps.sessionFetch,podUrl:this.deps.podUrl,uriResolver:this.deps.uriResolver,createQueryEngine:this.deps.createQueryEngine};this.sparqlStrategy=new SparqlStrategy(e)}return this.sparqlStrategy}static getMode(e){return e.getSparqlEndpoint?.()?"sparql":"ldp"}}class BaseResourceResolver{constructor(e){this.podBaseUrl=e}parseId(e,t){return this.extractBaseRelativeResourceId(e,t)}resolveSubject(e,t,r){const i=this.getSubjectBaseUrl(e);let s=t.id??t["@id"]??t.uri;if(s&&this.isAbsoluteUri(s))return s;if(typeof s=="string"){const c=this.resolveBaseRelativeSubjectId(e,s);if(c)return c;s.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(s=s.slice(1))}const o=this.getEffectiveTemplate(e),a=this.applyTemplate({...t,id:s},o,e,r);return i+a}parseTemplateId(e,t){const r=this.extractTemplateRelativeSubjectId(e,t);return this.extractIdFromTemplate(r,this.getEffectiveTemplate(e))}extractRelativeSubjectId(e,t){const r=this.getBaseUrlForTable(e);return t.startsWith(r)?t.substring(r.length):this.extractIdFallback(t)}extractBaseRelativeResourceId(e,t){const r=this.getContainerUrl(e);if(t.startsWith(r))return t.substring(r.length);const i=this.extractRelativeSubjectId(e,t);return i.startsWith("#")&&!(e.hasCustomTemplate?.()??!1)?`${this.getResourceUrl(e).split("/").filter(Boolean).pop()??""}${i}`:i}extractTemplateRelativeSubjectId(e,t){const r=this.resolveBaseUrl(e);return t.startsWith(r)?t.substring(r.length):this.extractRelativeSubjectId(e,t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=this.getEffectiveTemplate(e),r=this.getTemplateVariables(t);return t==="#{id}"||t.startsWith("#")&&r.length===1&&r[0].field==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const r=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${r}${t}`:null;if(r.endsWith("/"))return`${r}${t}`;const i=r.lastIndexOf("/");return`${i>=0?r.slice(0,i+1):`${r}/`}${t}`}hasVirtualIdColumn(e){return!!e.columns?.id?._virtualId}getBaseUrlForTable(e){return this.resolveBaseUrl(e)}getSubjectBaseUrl(e){return this.acceptsFragmentOnlyResourceId(e)?this.getResourceUrl(e):this.getBaseUrlForTable(e)}getEffectiveTemplate(e){return e.config?.subjectTemplate?e.config.subjectTemplate:this.getDefaultTemplate()}generateUuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}applyTemplate(e,t,r,i){if(!t.includes("{"))return t;const s=this.createTimeContext(e);return t.replace(/(#?)\{([^}]+)\}/g,(o,a,c)=>{const l=this.parseTemplateVariable(c),d=l.field;if(d==="index"&&i!==void 0)return a+String(i+1);if(d in s)return a+s[d];let f=e[d];if(d==="id"&&f==null&&(f=e["@id"]??e.uri),f==null)return`${a}{${c}}`;const u=this.applyTemplateTransforms(f,l,r,d);return a==="#"&&u.startsWith("#")?a+u.slice(1):a+u})}extractVarsFromTemplate(e,t){let r=0;const i=new Map;let s=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{([^}]+)\}/g,(o,a)=>{const c=this.parseTemplateVariable(a),l=`var${r++}`;return i.set(l,c.field),`(?<${l}>.+?)`});s=`^${s}$`;try{const o=e.match(new RegExp(s));if(!o?.groups)return null;const a={};for(const[c,l]of Object.entries(o.groups)){const d=i.get(c);if(!(!d||l===void 0)){if(d in a&&a[d]!==l)return null;a[d]=l}}return a}catch{return null}}extractIdFromTemplate(e,t){return this.extractVarsFromTemplate(e,t)?.id??null}extractIdValues(e){if(!e)return[];const t=[];if(typeof e=="object"&&!("type"in e)){for(const[r,i]of Object.entries(e)){const s=this.normalizeConditionColumnName(r);s!=="id"&&s!=="@id"||(Array.isArray(i)?t.push(...i.map(String)):i!=null&&t.push(String(i)))}if(t.length>0)return t}return this.collectIdValues(e,t),t}extractTemplateValues(e,t){if(!e||t.length===0)return{};const r=Array.from(new Set(t.map(s=>this.parseTemplateVariable(s).field))),i={};if(typeof e=="object"&&!("type"in e)){for(const[s,o]of Object.entries(e)){const a=this.normalizeConditionColumnName(s);r.includes(a)&&o!=null&&!Array.isArray(o)&&(i[a]=String(o))}return i}for(const s of r){const o=this.collectColumnValue(e,s);o!==void 0&&(i[s]=o)}return i}collectColumnValue(e,t){if(e){if(e.type==="binary_expr"&&this.normalizeConditionColumnName(e.left)===t&&e.operator==="="&&e.right!=null)return String(e.right);if(e.type==="logical_expr"&&e.operator==="AND"&&Array.isArray(e.expressions))for(const r of e.expressions){const i=this.collectColumnValue(r,t);if(i!==void 0)return i}}}collectIdValues(e,t){if(e){if(e.type==="binary_expr"){const r=this.normalizeConditionColumnName(e.left);(r==="id"||r==="@id")&&(e.operator==="="&&e.right!=null?t.push(String(e.right)):e.operator==="IN"&&Array.isArray(e.right)&&t.push(...e.right.map(String)))}if(e.type==="logical_expr"&&Array.isArray(e.expressions))for(const r of e.expressions)this.collectIdValues(r,t)}}normalizeConditionColumnName(e){let t;if(typeof e=="string")t=e;else if(e&&typeof e=="object"&&"name"in e){const r=e.name;t=typeof r=="string"?r:void 0}return t?t.includes(".")?t.split(".").pop()??t:t:""}parseTemplateVariable(e){const[t,...r]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:r}}getTemplateVariables(e){return Array.from(e.matchAll(/\{([^}]+)\}/g)).map(t=>this.parseTemplateVariable(t[1]))}createTimeContext(e){let t;const r=e.createdAt??e.created_at??e.dateCreated;return r instanceof Date?t=r:typeof r=="string"||typeof r=="number"?t=new Date(r):t=new Date,{yyyy:t.getUTCFullYear().toString(),MM:String(t.getUTCMonth()+1).padStart(2,"0"),dd:String(t.getUTCDate()).padStart(2,"0"),HH:String(t.getUTCHours()).padStart(2,"0"),mm:String(t.getUTCMinutes()).padStart(2,"0"),ss:String(t.getUTCSeconds()).padStart(2,"0")}}applyTemplateTransforms(e,t,r,i){let s=this.normalizeTemplateValue(e,r,i);for(const o of t.transforms){if(o==="id"){s=this.extractTemplateId(s,r,i);continue}o==="slug"&&(s=this.slugifyValue(s))}return s}normalizeTemplateValue(e,t,r){const i=String(e);if(!t||!r||!this.isAbsoluteUri(i))return i;const s=t.columns?.[r];return this.isLinkColumn(s)?this.extractTemplateId(i,t,r):i}extractTemplateId(e,t,r){if(e.startsWith("/")){const a=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}if(!this.isAbsoluteUri(e))return e;const i=t&&r?t.columns?.[r]:void 0,s=i?.getLinkTable?.()??i?.options?.linkTable;if(s)return this.parseTemplateId(s,e)??this.parseId(s,e);const o=this.extractIdFallback(e);return o.startsWith("#")?o.slice(1):o.replace(/\.ttl$/i,"")}isLinkColumn(e){return!!(e?.getLinkTable?.()||e?.options?.linkTable||e?.getLinkTableName?.()||e?.options?.linkTableName||e?.getLinkTarget?.()||e?.options?.linkTarget)}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}resolveBaseUrl(e){const t=e.config.base||e.config.name;if(t.startsWith("http://")||t.startsWith("https://"))return t;const r=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`,i=t.startsWith("/")?t.slice(1):t;return new URL(i,r).toString()}isAbsoluteUri(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")}extractIdFallback(e){const t=e.indexOf("#");if(t!==-1)return e.substring(t);const r=e.lastIndexOf("/");return r!==-1?e.substring(r+1):e}}const DEFAULT_TEMPLATE$1="{id}";class FragmentResourceResolver extends BaseResourceResolver{constructor(){super(...arguments),this.mode="fragment"}getDefaultTemplate(){return DEFAULT_TEMPLATE$1}getContainerUrl(e){const t=this.getResourceUrl(e),r=t.lastIndexOf("/");return t.substring(0,r+1)}getResourceUrl(e){return this.resolveBaseUrl(e)}getBaseUrlForTable(e){return this.getResourceUrl(e)}getResourceUrlForSubject(e){const t=e.indexOf("#");return t===-1?e:e.substring(0,t)}async resolveSelectSources(e,t,r,i){return[this.getResourceUrl(e)]}async resolveSubjectsForMutation(e,t,r,i){const s=this.extractIdValues(t);if(s.length>0)return s.map(a=>this.resolveSubject(e,{id:a}));const o=this.getResourceUrl(e);return r(o)}}class DebugLogger{constructor(e=!1,t="[drizzle-solid]"){this.enabled=e,this.prefix=t}log(e,...t){this.enabled&&console.log(`${this.prefix} ${e}`,...t)}warn(e,...t){this.enabled&&console.warn(`${this.prefix} ⚠️ ${e}`,...t)}error(e,...t){this.enabled&&console.error(`${this.prefix} ❌ ${e}`,...t)}group(e){this.enabled&&console.group(`${this.prefix} ${e}`)}groupEnd(){this.enabled&&console.groupEnd()}table(e){this.enabled&&console.table(e)}}let globalDebugLogger=null;function setGlobalDebugLogger(n){globalDebugLogger=n}function getGlobalDebugLogger(){return globalDebugLogger||(globalDebugLogger=new DebugLogger(!1)),globalDebugLogger}const DEFAULT_TEMPLATE="{id}";class DocumentResourceResolver extends BaseResourceResolver{constructor(){super(...arguments),this.mode="document"}buildUnsupportedCollectionReadError(e){return new Error(`Document-mode collection queries over plain LDP are not supported for table "${e.config.name}". Configure a global query capability (SPARQL endpoint or index), or use findById()/findByIri() for exact-target reads.`)}buildUnsupportedCollectionMutationError(e){return new Error(`Document-mode collection mutations over plain LDP are not supported for table "${e.config.name}". Use updateById()/updateByIri() or deleteById()/deleteByIri() for exact-target mutations.`)}getDefaultTemplate(){return DEFAULT_TEMPLATE}getContainerUrl(e){const t=e.getContainerPath();if(t.startsWith("http://")||t.startsWith("https://"))return t;const r=this.podBaseUrl.endsWith("/")?this.podBaseUrl:`${this.podBaseUrl}/`,i=t.startsWith("/")?t.slice(1):t;return new URL(i,r).toString()}getResourceUrl(e){return`${this.getContainerUrl(e)}${e.config.name}.ttl`}getBaseUrlForTable(e){return this.getContainerUrl(e)}getResourceUrlForSubject(e){const t=e.indexOf("#");return t!==-1?e.substring(0,t):e}async resolveSelectSources(e,t,r,i){const s=getGlobalDebugLogger(),o=this.getEffectiveTemplate(e),a=Array.from(new Set(this.getTemplateVariables(o).map(d=>d.field))).filter(d=>d!=="id"&&d!=="index"),c=this.extractIdValues(r),l=this.extractTemplateValues(r,a);if(c.length>0&&!("id"in l)&&(l.id=c[0]),s.group(`[Document Resolver] Resolving SELECT sources for table: ${e.name||"unknown"}`),s.log("Template:",o),s.log("ID values from condition:",c),s.log("Template values:",l),c.length>0){const d=c[0];if(this.isAbsoluteUri(d))return s.log("Full URI provided, using directly"),s.groupEnd(),c.map(f=>this.getResourceUrlForSubject(f))}if(c.length>0){if(a.every(u=>u in l)){s.log("All variables present, resolving directly");const u=c.map(p=>{const g=this.resolveSubject(e,{...l,id:p});return this.getResourceUrlForSubject(g)});return s.log("Resolved sources:",u),s.groupEnd(),u}const f=a.filter(u=>!(u in l));throw s.error("Missing required variables:",f),s.groupEnd(),new Error(`Cannot resolve subjectTemplate '${o}': missing required variable(s) [${f.join(", ")}] in query condition. Add eq(table.${f[0]}, value) to your where clause.`)}throw s.error("Document-mode LDP collection query is unsupported without an exact target"),s.groupEnd(),this.buildUnsupportedCollectionReadError(e)}async resolveSubjectsForMutation(e,t,r,i){const s=this.getEffectiveTemplate(e),o=Array.from(new Set(this.getTemplateVariables(s).map(l=>l.field))).filter(l=>l!=="id"&&l!=="index"),a=this.extractIdValues(t),c=this.extractTemplateValues(t,o);if(a.length>0&&!("id"in c)&&(c.id=a[0]),a.length>0){const l=a[0];if(this.isAbsoluteUri(l))return a}if(a.length>0){if(o.every(f=>f in c))return a.map(f=>this.resolveSubject(e,{...c,id:f}));const d=o.filter(f=>!(f in c));throw new Error(`Cannot resolve subjectTemplate '${s}' for mutation: missing required variable(s) [${d.join(", ")}] in query condition. Add eq(table.${d[0]}, value) to your where clause.`)}throw this.buildUnsupportedCollectionMutationError(e)}}class ResourceResolverFactoryImpl{constructor(e,t){this.resolverCache=new WeakMap,this.podBaseUrl=e,this.uriResolver=t??new UriResolverImpl}setPodBaseUrl(e){this.podBaseUrl=e,this.resolverCache=new WeakMap}getResolver(e){const t=this.resolverCache.get(e);if(t)return t;const i=this.determineMode(e)==="document"?new DocumentResourceResolver(this.podBaseUrl):new FragmentResourceResolver(this.podBaseUrl);return this.resolverCache.set(e,i),i}determineMode(e){return this.uriResolver.getResourceMode(e)}}const XSD={STRING:"http://www.w3.org/2001/XMLSchema#string",INTEGER:"http://www.w3.org/2001/XMLSchema#integer",BOOLEAN:"http://www.w3.org/2001/XMLSchema#boolean",DATETIME:"http://www.w3.org/2001/XMLSchema#dateTime",DATE:"http://www.w3.org/2001/XMLSchema#date",DECIMAL:"http://www.w3.org/2001/XMLSchema#decimal",DOUBLE:"http://www.w3.org/2001/XMLSchema#double",ANYURI:"http://www.w3.org/2001/XMLSchema#anyURI"},SHACL={NS:"http://www.w3.org/ns/shacl#",NODE_SHAPE:"http://www.w3.org/ns/shacl#NodeShape",TARGET_CLASS:"http://www.w3.org/ns/shacl#targetClass",PROPERTY:"http://www.w3.org/ns/shacl#property",PATH:"http://www.w3.org/ns/shacl#path",DATATYPE:"http://www.w3.org/ns/shacl#datatype",NODE_KIND:"http://www.w3.org/ns/shacl#nodeKind",MIN_COUNT:"http://www.w3.org/ns/shacl#minCount",MAX_COUNT:"http://www.w3.org/ns/shacl#maxCount",PATTERN:"http://www.w3.org/ns/shacl#pattern",NAME:"http://www.w3.org/ns/shacl#name",DESCRIPTION:"http://www.w3.org/ns/shacl#description",CLASS:"http://www.w3.org/ns/shacl#class",INVERSE_PATH:"http://www.w3.org/ns/shacl#inversePath",IRI:"http://www.w3.org/ns/shacl#IRI",LITERAL:"http://www.w3.org/ns/shacl#Literal",BLANK_NODE:"http://www.w3.org/ns/shacl#BlankNode"};function $constructor(n,e,t){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(n))return;a._zod.traits.add(n),e(a,c);const l=o.prototype,d=Object.keys(l);for(let f=0;f<d.length;f++){const u=d[f];u in a||(a[u]=l[u].bind(a))}}const i=t?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:n});function o(a){var c;const l=t?.Parent?new s:this;r(l,a),(c=l._zod).deferred??(c.deferred=[]);for(const d of l._zod.deferred)d();return l}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(n)}),Object.defineProperty(o,"name",{value:n}),o}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $ZodEncodeError extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const globalConfig={};function config(n){return globalConfig}function getEnumValues(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function jsonStringifyReplacer(n,e){return typeof e=="bigint"?e.toString():e}function cached(n){return{get value(){{const e=n();return Object.defineProperty(this,"value",{value:e}),e}}}}function nullish(n){return n==null}function cleanRegex(n){const e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,r=e.toString();let i=(r.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(r)){const c=r.match(/\d?e-(\d?)/);c?.[1]&&(i=Number.parseInt(c[1]))}const s=t>i?t:i,o=Number.parseInt(n.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}const EVALUATING=Symbol("evaluating");function defineLazy(n,e,t){let r;Object.defineProperty(n,e,{get(){if(r!==EVALUATING)return r===void 0&&(r=EVALUATING,r=t()),r},set(i){Object.defineProperty(n,e,{value:i})},configurable:!0})}function assignProp(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...n){const e={};for(const t of n){const r=Object.getOwnPropertyDescriptors(t);Object.assign(e,r)}return Object.defineProperties({},e)}function esc(n){return JSON.stringify(n)}function slugify(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function isObject(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const n=Function;return new n(""),!0}catch{return!1}});function isPlainObject(n){if(isObject(n)===!1)return!1;const e=n.constructor;if(e===void 0||typeof e!="function")return!0;const t=e.prototype;return!(isObject(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function shallowClone(n){return isPlainObject(n)?{...n}:Array.isArray(n)?[...n]:n}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function normalizeParams(n){const e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function optionalKeys(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=mergeDefs(n._zod.def,{get shape(){const o={};for(const a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(o[a]=t.shape[a])}return assignProp(this,"shape",o),o},checks:[]});return clone(n,s)}function omit(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=mergeDefs(n._zod.def,{get shape(){const o={...n._zod.def.shape};for(const a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete o[a]}return assignProp(this,"shape",o),o},checks:[]});return clone(n,s)}function extend(n,e){if(!isPlainObject(e))throw new Error("Invalid input to extend: expected a plain object");const t=n._zod.def.checks;if(t&&t.length>0){const s=n._zod.def.shape;for(const o in e)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=mergeDefs(n._zod.def,{get shape(){const s={...n._zod.def.shape,...e};return assignProp(this,"shape",s),s}});return clone(n,i)}function safeExtend(n,e){if(!isPlainObject(e))throw new Error("Invalid input to safeExtend: expected a plain object");const t=mergeDefs(n._zod.def,{get shape(){const r={...n._zod.def.shape,...e};return assignProp(this,"shape",r),r}});return clone(n,t)}function merge(n,e){const t=mergeDefs(n._zod.def,{get shape(){const r={...n._zod.def.shape,...e._zod.def.shape};return assignProp(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return clone(n,t)}function partial(n,e,t){const i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=mergeDefs(e._zod.def,{get shape(){const a=e._zod.def.shape,c={...a};if(t)for(const l in t){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(c[l]=n?new n({type:"optional",innerType:a[l]}):a[l])}else for(const l in a)c[l]=n?new n({type:"optional",innerType:a[l]}):a[l];return assignProp(this,"shape",c),c},checks:[]});return clone(e,o)}function required(n,e,t){const r=mergeDefs(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(t)for(const o in t){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(s[o]=new n({type:"nonoptional",innerType:i[o]}))}else for(const o in i)s[o]=new n({type:"nonoptional",innerType:i[o]});return assignProp(this,"shape",s),s}});return clone(e,r)}function aborted(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function prefixIssues(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function unwrapMessage(n){return typeof n=="string"?n:n?.message}function finalizeIssue(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const i=unwrapMessage(n.inst?._zod.def?.error?.(n))??unwrapMessage(e?.error?.(n))??unwrapMessage(t.customError?.(n))??unwrapMessage(t.localeError?.(n))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function getLengthableOrigin(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function issue(...n){const[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}const initializer$1=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),n.message=JSON.stringify(e,jsonStringifyReplacer,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(n,e=t=>t.message){const t={},r=[];for(const i of n.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):r.push(e(i));return{formErrors:r,fieldErrors:t}}function formatError(n,e=t=>t.message){const t={_errors:[]},r=i=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(o=>r({issues:o}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)t._errors.push(e(s));else{let o=t,a=0;for(;a<s.path.length;){const c=s.path[a];a===s.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(e(s))):o[c]=o[c]||{_errors:[]},o=o[c],a++}}};return r(n),t}const _parse=n=>(e,t,r,i)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:t,issues:[]},s);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){const a=new(i?.Err??n)(o.issues.map(c=>finalizeIssue(c,s,config())));throw captureStackTrace(a,i?.callee),a}return o.value},_parseAsync=n=>async(e,t,r,i)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:t,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(i?.Err??n)(o.issues.map(c=>finalizeIssue(c,s,config())));throw captureStackTrace(a,i?.callee),a}return o.value},_safeParse=n=>(e,t,r)=>{const i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new $ZodAsyncError;return s.issues.length?{success:!1,error:new(n??$ZodError)(s.issues.map(o=>finalizeIssue(o,i,config())))}:{success:!0,data:s.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=n=>async(e,t,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:t,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new n(s.issues.map(o=>finalizeIssue(o,i,config())))}:{success:!0,data:s.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=n=>(e,t,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _parse(n)(e,t,i)},_decode=n=>(e,t,r)=>_parse(n)(e,t,r),_encodeAsync=n=>async(e,t,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _parseAsync(n)(e,t,i)},_decodeAsync=n=>async(e,t,r)=>_parseAsync(n)(e,t,r),_safeEncode=n=>(e,t,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _safeParse(n)(e,t,i)},_safeDecode=n=>(e,t,r)=>_safeParse(n)(e,t,r),_safeEncodeAsync=n=>async(e,t,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(n)(e,t,i)},_safeDecodeAsync=n=>async(e,t,r)=>_safeParseAsync(n)(e,t,r),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$2=new RegExp(`^${dateSource}$`);function timeSource(n){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(n){return new RegExp(`^${timeSource(n)}$`)}function datetime$1(n){const e=timeSource({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${t.join("|")})`;return new RegExp(`^${dateSource}T(?:${r})$`)}const string$1=n=>{const e=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},integer=/^-?\d+$/,number$1=/^-?\d+(?:\.\d+)?$/,boolean$1=/^(?:true|false)$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(n,e)=>{$ZodCheck.init(n,e);const t=numericOriginMap[typeof e.value];n._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(n,e)=>{$ZodCheck.init(n,e);const t=numericOriginMap[typeof e.value];n._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(n,e)=>{$ZodCheck.init(n,e),n._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):floatSafeRemainder(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(n,e)=>{$ZodCheck.init(n,e),e.format=e.format||"float64";const t=e.format?.includes("int"),r=t?"int":"number",[i,s]=NUMBER_FORMAT_RANGES[e.format];n._zod.onattach.push(o=>{const a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,t&&(a.pattern=integer)}),n._zod.check=o=>{const a=o.value;if(t){if(!Number.isInteger(a)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:n,continue:!e.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:n,continue:!e.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(r._zod.bag.maximum=e.maximum)}),n._zod.check=r=>{const i=r.value;if(i.length<=e.maximum)return;const o=getLengthableOrigin(i);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),n._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const o=getLengthableOrigin(i);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(n,e)=>{var t;$ZodCheck.init(n,e),(t=n._zod.def).when??(t.when=r=>{const i=r.value;return!nullish(i)&&i.length!==void 0}),n._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),n._zod.check=r=>{const i=r.value,s=i.length;if(s===e.length)return;const o=getLengthableOrigin(i),a=s>e.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(n,e)=>{var t,r;$ZodCheck.init(n,e),n._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(n,e)=>{$ZodCheckStringFormat.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=lowercase),$ZodCheckStringFormat.init(n,e)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=uppercase),$ZodCheckStringFormat.init(n,e)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(n,e)=>{$ZodCheck.init(n,e);const t=escapeRegex(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=r,n._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),n._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:n,continue:!e.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(n,e)=>{$ZodCheck.init(n,e);const t=new RegExp(`^${escapeRegex(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(n,e)=>{$ZodCheck.init(n,e);const t=new RegExp(`.*${escapeRegex(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:n,continue:!e.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(n,e)=>{$ZodCheck.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});class Doc{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
128
+ `).filter(o=>o),i=Math.min(...r.map(o=>o.length-o.trimStart().length)),s=r.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,t=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...t,i.join(`
129
+ `))}}const version={major:4,minor:3,patch:5},$ZodType=$constructor("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=version;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const i of r)for(const s of i._zod.onattach)s(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{const i=(o,a,c)=>{let l=aborted(o),d;for(const f of a){if(f._zod.def.when){if(!f._zod.def.when(o))continue}else if(l)continue;const u=o.issues.length,p=f._zod.check(o);if(p instanceof Promise&&c?.async===!1)throw new $ZodAsyncError;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,o.issues.length!==u&&(l||(l=aborted(o,u)))});else{if(o.issues.length===u)continue;l||(l=aborted(o,u))}}return d?d.then(()=>o):o},s=(o,a,c)=>{if(aborted(o))return o.aborted=!0,o;const l=i(a,r,c);if(l instanceof Promise){if(c.async===!1)throw new $ZodAsyncError;return l.then(d=>n._zod.parse(d,c))}return n._zod.parse(l,c)};n._zod.run=(o,a)=>{if(a.skipChecks)return n._zod.parse(o,a);if(a.direction==="backward"){const l=n._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(d=>s(d,o,a)):s(l,o,a)}const c=n._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return c.then(l=>i(l,r,a))}return i(c,r,a)}}defineLazy(n,"~standard",()=>({validate:i=>{try{const s=safeParse$1(n,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return safeParseAsync$1(n,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??string$1(n._zod.bag),n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),$ZodStringFormat=$constructor("$ZodStringFormat",(n,e)=>{$ZodCheckStringFormat.init(n,e),$ZodString.init(n,e)}),$ZodGUID=$constructor("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=guid),$ZodStringFormat.init(n,e)}),$ZodUUID=$constructor("$ZodUUID",(n,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=uuid(r))}else e.pattern??(e.pattern=uuid());$ZodStringFormat.init(n,e)}),$ZodEmail=$constructor("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=email),$ZodStringFormat.init(n,e)}),$ZodURL=$constructor("$ZodURL",(n,e)=>{$ZodStringFormat.init(n,e),n._zod.check=t=>{try{const r=t.value.trim(),i=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),e.normalize?t.value=i.href:t.value=r;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=emoji()),$ZodStringFormat.init(n,e)}),$ZodNanoID=$constructor("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=nanoid),$ZodStringFormat.init(n,e)}),$ZodCUID=$constructor("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=cuid),$ZodStringFormat.init(n,e)}),$ZodCUID2=$constructor("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=cuid2),$ZodStringFormat.init(n,e)}),$ZodULID=$constructor("$ZodULID",(n,e)=>{e.pattern??(e.pattern=ulid),$ZodStringFormat.init(n,e)}),$ZodXID=$constructor("$ZodXID",(n,e)=>{e.pattern??(e.pattern=xid),$ZodStringFormat.init(n,e)}),$ZodKSUID=$constructor("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=ksuid),$ZodStringFormat.init(n,e)}),$ZodISODateTime=$constructor("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=datetime$1(e)),$ZodStringFormat.init(n,e)}),$ZodISODate=$constructor("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=date$2),$ZodStringFormat.init(n,e)}),$ZodISOTime=$constructor("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=time$1(e)),$ZodStringFormat.init(n,e)}),$ZodISODuration=$constructor("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=duration$1),$ZodStringFormat.init(n,e)}),$ZodIPv4=$constructor("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=ipv4),$ZodStringFormat.init(n,e),n._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=ipv6),$ZodStringFormat.init(n,e),n._zod.bag.format="ipv6",n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=cidrv4),$ZodStringFormat.init(n,e)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=cidrv6),$ZodStringFormat.init(n,e),n._zod.check=t=>{const r=t.value.split("/");try{if(r.length!==2)throw new Error;const[i,s]=r;if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});function isValidBase64(n){if(n==="")return!0;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}const $ZodBase64=$constructor("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=base64),$ZodStringFormat.init(n,e),n._zod.bag.contentEncoding="base64",n._zod.check=t=>{isValidBase64(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});function isValidBase64URL(n){if(!base64url.test(n))return!1;const e=n.replace(/[-_]/g,r=>r==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return isValidBase64(t)}const $ZodBase64URL=$constructor("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=base64url),$ZodStringFormat.init(n,e),n._zod.bag.contentEncoding="base64url",n._zod.check=t=>{isValidBase64URL(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),$ZodE164=$constructor("$ZodE164",(n,e)=>{e.pattern??(e.pattern=e164),$ZodStringFormat.init(n,e)});function isValidJWT(n,e=null){try{const t=n.split(".");if(t.length!==3)return!1;const[r]=t;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const $ZodJWT=$constructor("$ZodJWT",(n,e)=>{$ZodStringFormat.init(n,e),n._zod.check=t=>{isValidJWT(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}}),$ZodNumber=$constructor("$ZodNumber",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=n._zod.bag.pattern??number$1,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}const i=t.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return t;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:i,inst:n,...s?{received:s}:{}}),t}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(n,e)=>{$ZodCheckNumberFormat.init(n,e),$ZodNumber.init(n,e)}),$ZodBoolean=$constructor("$ZodBoolean",(n,e)=>{$ZodType.init(n,e),n._zod.pattern=boolean$1,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}const i=t.value;return typeof i=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:n}),t}}),$ZodAny=$constructor("$ZodAny",(n,e)=>{$ZodType.init(n,e),n._zod.parse=t=>t}),$ZodUnknown=$constructor("$ZodUnknown",(n,e)=>{$ZodType.init(n,e),n._zod.parse=t=>t}),$ZodNever=$constructor("$ZodNever",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)}),$ZodDate=$constructor("$ZodDate",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=new Date(t.value)}catch{}const i=t.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||t.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:n}),t}});function handleArrayResult(n,e,t){n.issues.length&&e.issues.push(...prefixIssues(t,n.issues)),e.value[t]=n.value}const $ZodArray=$constructor("$ZodArray",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{const i=t.value;if(!Array.isArray(i))return t.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),t;t.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const a=i[o],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(l=>handleArrayResult(l,t,o))):handleArrayResult(c,t,o)}return s.length?Promise.all(s).then(()=>t):t}});function handlePropertyResult(n,e,t,r,i){if(n.issues.length){if(i&&!(t in r))return;e.issues.push(...prefixIssues(t,n.issues))}n.value===void 0?t in r&&(e.value[t]=void 0):e.value[t]=n.value}function normalizeDef(n){const e=Object.keys(n.shape);for(const r of e)if(!n.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const t=optionalKeys(n.shape);return{...n,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function handleCatchall(n,e,t,r,i,s){const o=[],a=i.keySet,c=i.catchall._zod,l=c.def.type,d=c.optout==="optional";for(const f in e){if(a.has(f))continue;if(l==="never"){o.push(f);continue}const u=c.run({value:e[f],issues:[]},r);u instanceof Promise?n.push(u.then(p=>handlePropertyResult(p,t,f,e,d))):handlePropertyResult(u,t,f,e,d)}return o.length&&t.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:s}),n.length?Promise.all(n).then(()=>t):t}const $ZodObject=$constructor("$ZodObject",(n,e)=>{if($ZodType.init(n,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}const r=cached(()=>normalizeDef(e));defineLazy(n._zod,"propValues",()=>{const a=e.shape,c={};for(const l in a){const d=a[l]._zod;if(d.values){c[l]??(c[l]=new Set);for(const f of d.values)c[l].add(f)}}return c});const i=isObject,s=e.catchall;let o;n._zod.parse=(a,c)=>{o??(o=r.value);const l=a.value;if(!i(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:n}),a;a.value={};const d=[],f=o.shape;for(const u of o.keys){const p=f[u],g=p._zod.optout==="optional",y=p._zod.run({value:l[u],issues:[]},c);y instanceof Promise?d.push(y.then(w=>handlePropertyResult(w,a,u,l,g))):handlePropertyResult(y,a,u,l,g)}return s?handleCatchall(d,l,a,c,r.value,n):d.length?Promise.all(d).then(()=>a):a}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(n,e)=>{$ZodObject.init(n,e);const t=n._zod.parse,r=cached(()=>normalizeDef(e)),i=u=>{const p=new Doc(["shape","payload","ctx"]),g=r.value,y=b=>{const C=esc(b);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};p.write("const input = payload.value;");const w=Object.create(null);let _=0;for(const b of g.keys)w[b]=`key_${_++}`;p.write("const newResult = {};");for(const b of g.keys){const C=w[b],P=esc(b),M=u[b]?._zod?.optout==="optional";p.write(`const ${C} = ${y(b)};`),M?p.write(`
130
+ if (${C}.issues.length) {
131
+ if (${P} in input) {
132
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
133
+ ...iss,
134
+ path: iss.path ? [${P}, ...iss.path] : [${P}]
135
+ })));
136
+ }
137
+ }
138
+
139
+ if (${C}.value === undefined) {
140
+ if (${P} in input) {
141
+ newResult[${P}] = undefined;
142
+ }
143
+ } else {
144
+ newResult[${P}] = ${C}.value;
145
+ }
146
+
147
+ `):p.write(`
148
+ if (${C}.issues.length) {
149
+ payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
150
+ ...iss,
151
+ path: iss.path ? [${P}, ...iss.path] : [${P}]
152
+ })));
153
+ }
154
+
155
+ if (${C}.value === undefined) {
156
+ if (${P} in input) {
157
+ newResult[${P}] = undefined;
158
+ }
159
+ } else {
160
+ newResult[${P}] = ${C}.value;
161
+ }
162
+
163
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");const R=p.compile();return(b,C)=>R(u,b,C)};let s;const o=isObject,a=!globalConfig.jitless,l=a&&allowsEval.value,d=e.catchall;let f;n._zod.parse=(u,p)=>{f??(f=r.value);const g=u.value;return o(g)?a&&l&&p?.async===!1&&p.jitless!==!0?(s||(s=i(e.shape)),u=s(u,p),d?handleCatchall([],g,u,p,f,n):u):t(u,p):(u.issues.push({expected:"object",code:"invalid_type",input:g,inst:n}),u)}});function handleUnionResults(n,e,t,r){for(const s of n)if(s.issues.length===0)return e.value=s.value,e;const i=n.filter(s=>!aborted(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(s=>s.issues.map(o=>finalizeIssue(o,r,config())))}),e)}const $ZodUnion=$constructor("$ZodUnion",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),defineLazy(n._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),defineLazy(n._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),defineLazy(n._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){const i=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>cleanRegex(s.source)).join("|")})$`)}});const t=e.options.length===1,r=e.options[0]._zod.run;n._zod.parse=(i,s)=>{if(t)return r(i,s);let o=!1;const a=[];for(const c of e.options){const l=c._zod.run({value:i.value,issues:[]},s);if(l instanceof Promise)a.push(l),o=!0;else{if(l.issues.length===0)return l;a.push(l)}}return o?Promise.all(a).then(c=>handleUnionResults(c,i,n,s)):handleUnionResults(a,i,n,s)}}),$ZodIntersection=$constructor("$ZodIntersection",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{const i=t.value,s=e.left._zod.run({value:i,issues:[]},r),o=e.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,l])=>handleIntersectionResults(t,c,l)):handleIntersectionResults(t,s,o)}});function mergeValues(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(isPlainObject(n)&&isPlainObject(e)){const t=Object.keys(e),r=Object.keys(n).filter(s=>t.indexOf(s)!==-1),i={...n,...e};for(const s of r){const o=mergeValues(n[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};const t=[];for(let r=0;r<n.length;r++){const i=n[r],s=e[r],o=mergeValues(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};t.push(o.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(n,e,t){const r=new Map;let i;for(const a of e.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else n.issues.push(a);for(const a of t.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else n.issues.push(a);const s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&i&&n.issues.push({...i,keys:s}),aborted(n))return n;const o=mergeValues(e.value,t.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return n.value=o.data,n}const $ZodEnum=$constructor("$ZodEnum",(n,e)=>{$ZodType.init(n,e);const t=getEnumValues(e.entries),r=new Set(t);n._zod.values=r,n._zod.pattern=new RegExp(`^(${t.filter(i=>propertyKeyTypes.has(typeof i)).map(i=>typeof i=="string"?escapeRegex(i):i.toString()).join("|")})$`),n._zod.parse=(i,s)=>{const o=i.value;return r.has(o)||i.issues.push({code:"invalid_value",values:t,input:o,inst:n}),i}}),$ZodTransform=$constructor("$ZodTransform",(n,e)=>{$ZodType.init(n,e),n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new $ZodEncodeError(n.constructor.name);const i=e.transform(t.value,t);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(t.value=o,t));if(i instanceof Promise)throw new $ZodAsyncError;return t.value=i,t}});function handleOptionalResult(n,e){return n.issues.length&&e===void 0?{issues:[],value:void 0}:n}const $ZodOptional=$constructor("$ZodOptional",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",n._zod.optout="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),defineLazy(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),n._zod.parse=(t,r)=>{if(e.innerType._zod.optin==="optional"){const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>handleOptionalResult(s,t.value)):handleOptionalResult(i,t.value)}return t.value===void 0?t:e.innerType._zod.run(t,r)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(n,e)=>{$ZodOptional.init(n,e),defineLazy(n._zod,"values",()=>e.innerType._zod.values),defineLazy(n._zod,"pattern",()=>e.innerType._zod.pattern),n._zod.parse=(t,r)=>e.innerType._zod.run(t,r)}),$ZodNullable=$constructor("$ZodNullable",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"optin",()=>e.innerType._zod.optin),defineLazy(n._zod,"optout",()=>e.innerType._zod.optout),defineLazy(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazy(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,r)=>t.value===null?t:e.innerType._zod.run(t,r)}),$ZodDefault=$constructor("$ZodDefault",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);if(t.value===void 0)return t.value=e.defaultValue,t;const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>handleDefaultResult(s,e)):handleDefaultResult(i,e)}});function handleDefaultResult(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}const $ZodPrefault=$constructor("$ZodPrefault",(n,e)=>{$ZodType.init(n,e),n._zod.optin="optional",defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>(r.direction==="backward"||t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,r))}),$ZodNonOptional=$constructor("$ZodNonOptional",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(r=>r!==void 0)):void 0}),n._zod.parse=(t,r)=>{const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>handleNonOptionalResult(s,n)):handleNonOptionalResult(i,n)}});function handleNonOptionalResult(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}const $ZodCatch=$constructor("$ZodCatch",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"optin",()=>e.innerType._zod.optin),defineLazy(n._zod,"optout",()=>e.innerType._zod.optout),defineLazy(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(s=>(t.value=s.value,s.issues.length&&(t.value=e.catchValue({...t,error:{issues:s.issues.map(o=>finalizeIssue(o,r,config()))},input:t.value}),t.issues=[]),t)):(t.value=i.value,i.issues.length&&(t.value=e.catchValue({...t,error:{issues:i.issues.map(s=>finalizeIssue(s,r,config()))},input:t.value}),t.issues=[]),t)}}),$ZodPipe=$constructor("$ZodPipe",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"values",()=>e.in._zod.values),defineLazy(n._zod,"optin",()=>e.in._zod.optin),defineLazy(n._zod,"optout",()=>e.out._zod.optout),defineLazy(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,r)=>{if(r.direction==="backward"){const s=e.out._zod.run(t,r);return s instanceof Promise?s.then(o=>handlePipeResult(o,e.in,r)):handlePipeResult(s,e.in,r)}const i=e.in._zod.run(t,r);return i instanceof Promise?i.then(s=>handlePipeResult(s,e.out,r)):handlePipeResult(i,e.out,r)}});function handlePipeResult(n,e,t){return n.issues.length?(n.aborted=!0,n):e._zod.run({value:n.value,issues:n.issues},t)}const $ZodReadonly=$constructor("$ZodReadonly",(n,e)=>{$ZodType.init(n,e),defineLazy(n._zod,"propValues",()=>e.innerType._zod.propValues),defineLazy(n._zod,"values",()=>e.innerType._zod.values),defineLazy(n._zod,"optin",()=>e.innerType?._zod?.optin),defineLazy(n._zod,"optout",()=>e.innerType?._zod?.optout),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(handleReadonlyResult):handleReadonlyResult(i)}});function handleReadonlyResult(n){return n.value=Object.freeze(n.value),n}const $ZodCustom=$constructor("$ZodCustom",(n,e)=>{$ZodCheck.init(n,e),$ZodType.init(n,e),n._zod.parse=(t,r)=>t,n._zod.check=t=>{const r=t.value,i=e.fn(r);if(i instanceof Promise)return i.then(s=>handleRefineResult(s,t,r,n));handleRefineResult(i,t,r,n)}});function handleRefineResult(n,e,t,r){if(!n){const i={code:"custom",input:t,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(issue(i))}}var _a$1;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const i={...r,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}(_a$1=globalThis).__zod_globalRegistry??(_a$1.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(n,e){return new n({type:"string",...normalizeParams(e)})}function _email(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(e)})}function _guid(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(e)})}function _uuid(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _uuidv4(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(e)})}function _uuidv6(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(e)})}function _uuidv7(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(e)})}function _url(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(e)})}function _emoji(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(e)})}function _nanoid(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(e)})}function _cuid(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _cuid2(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(e)})}function _ulid(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(e)})}function _xid(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(e)})}function _ksuid(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(e)})}function _ipv4(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(e)})}function _ipv6(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(e)})}function _cidrv4(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(e)})}function _cidrv6(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(e)})}function _base64(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(e)})}function _base64url(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(e)})}function _e164(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(e)})}function _jwt(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(e)})}function _isoDateTime(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(e)})}function _isoDate(n,e){return new n({type:"string",format:"date",check:"string_format",...normalizeParams(e)})}function _isoTime(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(e)})}function _isoDuration(n,e){return new n({type:"string",format:"duration",check:"string_format",...normalizeParams(e)})}function _number(n,e){return new n({type:"number",checks:[],...normalizeParams(e)})}function _int(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(e)})}function _boolean(n,e){return new n({type:"boolean",...normalizeParams(e)})}function _any(n){return new n({type:"any"})}function _unknown(n){return new n({type:"unknown"})}function _never(n,e){return new n({type:"never",...normalizeParams(e)})}function _date(n,e){return new n({type:"date",...normalizeParams(e)})}function _lt(n,e){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(e),value:n,inclusive:!1})}function _lte(n,e){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(e),value:n,inclusive:!0})}function _gt(n,e){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(e),value:n,inclusive:!1})}function _gte(n,e){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(e),value:n,inclusive:!0})}function _multipleOf(n,e){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(e),value:n})}function _maxLength(n,e){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(e),maximum:n})}function _minLength(n,e){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(e),minimum:n})}function _length(n,e){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(e),length:n})}function _regex(n,e){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(e),pattern:n})}function _lowercase(n){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(n)})}function _uppercase(n){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(n)})}function _includes(n,e){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(e),includes:n})}function _startsWith(n,e){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(e),prefix:n})}function _endsWith(n,e){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(e),suffix:n})}function _overwrite(n){return new $ZodCheckOverwrite({check:"overwrite",tx:n})}function _normalize(n){return _overwrite(e=>e.normalize(n))}function _trim(){return _overwrite(n=>n.trim())}function _toLowerCase(){return _overwrite(n=>n.toLowerCase())}function _toUpperCase(){return _overwrite(n=>n.toUpperCase())}function _slugify(){return _overwrite(n=>slugify(n))}function _array(n,e,t){return new n({type:"array",element:e,...normalizeParams(t)})}function _refine(n,e,t){return new n({type:"custom",check:"custom",fn:e,...normalizeParams(t)})}function _superRefine(n){const e=_check(t=>(t.addIssue=r=>{if(typeof r=="string")t.issues.push(issue(r,t.value,e._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=t.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),t.issues.push(issue(i))}},n(t.value,t)));return e}function _check(n,e){const t=new $ZodCheck({check:"custom",...normalizeParams(e)});return t._zod.check=n,t}function initializeContext(n){let e=n?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:n.processors??{},metadataRegistry:n?.metadata??globalRegistry,target:e,unrepresentable:n?.unrepresentable??"throw",override:n?.override??(()=>{}),io:n?.io??"output",counter:0,seen:new Map,cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0}}function process$1(n,e,t={path:[],schemaPath:[]}){var r;const i=n._zod.def,s=e.seen.get(n);if(s)return s.count++,t.schemaPath.includes(n)&&(s.cycle=t.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};e.seen.set(n,o);const a=n._zod.toJSONSchema?.();if(a)o.schema=a;else{const d={...t,schemaPath:[...t.schemaPath,n],path:t.path};if(n._zod.processJSONSchema)n._zod.processJSONSchema(e,o.schema,d);else{const u=o.schema,p=e.processors[i.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);p(n,e,u,d)}const f=n._zod.parent;f&&(o.ref||(o.ref=f),process$1(f,e,d),e.seen.get(f).isParent=!0)}const c=e.metadataRegistry.get(n);return c&&Object.assign(o.schema,c),e.io==="input"&&isTransforming(n)&&(delete o.schema.examples,delete o.schema.default),e.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,e.seen.get(n).schema}function extractDefs(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const o of n.seen.entries()){const a=n.metadataRegistry.get(o[0])?.id;if(a){const c=r.get(a);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,o[0])}}const i=o=>{const a=n.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const f=n.external.registry.get(o[0])?.id,u=n.external.uri??(g=>g);if(f)return{ref:u(f)};const p=o[1].defId??o[1].schema.id??`schema${n.counter++}`;return o[1].defId=p,{defId:p,ref:`${u("__shared")}#/${a}/${p}`}}if(o[1]===t)return{ref:"#"};const l=`#/${a}/`,d=o[1].schema.id??`__schema${n.counter++}`;return{defId:d,ref:l+d}},s=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:c,defId:l}=i(o);a.def={...a.schema},l&&(a.defId=l);const d=a.schema;for(const f in d)delete d[f];d.$ref=c};if(n.cycles==="throw")for(const o of n.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
164
+
165
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of n.seen.entries()){const a=o[1];if(e===o[0]){s(o);continue}if(n.external){const l=n.external.registry.get(o[0])?.id;if(e!==o[0]&&l){s(o);continue}}if(n.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&n.reused==="ref"){s(o);continue}}}function finalize(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=o=>{const a=n.seen.get(o);if(a.ref===null)return;const c=a.def??a.schema,l={...c},d=a.ref;if(a.ref=null,d){r(d);const u=n.seen.get(d),p=u.schema;if(p.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,l),o._zod.parent===d)for(const y in c)y==="$ref"||y==="allOf"||y in l||delete c[y];if(p.$ref)for(const y in c)y==="$ref"||y==="allOf"||y in u.def&&JSON.stringify(c[y])===JSON.stringify(u.def[y])&&delete c[y]}const f=o._zod.parent;if(f&&f!==d){r(f);const u=n.seen.get(f);if(u?.schema.$ref&&(c.$ref=u.schema.$ref,u.def))for(const p in c)p==="$ref"||p==="allOf"||p in u.def&&JSON.stringify(c[p])===JSON.stringify(u.def[p])&&delete c[p]}n.override({zodSchema:o,jsonSchema:c,path:a.path??[]})};for(const o of[...n.seen.entries()].reverse())r(o[0]);const i={};if(n.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":n.target,n.external?.uri){const o=n.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=n.external.uri(o)}Object.assign(i,t.def??t.schema);const s=n.external?.defs??{};for(const o of n.seen.entries()){const a=o[1];a.def&&a.defId&&(s[a.defId]=a.def)}n.external||Object.keys(s).length>0&&(n.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(e,"input",n.processors),output:createStandardJSONSchemaMethod(e,"output",n.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const r=n._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return isTransforming(r.element,t);if(r.type==="set")return isTransforming(r.valueType,t);if(r.type==="lazy")return isTransforming(r.getter(),t);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return isTransforming(r.innerType,t);if(r.type==="intersection")return isTransforming(r.left,t)||isTransforming(r.right,t);if(r.type==="record"||r.type==="map")return isTransforming(r.keyType,t)||isTransforming(r.valueType,t);if(r.type==="pipe")return isTransforming(r.in,t)||isTransforming(r.out,t);if(r.type==="object"){for(const i in r.shape)if(isTransforming(r.shape[i],t))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(isTransforming(i,t))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(isTransforming(i,t))return!0;return!!(r.rest&&isTransforming(r.rest,t))}return!1}const createToJSONSchemaMethod=(n,e={})=>t=>{const r=initializeContext({...t,processors:e});return process$1(n,r),extractDefs(r,n),finalize(r,n)},createStandardJSONSchemaMethod=(n,e,t={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=initializeContext({...i??{},target:s,io:e,processors:t});return process$1(n,o),extractDefs(o,n),finalize(o,n)},formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},stringProcessor=(n,e,t,r)=>{const i=t;i.type="string";const{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:l}=n._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=formatMap[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){const d=[...c];d.length===1?i.pattern=d[0].source:d.length>1&&(i.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},numberProcessor=(n,e,t,r)=>{const i=t,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:d}=n._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof d=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=d,i.exclusiveMinimum=!0):i.exclusiveMinimum=d),typeof s=="number"&&(i.minimum=s,typeof d=="number"&&e.target!=="draft-04"&&(d>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o=="number"&&(i.maximum=o,typeof l=="number"&&e.target!=="draft-04"&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},booleanProcessor=(n,e,t,r)=>{t.type="boolean"},neverProcessor=(n,e,t,r)=>{t.not={}},anyProcessor=(n,e,t,r)=>{},unknownProcessor=(n,e,t,r)=>{},dateProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},enumProcessor=(n,e,t,r)=>{const i=n._zod.def,s=getEnumValues(i.entries);s.every(o=>typeof o=="number")&&(t.type="number"),s.every(o=>typeof o=="string")&&(t.type="string"),t.enum=s},customProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},transformProcessor=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},arrayProcessor=(n,e,t,r)=>{const i=t,s=n._zod.def,{minimum:o,maximum:a}=n._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=process$1(s.element,e,{...r,path:[...r.path,"items"]})},objectProcessor=(n,e,t,r)=>{const i=t,s=n._zod.def;i.type="object",i.properties={};const o=s.shape;for(const l in o)i.properties[l]=process$1(o[l],e,{...r,path:[...r.path,"properties",l]});const a=new Set(Object.keys(o)),c=new Set([...a].filter(l=>{const d=s.shape[l]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=process$1(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},unionProcessor=(n,e,t,r)=>{const i=n._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>process$1(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?t.oneOf=o:t.anyOf=o},intersectionProcessor=(n,e,t,r)=>{const i=n._zod.def,s=process$1(i.left,e,{...r,path:[...r.path,"allOf",0]}),o=process$1(i.right,e,{...r,path:[...r.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];t.allOf=c},nullableProcessor=(n,e,t,r)=>{const i=n._zod.def,s=process$1(i.innerType,e,r),o=e.seen.get(n);e.target==="openapi-3.0"?(o.ref=i.innerType,t.nullable=!0):t.anyOf=[s,{type:"null"}]},nonoptionalProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType},defaultProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,t.default=JSON.parse(JSON.stringify(i.defaultValue))},prefaultProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catchProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=o},pipeProcessor=(n,e,t,r)=>{const i=n._zod.def,s=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;process$1(s,e,r);const o=e.seen.get(n);o.ref=s},readonlyProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType,t.readOnly=!0},optionalProcessor=(n,e,t,r)=>{const i=n._zod.def;process$1(i.innerType,e,r);const s=e.seen.get(n);s.ref=i.innerType},ZodISODateTime=$constructor("ZodISODateTime",(n,e)=>{$ZodISODateTime.init(n,e),ZodStringFormat.init(n,e)});function datetime(n){return _isoDateTime(ZodISODateTime,n)}const ZodISODate=$constructor("ZodISODate",(n,e)=>{$ZodISODate.init(n,e),ZodStringFormat.init(n,e)});function date$1(n){return _isoDate(ZodISODate,n)}const ZodISOTime=$constructor("ZodISOTime",(n,e)=>{$ZodISOTime.init(n,e),ZodStringFormat.init(n,e)});function time(n){return _isoTime(ZodISOTime,n)}const ZodISODuration=$constructor("ZodISODuration",(n,e)=>{$ZodISODuration.init(n,e),ZodStringFormat.init(n,e)});function duration(n){return _isoDuration(ZodISODuration,n)}const initializer=(n,e)=>{$ZodError.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>formatError(n,t)},flatten:{value:t=>flattenError(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return n.issues.length===0}}})},ZodError=$constructor("ZodError",initializer),ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType=$constructor("ZodType",(n,e)=>($ZodType.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(n,"input"),output:createStandardJSONSchemaMethod(n,"output")}}),n.toJSONSchema=createToJSONSchemaMethod(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.check=(...t)=>n.clone(mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),n.with=n.check,n.clone=(t,r)=>clone(n,t,r),n.brand=()=>n,n.register=((t,r)=>(t.add(n,r),n)),n.parse=(t,r)=>parse(n,t,r,{callee:n.parse}),n.safeParse=(t,r)=>safeParse(n,t,r),n.parseAsync=async(t,r)=>parseAsync(n,t,r,{callee:n.parseAsync}),n.safeParseAsync=async(t,r)=>safeParseAsync(n,t,r),n.spa=n.safeParseAsync,n.encode=(t,r)=>encode(n,t,r),n.decode=(t,r)=>decode(n,t,r),n.encodeAsync=async(t,r)=>encodeAsync(n,t,r),n.decodeAsync=async(t,r)=>decodeAsync(n,t,r),n.safeEncode=(t,r)=>safeEncode(n,t,r),n.safeDecode=(t,r)=>safeDecode(n,t,r),n.safeEncodeAsync=async(t,r)=>safeEncodeAsync(n,t,r),n.safeDecodeAsync=async(t,r)=>safeDecodeAsync(n,t,r),n.refine=(t,r)=>n.check(refine(t,r)),n.superRefine=t=>n.check(superRefine(t)),n.overwrite=t=>n.check(_overwrite(t)),n.optional=()=>optional(n),n.exactOptional=()=>exactOptional(n),n.nullable=()=>nullable(n),n.nullish=()=>optional(nullable(n)),n.nonoptional=t=>nonoptional(n,t),n.array=()=>array(n),n.or=t=>union([n,t]),n.and=t=>intersection(n,t),n.transform=t=>pipe(n,transform(t)),n.default=t=>_default(n,t),n.prefault=t=>prefault(n,t),n.catch=t=>_catch(n,t),n.pipe=t=>pipe(n,t),n.readonly=()=>readonly(n),n.describe=t=>{const r=n.clone();return globalRegistry.add(r,{description:t}),r},Object.defineProperty(n,"description",{get(){return globalRegistry.get(n)?.description},configurable:!0}),n.meta=(...t)=>{if(t.length===0)return globalRegistry.get(n);const r=n.clone();return globalRegistry.add(r,t[0]),r},n.isOptional=()=>n.safeParse(void 0).success,n.isNullable=()=>n.safeParse(null).success,n.apply=t=>t(n),n)),_ZodString=$constructor("_ZodString",(n,e)=>{$ZodString.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(r,i,s)=>stringProcessor(n,r,i);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,n.regex=(...r)=>n.check(_regex(...r)),n.includes=(...r)=>n.check(_includes(...r)),n.startsWith=(...r)=>n.check(_startsWith(...r)),n.endsWith=(...r)=>n.check(_endsWith(...r)),n.min=(...r)=>n.check(_minLength(...r)),n.max=(...r)=>n.check(_maxLength(...r)),n.length=(...r)=>n.check(_length(...r)),n.nonempty=(...r)=>n.check(_minLength(1,...r)),n.lowercase=r=>n.check(_lowercase(r)),n.uppercase=r=>n.check(_uppercase(r)),n.trim=()=>n.check(_trim()),n.normalize=(...r)=>n.check(_normalize(...r)),n.toLowerCase=()=>n.check(_toLowerCase()),n.toUpperCase=()=>n.check(_toUpperCase()),n.slugify=()=>n.check(_slugify())}),ZodString=$constructor("ZodString",(n,e)=>{$ZodString.init(n,e),_ZodString.init(n,e),n.email=t=>n.check(_email(ZodEmail,t)),n.url=t=>n.check(_url(ZodURL,t)),n.jwt=t=>n.check(_jwt(ZodJWT,t)),n.emoji=t=>n.check(_emoji(ZodEmoji,t)),n.guid=t=>n.check(_guid(ZodGUID,t)),n.uuid=t=>n.check(_uuid(ZodUUID,t)),n.uuidv4=t=>n.check(_uuidv4(ZodUUID,t)),n.uuidv6=t=>n.check(_uuidv6(ZodUUID,t)),n.uuidv7=t=>n.check(_uuidv7(ZodUUID,t)),n.nanoid=t=>n.check(_nanoid(ZodNanoID,t)),n.guid=t=>n.check(_guid(ZodGUID,t)),n.cuid=t=>n.check(_cuid(ZodCUID,t)),n.cuid2=t=>n.check(_cuid2(ZodCUID2,t)),n.ulid=t=>n.check(_ulid(ZodULID,t)),n.base64=t=>n.check(_base64(ZodBase64,t)),n.base64url=t=>n.check(_base64url(ZodBase64URL,t)),n.xid=t=>n.check(_xid(ZodXID,t)),n.ksuid=t=>n.check(_ksuid(ZodKSUID,t)),n.ipv4=t=>n.check(_ipv4(ZodIPv4,t)),n.ipv6=t=>n.check(_ipv6(ZodIPv6,t)),n.cidrv4=t=>n.check(_cidrv4(ZodCIDRv4,t)),n.cidrv6=t=>n.check(_cidrv6(ZodCIDRv6,t)),n.e164=t=>n.check(_e164(ZodE164,t)),n.datetime=t=>n.check(datetime(t)),n.date=t=>n.check(date$1(t)),n.time=t=>n.check(time(t)),n.duration=t=>n.check(duration(t))});function string(n){return _string(ZodString,n)}const ZodStringFormat=$constructor("ZodStringFormat",(n,e)=>{$ZodStringFormat.init(n,e),_ZodString.init(n,e)}),ZodEmail=$constructor("ZodEmail",(n,e)=>{$ZodEmail.init(n,e),ZodStringFormat.init(n,e)}),ZodGUID=$constructor("ZodGUID",(n,e)=>{$ZodGUID.init(n,e),ZodStringFormat.init(n,e)}),ZodUUID=$constructor("ZodUUID",(n,e)=>{$ZodUUID.init(n,e),ZodStringFormat.init(n,e)}),ZodURL=$constructor("ZodURL",(n,e)=>{$ZodURL.init(n,e),ZodStringFormat.init(n,e)}),ZodEmoji=$constructor("ZodEmoji",(n,e)=>{$ZodEmoji.init(n,e),ZodStringFormat.init(n,e)}),ZodNanoID=$constructor("ZodNanoID",(n,e)=>{$ZodNanoID.init(n,e),ZodStringFormat.init(n,e)}),ZodCUID=$constructor("ZodCUID",(n,e)=>{$ZodCUID.init(n,e),ZodStringFormat.init(n,e)}),ZodCUID2=$constructor("ZodCUID2",(n,e)=>{$ZodCUID2.init(n,e),ZodStringFormat.init(n,e)}),ZodULID=$constructor("ZodULID",(n,e)=>{$ZodULID.init(n,e),ZodStringFormat.init(n,e)}),ZodXID=$constructor("ZodXID",(n,e)=>{$ZodXID.init(n,e),ZodStringFormat.init(n,e)}),ZodKSUID=$constructor("ZodKSUID",(n,e)=>{$ZodKSUID.init(n,e),ZodStringFormat.init(n,e)}),ZodIPv4=$constructor("ZodIPv4",(n,e)=>{$ZodIPv4.init(n,e),ZodStringFormat.init(n,e)}),ZodIPv6=$constructor("ZodIPv6",(n,e)=>{$ZodIPv6.init(n,e),ZodStringFormat.init(n,e)}),ZodCIDRv4=$constructor("ZodCIDRv4",(n,e)=>{$ZodCIDRv4.init(n,e),ZodStringFormat.init(n,e)}),ZodCIDRv6=$constructor("ZodCIDRv6",(n,e)=>{$ZodCIDRv6.init(n,e),ZodStringFormat.init(n,e)}),ZodBase64=$constructor("ZodBase64",(n,e)=>{$ZodBase64.init(n,e),ZodStringFormat.init(n,e)}),ZodBase64URL=$constructor("ZodBase64URL",(n,e)=>{$ZodBase64URL.init(n,e),ZodStringFormat.init(n,e)}),ZodE164=$constructor("ZodE164",(n,e)=>{$ZodE164.init(n,e),ZodStringFormat.init(n,e)}),ZodJWT=$constructor("ZodJWT",(n,e)=>{$ZodJWT.init(n,e),ZodStringFormat.init(n,e)}),ZodNumber=$constructor("ZodNumber",(n,e)=>{$ZodNumber.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(r,i,s)=>numberProcessor(n,r,i),n.gt=(r,i)=>n.check(_gt(r,i)),n.gte=(r,i)=>n.check(_gte(r,i)),n.min=(r,i)=>n.check(_gte(r,i)),n.lt=(r,i)=>n.check(_lt(r,i)),n.lte=(r,i)=>n.check(_lte(r,i)),n.max=(r,i)=>n.check(_lte(r,i)),n.int=r=>n.check(int(r)),n.safe=r=>n.check(int(r)),n.positive=r=>n.check(_gt(0,r)),n.nonnegative=r=>n.check(_gte(0,r)),n.negative=r=>n.check(_lt(0,r)),n.nonpositive=r=>n.check(_lte(0,r)),n.multipleOf=(r,i)=>n.check(_multipleOf(r,i)),n.step=(r,i)=>n.check(_multipleOf(r,i)),n.finite=()=>n;const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function number(n){return _number(ZodNumber,n)}const ZodNumberFormat=$constructor("ZodNumberFormat",(n,e)=>{$ZodNumberFormat.init(n,e),ZodNumber.init(n,e)});function int(n){return _int(ZodNumberFormat,n)}const ZodBoolean=$constructor("ZodBoolean",(n,e)=>{$ZodBoolean.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>booleanProcessor(n,t,r)});function boolean(n){return _boolean(ZodBoolean,n)}const ZodAny=$constructor("ZodAny",(n,e)=>{$ZodAny.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>anyProcessor()});function any(){return _any(ZodAny)}const ZodUnknown=$constructor("ZodUnknown",(n,e)=>{$ZodUnknown.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>unknownProcessor()});function unknown(){return _unknown(ZodUnknown)}const ZodNever=$constructor("ZodNever",(n,e)=>{$ZodNever.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>neverProcessor(n,t,r)});function never(n){return _never(ZodNever,n)}const ZodDate=$constructor("ZodDate",(n,e)=>{$ZodDate.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(r,i,s)=>dateProcessor(n,r),n.min=(r,i)=>n.check(_gte(r,i)),n.max=(r,i)=>n.check(_lte(r,i));const t=n._zod.bag;n.minDate=t.minimum?new Date(t.minimum):null,n.maxDate=t.maximum?new Date(t.maximum):null});function date(n){return _date(ZodDate,n)}const ZodArray=$constructor("ZodArray",(n,e)=>{$ZodArray.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>arrayProcessor(n,t,r,i),n.element=e.element,n.min=(t,r)=>n.check(_minLength(t,r)),n.nonempty=t=>n.check(_minLength(1,t)),n.max=(t,r)=>n.check(_maxLength(t,r)),n.length=(t,r)=>n.check(_length(t,r)),n.unwrap=()=>n.element});function array(n,e){return _array(ZodArray,n,e)}const ZodObject=$constructor("ZodObject",(n,e)=>{$ZodObjectJIT.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>objectProcessor(n,t,r,i),defineLazy(n,"shape",()=>e.shape),n.keyof=()=>_enum(Object.keys(n._zod.def.shape)),n.catchall=t=>n.clone({...n._zod.def,catchall:t}),n.passthrough=()=>n.clone({...n._zod.def,catchall:unknown()}),n.loose=()=>n.clone({...n._zod.def,catchall:unknown()}),n.strict=()=>n.clone({...n._zod.def,catchall:never()}),n.strip=()=>n.clone({...n._zod.def,catchall:void 0}),n.extend=t=>extend(n,t),n.safeExtend=t=>safeExtend(n,t),n.merge=t=>merge(n,t),n.pick=t=>pick(n,t),n.omit=t=>omit(n,t),n.partial=(...t)=>partial(ZodOptional,n,t[0]),n.required=(...t)=>required(ZodNonOptional,n,t[0])});function object(n,e){const t={type:"object",shape:n??{},...normalizeParams(e)};return new ZodObject(t)}const ZodUnion=$constructor("ZodUnion",(n,e)=>{$ZodUnion.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>unionProcessor(n,t,r,i),n.options=e.options});function union(n,e){return new ZodUnion({type:"union",options:n,...normalizeParams(e)})}const ZodIntersection=$constructor("ZodIntersection",(n,e)=>{$ZodIntersection.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>intersectionProcessor(n,t,r,i)});function intersection(n,e){return new ZodIntersection({type:"intersection",left:n,right:e})}const ZodEnum=$constructor("ZodEnum",(n,e)=>{$ZodEnum.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(r,i,s)=>enumProcessor(n,r,i),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(r,i)=>{const s={};for(const o of r)if(t.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ZodEnum({...e,checks:[],...normalizeParams(i),entries:s})},n.exclude=(r,i)=>{const s={...e.entries};for(const o of r)if(t.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new ZodEnum({...e,checks:[],...normalizeParams(i),entries:s})}});function _enum(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(r=>[r,r])):n;return new ZodEnum({type:"enum",entries:t,...normalizeParams(e)})}const ZodTransform=$constructor("ZodTransform",(n,e)=>{$ZodTransform.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>transformProcessor(n,t),n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new $ZodEncodeError(n.constructor.name);t.addIssue=s=>{if(typeof s=="string")t.issues.push(issue(s,t.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=t.value),o.inst??(o.inst=n),t.issues.push(issue(o))}};const i=e.transform(t.value,t);return i instanceof Promise?i.then(s=>(t.value=s,t)):(t.value=i,t)}});function transform(n){return new ZodTransform({type:"transform",transform:n})}const ZodOptional=$constructor("ZodOptional",(n,e)=>{$ZodOptional.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>optionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function optional(n){return new ZodOptional({type:"optional",innerType:n})}const ZodExactOptional=$constructor("ZodExactOptional",(n,e)=>{$ZodExactOptional.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>optionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function exactOptional(n){return new ZodExactOptional({type:"optional",innerType:n})}const ZodNullable=$constructor("ZodNullable",(n,e)=>{$ZodNullable.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>nullableProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function nullable(n){return new ZodNullable({type:"nullable",innerType:n})}const ZodDefault=$constructor("ZodDefault",(n,e)=>{$ZodDefault.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>defaultProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function _default(n,e){return new ZodDefault({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():shallowClone(e)}})}const ZodPrefault=$constructor("ZodPrefault",(n,e)=>{$ZodPrefault.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>prefaultProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function prefault(n,e){return new ZodPrefault({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():shallowClone(e)}})}const ZodNonOptional=$constructor("ZodNonOptional",(n,e)=>{$ZodNonOptional.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>nonoptionalProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function nonoptional(n,e){return new ZodNonOptional({type:"nonoptional",innerType:n,...normalizeParams(e)})}const ZodCatch=$constructor("ZodCatch",(n,e)=>{$ZodCatch.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>catchProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function _catch(n,e){return new ZodCatch({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const ZodPipe=$constructor("ZodPipe",(n,e)=>{$ZodPipe.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>pipeProcessor(n,t,r,i),n.in=e.in,n.out=e.out});function pipe(n,e){return new ZodPipe({type:"pipe",in:n,out:e})}const ZodReadonly=$constructor("ZodReadonly",(n,e)=>{$ZodReadonly.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>readonlyProcessor(n,t,r,i),n.unwrap=()=>n._zod.def.innerType});function readonly(n){return new ZodReadonly({type:"readonly",innerType:n})}const ZodCustom=$constructor("ZodCustom",(n,e)=>{$ZodCustom.init(n,e),ZodType.init(n,e),n._zod.processJSONSchema=(t,r,i)=>customProcessor(n,t)});function refine(n,e={}){return _refine(ZodCustom,n,e)}function superRefine(n){return _superRefine(n)}async function parseSHACL(n,e){const t=new N3Store,r=new N3Parser({baseIRI:e});return new Promise((i,s)=>{const o=[];r.parse(n,(a,c,l)=>{if(a){s(a);return}if(c)o.push(c);else{t.addQuads(o);try{const d=extractShapes(t);i(d)}catch(d){s(d)}}})})}function extractShapes(n){const e=[],t=n.getQuads(null,new NamedNode$1("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new NamedNode$1(SHACL.NODE_SHAPE),null);for(const r of t){const i=r.subject;if(i.termType==="NamedNode"||i.termType==="BlankNode"){const s=extractShape(n,i);s&&e.push(s)}}return e}function extractShape(n,e){const t=n.getQuads(e,new NamedNode$1(SHACL.TARGET_CLASS),null,null);if(t.length===0)return null;const r=t[0].object.value,i=n.getQuads(e,new NamedNode$1(SHACL.NAME),null,null),s=i.length>0?i[0].object.value:void 0,o=n.getQuads(e,new NamedNode$1(SHACL.DESCRIPTION),null,null),a=o.length>0?o[0].object.value:void 0,c=n.getQuads(e,new NamedNode$1(SHACL.PROPERTY),null,null),l=[];for(const d of c){const f=d.object,u=extractProperty(n,f);u&&l.push(u)}return{uri:e.value,targetClass:r,name:s,description:a,properties:l}}function extractProperty(n,e){const t=n.getQuads(e,new NamedNode$1(SHACL.PATH),null,null);if(t.length===0)return null;let r,i=!1;const s=t[0].object;if(s.termType==="BlankNode"){const C=n.getQuads(s,new NamedNode$1(SHACL.INVERSE_PATH),null,null);if(C.length>0)r=C[0].object.value,i=!0;else return null}else r=s.value;const o=n.getQuads(e,new NamedNode$1(SHACL.NAME),null,null),a=o.length>0?o[0].object.value:extractNameFromPath(r),c=n.getQuads(e,new NamedNode$1(SHACL.DATATYPE),null,null),l=c.length>0?c[0].object.value:void 0,d=n.getQuads(e,new NamedNode$1(SHACL.NODE_KIND),null,null),f=d.length>0?d[0].object.value:void 0,u=n.getQuads(e,new NamedNode$1(SHACL.MIN_COUNT),null,null),p=u.length>0?parseInt(u[0].object.value,10):void 0,g=n.getQuads(e,new NamedNode$1(SHACL.MAX_COUNT),null,null),y=g.length>0?parseInt(g[0].object.value,10):void 0,w=n.getQuads(e,new NamedNode$1(SHACL.PATTERN),null,null),_=w.length>0?w[0].object.value:void 0,R=n.getQuads(e,new NamedNode$1(SHACL.CLASS),null,null),b=R.length>0?R[0].object.value:void 0;return{path:r,name:a,datatype:l,nodeKind:f,minCount:p,maxCount:y,pattern:_,class:b,inverse:i}}function extractNameFromPath(n){const e=n.lastIndexOf("#");if(e>=0)return n.substring(e+1);const t=n.lastIndexOf("/");return t>=0?n.substring(t+1):n}function xsdToDrizzleType(n){if(!n)return"string";switch(n){case XSD.STRING:return"string";case XSD.INTEGER:return"integer";case XSD.BOOLEAN:return"boolean";case XSD.DATETIME:case XSD.DATE:return"datetime";case XSD.DECIMAL:case XSD.DOUBLE:return"number";case XSD.ANYURI:return"uri";default:return"string"}}function nodeKindToDrizzleType(n){if(n)switch(n){case SHACL.IRI:return"uri";case SHACL.LITERAL:return"string";case SHACL.BLANK_NODE:return"object";default:return}}class DrizzleShapeManager{constructor(e,t){this.podUrl=e.endsWith("/")?e:`${e}/`,this.authenticatedFetch=t??globalThis.fetch}generateShape(e){const t=typeof e.config.type=="string"?e.config.type:e.config.type.value;let i=e.getResourcePath?.()||e.getContainerPath();i&&!i.startsWith("http")&&(i=`${this.podUrl}${i.replace(/^\//,"")}`),i||(i=this.podUrl);const a=`${i.endsWith("/")?`${i}shapes/`:`${i.substring(0,i.lastIndexOf("/")+1)}shapes/`}${e.config.name}Shape.ttl#${e.config.name}Shape`,c=[];return Object.entries(e.columns).forEach(([l,d])=>{if(l==="id")return;const f=getPredicateForColumn(d,e);if(!f||f.includes("example.org/unknown"))return;const u={path:f,name:d.name,minCount:d.options?.required?1:void 0,maxCount:d.dataType==="array"||d.options?.isArray?void 0:1};if(d.options?.inverse&&(u.inverse=!0),d.dataType==="uri"||d.options?.linkTarget)u.datatype=d.dataType==="uri"?XSD.ANYURI:void 0,u.nodeKind=SHACL.IRI,u.class=d.options?.linkTarget;else switch(d.dataType){case"string":u.datatype=XSD.STRING,u.nodeKind=SHACL.LITERAL;break;case"integer":u.datatype=XSD.INTEGER,u.nodeKind=SHACL.LITERAL;break;case"boolean":u.datatype=XSD.BOOLEAN,u.nodeKind=SHACL.LITERAL;break;case"datetime":u.datatype=XSD.DATETIME,u.nodeKind=SHACL.LITERAL;break;case"object":case"json":u.nodeKind=SHACL.BLANK_NODE;break;case"array":u.minCount=d.options?.required?1:0;break}c.push(u)}),{uri:a,name:`${e.config.name} Shape`,description:`SHACL Shape for the ${e.config.name} PodTable.`,targetClass:t,properties:c.filter(l=>l.path!==SHACL.PATH)}}toSHACL(e){const t=[`@prefix sh: <${SHACL.NS}> .`,`@prefix xsd: <${XSD.ANYURI.slice(0,XSD.ANYURI.lastIndexOf("#")+1)}> .`,"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .","@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .","@prefix schema: <https://schema.org/> .","@prefix foaf: <http://xmlns.com/foaf/0.1/> .","@prefix dc: <http://purl.org/dc/terms/> .",`@prefix : <${e.uri.slice(0,e.uri.indexOf("#")+1)}>`,"",`:${e.name?.replace(/\s/g,"")} a sh:NodeShape ;`,` sh:targetClass <${e.targetClass}> ;`," sh:closed false ;"];return e.name&&t.push(` sh:name "${e.name}" ;`),e.description&&(t.push(` sh:description "${e.description}" ;`),t.push(` rdfs:comment """${e.description}""" ;`)),e.properties.forEach(r=>{t.push(" sh:property ["),t.push(` sh:path ${r.inverse?`[ sh:inversePath <${r.path}> ]`:`<${r.path}>`} ;`),r.name&&t.push(` sh:name "${r.name}" ;`),r.datatype&&t.push(` sh:datatype <${r.datatype}> ;`),r.nodeKind&&t.push(` sh:nodeKind <${r.nodeKind}> ;`),typeof r.minCount=="number"&&t.push(` sh:minCount ${r.minCount} ;`),typeof r.maxCount=="number"&&t.push(` sh:maxCount ${r.maxCount} ;`),r.pattern&&t.push(` sh:pattern "${r.pattern}" ;`),r.class&&t.push(` sh:class <${r.class}> ;`),t[t.length-1]=t[t.length-1].replace(/\s;$/,""),t.push(" ] ;")}),t[t.length-1]=t[t.length-1].replace(/\s;$/," ."),t.join(`
166
+ `)}async saveShape(e,t,r){const i=r??this.authenticatedFetch,s=this.toSHACL(e),o=await i(t,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:s});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`Failed to save shape to ${t}: ${o.status} ${o.statusText}${a?` - ${a}`:""}`)}}async loadShape(e,t){const r=t??this.authenticatedFetch;try{const i=await r(e,{headers:{Accept:"text/turtle, application/ld+json"}});if(!i.ok)return console.warn(`[ShapeManager] Failed to fetch Shape from ${e}: ${i.status}`),null;const s=await i.text(),o=await parseSHACL(s,e);return o.length===0?(console.warn(`[ShapeManager] No shapes found in ${e}`),null):o.find(c=>c.uri===e||e.includes(c.uri))||o[0]}catch(i){return console.error(`[ShapeManager] Error loading Shape from ${e}:`,i),null}}shapeToTable(e,t){const r=this.extractTableName(e),i={id:string$2("id").primaryKey()};for(const o of e.properties){const a=o.name||this.extractNameFromPath(o.path),c=this.propertyToColumn(o,a);c&&(i[a]=c)}const s=podTable(r,i,{type:e.targetClass,base:t});return{name:r,table:s,shape:e}}extractTableName(e){return e.name?e.name.replace(/\s+/g,"_").replace(/Shape$/i,"").toLowerCase():this.extractNameFromPath(e.targetClass).toLowerCase()}extractNameFromPath(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1);const r=e.lastIndexOf("/");return r>=0?e.substring(r+1):e}propertyToColumn(e,t){let r="string";if(e.nodeKind){const a=nodeKindToDrizzleType(e.nodeKind);a&&(r=a)}e.datatype&&(r=xsdToDrizzleType(e.datatype)),e.class&&(r="uri");const i=e.maxCount===void 0||e.maxCount>1,s=e.minCount!==void 0&&e.minCount>0;let o;switch(r){case"string":o=string$2(t).predicate(e.path);break;case"integer":o=integer$1(t).predicate(e.path);break;case"boolean":o=boolean$2(t).predicate(e.path);break;case"datetime":o=date$3(t).predicate(e.path);break;case"uri":o=uri(t).predicate(e.path),e.class&&(o=o.link(e.class));break;case"object":o=object$1(t).predicate(e.path);break;default:o=string$2(t).predicate(e.path)}return s&&(o=o.notNull()),i&&(o=o.array()),e.inverse&&(o=o.inverse()),o}validate(e,t){try{return this.shapeToZod(t).parse(e),{valid:!0}}catch(r){const i=r instanceof ZodError?r.issues:r&&Array.isArray(r.errors)?r.errors:void 0;return i?{valid:!1,errors:i.map(s=>({path:s.path?String(s.path[0]):"",message:s.message,constraint:s.code||"unknown",value:void 0}))}:{valid:!1,errors:[{path:"",message:String(r)}]}}}shapeToZod(e){const t={};return e.properties.forEach(r=>{if(!r.name)return;let i=any();if(r.nodeKind===SHACL.IRI)i=string().url().or(string().startsWith("http"));else if(r.datatype)switch(r.datatype){case XSD.STRING:i=string(),r.pattern&&(i=i.regex(new RegExp(r.pattern)));break;case XSD.INTEGER:i=number().int().or(string().regex(/^\d+$/));break;case XSD.DECIMAL:case XSD.DOUBLE:i=number().or(string().regex(/^-?\d*\.?\d+$/));break;case XSD.BOOLEAN:i=boolean().or(string().regex(/^(true|false|1|0)$/i));break;case XSD.DATETIME:case XSD.DATE:i=date().or(string().datetime({offset:!0}));break;case XSD.ANYURI:i=string();break}const s=r.maxCount!==1,o=r.minCount!==void 0&&r.minCount>0;s?(i=array(i),o?i=i.min(r.minCount):i=i.optional()):o||(i=i.optional()),t[r.name]=i}),object(t)}}const CACHE_TTL=300*1e3;class TypeIndexManager{constructor(e,t,r=globalThis.fetch){this.typeIndexCache=null,this.cachedTypeIndexUrl=null,this.webId=e,this.podUrl=t,this.fetchFn=r}getConfig(){return{webId:this.webId,podUrl:this.podUrl,fetch:this.fetchFn,autoCreate:!0}}updateConfig(e){this.webId=e.webId,this.podUrl=e.podUrl,e.fetch&&(this.fetchFn=e.fetch),this.clearCache()}clearCache(){this.typeIndexCache=null}async findTypeIndex(){if(this.typeIndexCache&&Date.now()-this.typeIndexCache.timestamp<CACHE_TTL)return this.typeIndexCache.url;try{let e,t;try{if(console.log("Fetching WebID profile document..."),e=await getSolidDataset(this.webId,{fetch:this.fetchFn}),e||(console.warn("WebID document is empty, attempting to refetch..."),e=await getSolidDataset(this.webId,{fetch:this.fetchFn})),e)if(t=getThing(e,this.webId),t)console.log("Successfully loaded profile from WebID document");else{console.warn("Profile thing not found in dataset, trying alternative approaches...");const i=getThingAll(e);i.length>0&&(t=i[0],console.log("Using first thing from dataset as profile"))}}catch(i){console.warn("Could not fetch WebID document:",i)}if(t){const i=this.extractStorages(t);this.podUrl=resolvePodBase({webId:this.webId,podUrl:this.podUrl,storages:i});const s=getUrl(t,"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(s){const l=Array.isArray(s)?s[0]:s;return console.log(`Found Private TypeIndex in profile: ${l}`),this.cachedTypeIndexUrl=l,l}const o=getUrl(t,"http://www.w3.org/ns/solid/terms#publicTypeIndex");if(o){const l=Array.isArray(o)?o[0]:o;return console.log(`Found Public TypeIndex in profile: ${l}`),this.cachedTypeIndexUrl=l,l}const a=getUrl(t,"http://www.w3.org/ns/solid/terms#typeIndex");if(a){const l=Array.isArray(a)?a[0]:a;return console.log(`Found legacy TypeIndex in profile: ${l}`),this.cachedTypeIndexUrl=l,l}const c=getUrl(t,"http://www.w3.org/ns/pim/space#storage");if(c){const l=Array.isArray(c)?c[0]:c;try{const d=await getSolidDataset(l,{fetch:this.fetchFn}),f=getThing(d,l);if(f){const u=getUrl(f,"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(u){const g=Array.isArray(u)?u[0]:u;return console.log(`Found Private TypeIndex in storage: ${g}`),this.cachedTypeIndexUrl=g,g}const p=getUrl(f,"http://www.w3.org/ns/solid/terms#publicTypeIndex");if(p){const g=Array.isArray(p)?p[0]:p;return console.log(`Found Public TypeIndex in storage: ${g}`),this.cachedTypeIndexUrl=g,g}}}catch(d){console.log("Could not access storage directory:",d)}}}else console.warn("Could not find profile in WebID document, trying fallback methods");const r=[this.joinWithPodBase("settings/privateTypeIndex.ttl"),this.joinWithPodBase("settings/publicTypeIndex.ttl"),this.joinWithPodBase("settings/typeIndex.ttl")];for(const i of r)try{return await getSolidDataset(i,{fetch:this.fetchFn}),console.log(`Found TypeIndex at standard location: ${i}`),this.cachedTypeIndexUrl=i,i}catch{}return console.log("No TypeIndex found"),null}catch(e){return console.error("Error finding TypeIndex:",e),null}}async createTypeIndex(e=!1){return e?this.createPublicTypeIndex():this.createPrivateTypeIndex()}async createPrivateTypeIndex(){const e=this.joinWithPodBase("settings/privateTypeIndex.ttl");try{const t=buildThing(createThing({url:e})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeIndex").addStringNoLocale("http://xmlns.com/foaf/0.1/name","Private Type Index").addStringNoLocale("http://purl.org/dc/terms/description","Private type index for this Pod").build(),r=setThing(createSolidDataset(),t);return await saveSolidDatasetAt(e,r,{fetch:this.fetchFn}),await this.linkTypeIndexToProfile(e,!1),console.log(`Private TypeIndex created and linked to profile: ${e}`),e}catch(t){throw console.error("Error creating private TypeIndex:",t),t}}async createPublicTypeIndex(){const e=this.joinWithPodBase("settings/publicTypeIndex.ttl");try{const t=buildThing(createThing({url:e})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeIndex").addStringNoLocale("http://xmlns.com/foaf/0.1/name","Public Type Index").addStringNoLocale("http://purl.org/dc/terms/description","Public type index for this Pod").build(),r=setThing(createSolidDataset(),t);return await saveSolidDatasetAt(e,r,{fetch:this.fetchFn}),await this.linkTypeIndexToProfile(e,!0),console.log(`Public TypeIndex created and linked to profile: ${e}`),e}catch(t){throw console.error("Error creating public TypeIndex:",t),t}}async linkTypeIndexToProfile(e,t){try{const r=await getSolidDataset(this.webId,{fetch:this.fetchFn}),i=getThing(r,this.webId);if(!i)throw new Error("Could not find profile in WebID document");const s=t?"http://www.w3.org/ns/solid/terms#publicTypeIndex":"http://www.w3.org/ns/solid/terms#privateTypeIndex",o=buildThing(i).addUrl(s,e).build(),a=setThing(r,o);await saveSolidDatasetAt(this.webId,a,{fetch:this.fetchFn}),console.log(`${t?"public":"private"} TypeIndex linked to profile: ${e}`)}catch(r){throw console.error("Error linking TypeIndex to profile:",r),r}}async registerType(e,t){let r=t;if(!r){const i=await this.findTypeIndexByVisibility(e.visibility==="public");if(!i)throw new Error("TypeIndex not found. Please create one first.");r=i}try{let i;try{i=await getSolidDataset(r,{fetch:this.fetchFn})}catch{i=createSolidDataset()}const s=e.instanceContainer||`${this.podUrl}${e.containerPath}`,o=`#${e.forClass.toLowerCase()}`,a=buildThing(createThing({url:`${r}${o}`})).addUrl("http://www.w3.org/1999/02/22-rdf-syntax-ns#type","http://www.w3.org/ns/solid/terms#TypeRegistration").addUrl("http://www.w3.org/ns/solid/terms#forClass",e.rdfClass).addUrl("http://www.w3.org/ns/solid/terms#instanceContainer",s).addStringNoLocale("http://xmlns.com/foaf/0.1/name",e.forClass).build();i=setThing(i,a),await saveSolidDatasetAt(r,i,{fetch:this.fetchFn});const c=e.visibility==="public"?"public":"private";console.log(`Type ${e.forClass} registered to ${c} TypeIndex: ${r}`)}catch(i){throw console.error("Error registering type:",i),i}}async findTypeIndexByVisibility(e){try{let t,r;try{console.log("Fetching WebID profile document for TypeIndex visibility check..."),t=await getSolidDataset(this.webId,{fetch:this.fetchFn}),t&&(r=getThing(t,this.webId))}catch(s){console.warn("Could not fetch WebID document for visibility check:",s)}if(r){const o=getUrl(r,e?"http://www.w3.org/ns/solid/terms#publicTypeIndex":"http://www.w3.org/ns/solid/terms#privateTypeIndex");if(o){const a=Array.isArray(o)?o[0]:o;return console.log(`Found ${e?"public":"private"} TypeIndex in profile: ${a}`),a}}const i=e?this.joinWithPodBase("settings/publicTypeIndex.ttl"):this.joinWithPodBase("settings/privateTypeIndex.ttl");try{return await getSolidDataset(i,{fetch:this.fetchFn}),console.log(`Found ${e?"public":"private"} TypeIndex at standard location: ${i}`),i}catch{return console.log(`No ${e?"public":"private"} TypeIndex found`),null}}catch(t){return console.error(`Error finding ${e?"public":"private"} TypeIndex:`,t),null}}joinWithPodBase(e){try{const t=this.getUserBaseUrl();return new URL(e,t).toString()}catch{return`${this.getUserBaseUrl()}${e}`.replace(/\/+$/,"")}}getUserBaseUrl(e){return resolvePodBase({webId:this.webId,podUrl:this.podUrl,storages:e})}extractStorages(e){try{return e?[...getUrlAll(e,"http://www.w3.org/ns/solid/terms#storage")||[],...getUrlAll(e,"http://www.w3.org/ns/pim/space#storage")||[]].filter(Boolean):[]}catch{return[]}}async discoverTypes(e){const t=e||await this.findTypeIndex();if(!t)return[];try{const r=await getSolidDataset(t,{fetch:this.fetchFn}),i=[],s=getThingAll(r);console.log(`[TypeIndex] Discovery on ${t} found ${s.length} things.`);for(const o of s)if(getUrl(o,"http://www.w3.org/1999/02/22-rdf-syntax-ns#type")==="http://www.w3.org/ns/solid/terms#TypeRegistration"){const c=getUrl(o,"http://www.w3.org/ns/solid/terms#forClass"),l=getUrl(o,"http://www.w3.org/ns/solid/terms#instanceContainer"),d=getStringNoLocale(o,"http://xmlns.com/foaf/0.1/name");if(c&&l){let f=l.replace(this.podUrl,"");f.endsWith("/")||(f+="/"),i.push({rdfClass:c,containerPath:f,forClass:d||this.deriveNameFromRdfClass(c),instanceContainer:l})}}return i}catch(r){return console.error("Error discovering types:",r),[]}}deriveNameFromRdfClass(e){try{const t=new URL(e);return t.hash?t.hash.slice(1):t.pathname.split("/").pop()||"Unknown"}catch{return"Unknown"}}async discoverSpecificType(e){try{const t=await this.findTypeIndex();if(t){const o=(await this.discoverTypes(t)).find(a=>a.rdfClass===e);if(o)return o}const i=(await this.discoverTypesFromProfile()).find(s=>s.rdfClass===e);return i||null}catch(t){return console.error(`Error discovering specific type ${e}:`,t),null}}async discoverSpecificTypes(e){const t=[];for(const r of e){const i=await this.discoverSpecificType(r);i&&t.push(i)}return t}async discoverTable(e){const t=await this.discoverSpecificType(e);if(!t)return null;const r=t.containerPath,i=this.inferColumnsFromRdfClass(e);return{name:t.forClass.toLowerCase(),columns:i,config:{containerPath:r,rdfClass:t.rdfClass}}}async discoverTables(e){const t=[];for(const r of e){const i=await this.discoverTable(r);i&&t.push(i)}return t}inferColumnsFromRdfClass(e){const t={id:{type:"int",primaryKey:!0}};return e.includes("schema.org/Person")?{...t,name:{type:"string",required:!0},email:{type:"string",required:!1}}:e.includes("schema.org/BlogPosting")?{...t,title:{type:"string",required:!0},content:{type:"string",required:!1},author:{type:"string",required:!1}}:e.includes("schema.org/Comment")?{...t,text:{type:"string",required:!0},author:{type:"string",required:!1}}:{...t,name:{type:"string",required:!0}}}async autoDiscoverAndRegister(e){const t=this.webId,r=e??this.webId;e&&e!==this.webId&&(this.webId=e);try{const i=await this.findTypeIndex();if(!i)return console.log("No TypeIndex found for user"),[];const s=await this.discoverTypes(i);return console.log(`Discovered ${s.length} types from TypeIndex for ${r}`),s}catch(i){return console.error("Error in auto discovery:",i),[]}finally{e&&e!==t&&(this.webId=t)}}async isTypeRegistered(e,t){return(await this.discoverTypes(t)).some(i=>i.rdfClass===e)}async discoverTypesFromProfile(){try{const e=await getSolidDataset(this.webId,{fetch:this.fetchFn}),t=getThing(e,this.webId);if(!t)throw new Error("Could not find profile in WebID document");const r=getUrl(t,"http://www.w3.org/ns/pim/space#storage"),i=[];if(r){const s=Array.isArray(r)?r[0]:r,o=await getSolidDataset(s,{fetch:this.fetchFn}),a=getThing(o,s);if(a){const c=getUrl(a,"http://www.w3.org/ns/ldp#contains");if(c){const l=Array.isArray(c)?c:[c];for(const d of l)try{const f=await getSolidDataset(d,{fetch:this.fetchFn}),u=getThing(f,d);if(u){const p=getStringNoLocale(u,"http://xmlns.com/foaf/0.1/name");if(p){const g=this.inferRdfClassFromContainerName(p);let y=d.replace(this.podUrl,"");y.endsWith("/")||(y+="/"),i.push({rdfClass:g,containerPath:y,forClass:this.capitalizeFirst(p),instanceContainer:d})}}}catch(f){console.warn(`Could not access container ${d}:`,f)}}}}return i}catch(e){return console.error("Error discovering types from profile:",e),[]}}inferRdfClassFromContainerName(e){const t=e.toLowerCase();return{people:"http://schema.org/Person",persons:"http://schema.org/Person",users:"http://schema.org/Person",posts:"http://schema.org/BlogPosting",articles:"http://schema.org/Article",events:"http://schema.org/Event",places:"http://schema.org/Place",organizations:"http://schema.org/Organization",products:"http://schema.org/Product",reviews:"http://schema.org/Review",comments:"http://schema.org/Comment",photos:"http://schema.org/ImageObject",images:"http://schema.org/ImageObject",documents:"http://schema.org/Document",files:"http://schema.org/MediaObject"}[t]||`https://example.com/vocab#${this.capitalizeFirst(e)}`}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}}class PodServices{constructor(e){const t=e.runtime,r=t.getPodUrl(),i=t.getWebId(),s=t.getFetch();this.uriResolver=new UriResolverImpl(r),this.sparqlConverter=new ASTToSPARQLConverter(r,i,this.uriResolver),this.sparqlExecutor=new SolidSPARQLExecutor({sources:[r],fetch:s,logging:!1,createQueryEngine:e.createQueryEngine}),this.ldpExecutor=new LdpExecutor(this.sparqlExecutor,s,this.uriResolver),this.typeIndexManager=new TypeIndexManager(i,r,s);const o=new TypeIndexDiscovery(this.typeIndexManager,r,this.uriResolver);if(e.disableInteropDiscovery)this.discovery=new CompositeDiscovery([o]);else{const a=new InteropDiscovery(i,s,e.clientId);this.discovery=new CompositeDiscovery([o,a])}this.shapeManager=new DrizzleShapeManager(r,s),this.resolverFactory=new ResourceResolverFactoryImpl(r,this.uriResolver),this.strategyFactory=new ExecutionStrategyFactoryImpl({sparqlExecutor:this.sparqlExecutor,sparqlConverter:this.sparqlConverter,sessionFetch:s,podUrl:r,createQueryEngine:e.createQueryEngine,ldpExecutor:this.ldpExecutor,uriResolver:this.uriResolver,getResolver:a=>this.resolverFactory.getResolver(a),listContainerResources:e.listContainerResources,findSubjectsForCondition:e.findSubjectsForCondition})}getUriResolver(){return this.uriResolver}getSparqlConverter(){return this.sparqlConverter}getSparqlExecutor(){return this.sparqlExecutor}getLdpExecutor(){return this.ldpExecutor}getTypeIndexManager(){return this.typeIndexManager}getDiscovery(){return this.discovery}getShapeManager(){return this.shapeManager}getResolverFactory(){return this.resolverFactory}getStrategyFactory(){return this.strategyFactory}}var define_process_env_default={},_a;function isRecord(n){return typeof n=="object"&&n!==null}function hasStringValue(n){return isRecord(n)&&typeof n.value=="string"}class PodDialect{constructor(e){this.registeredTables=new Set,this.preparedContainers=new Set,this.preparedResources=new Set,this.shortIdSubjectIndex=new Map,this.currentTableRegistry=new Map,this.currentTableNameRegistry=new Map,this.config=e;const t=e.session;this.debugLogger=new DebugLogger(e.debug||typeof process<"u"&&define_process_env_default?.LINX_DEBUG==="1"),setGlobalDebugLogger(this.debugLogger),this.debugLogger.log("Initializing PodDialect with config:",{debug:e.debug,disableInteropDiscovery:e.disableInteropDiscovery,storageTTL:e.storageTTL});const r=t.info.webId,i=t.info.clientId||t.info.client_id||define_process_env_default.SOLID_CLIENT_ID;if(!r)throw new Error("Session中未找到webId");this.runtime=new PodRuntime({session:t,webId:r,podUrl:e.podUrl,storageTTL:e.storageTTL}),this.webId=this.runtime.getWebId(),this.podUrl=this.runtime.getPodUrl(),this.services=new PodServices({runtime:this.runtime,clientId:i,createQueryEngine:e.createQueryEngine,disableInteropDiscovery:e.disableInteropDiscovery,listContainerResources:s=>this.listContainerResources(s),findSubjectsForCondition:(s,o,a)=>this.findSubjectsForCondition(s,o,a)}),this.uriResolver=this.services.getUriResolver(),this.sparqlConverter=this.services.getSparqlConverter(),this.sparqlExecutor=this.services.getSparqlExecutor(),this.ldpExecutor=this.services.getLdpExecutor(),this.typeIndexManager=this.services.getTypeIndexManager(),this.discovery=this.services.getDiscovery(),this.shapeManager=this.services.getShapeManager(),this.resolverFactory=this.services.getResolverFactory(),this.strategyFactory=this.services.getStrategyFactory(),this.executor=new PodExecutor({ensureConnected:async()=>{this.runtime.isConnected()||await this.connect()},ensureTableResourcePath:s=>this.ensureTableResourcePath(s),resolveTableResource:s=>this.resolveTableResource(s),resolveTableUrls:s=>this.resolveTableUrls(s),normalizeResourceUrl:s=>this.normalizeResourceUrl(s),normalizeContainerKey:s=>this.normalizeContainerKey(s),normalizeResourceKey:s=>this.normalizeResourceKey(s),ensureContainerExists:s=>this.ensureContainerExists(s),ensureResourceExists:(s,o)=>this.ensureResourceExists(s,o),shouldSkipResourcePreparation:()=>this.shouldSkipResourcePreparation(),shouldUseWriteTimeResourcePreparation:()=>this.shouldUseWriteTimeResourcePreparation(),shouldContinueAfterResourcePreparationError:()=>this.shouldContinueAfterResourcePreparationError(),getTableRegistries:()=>({tableRegistry:this.currentTableRegistry,tableNameRegistry:this.currentTableNameRegistry}),ensureIdentifierCondition:(s,o,a)=>this.ensureIdentifierCondition(s,o,a),resourceExists:s=>this.resourceExists(s),getStrategy:s=>this.getStrategy(s),getLdpStrategy:()=>this.strategyFactory.getLdpStrategy(),preparedContainers:this.preparedContainers,preparedResources:this.preparedResources,sparqlConverter:this.sparqlConverter,sparqlExecutor:this.sparqlExecutor,isSelectPlan:s=>this.isSelectPlan(s),isInsertPlan:s=>this.isInsertPlan(s),isUpdatePlan:s=>this.isUpdatePlan(s),isDeletePlan:s=>this.isDeletePlan(s)})}getResolver(e){return this.resolverFactory.getResolver(e)}buildShortIdSubjectIndexKey(e,t){const r=e.config?.base??e.getResourcePath?.()??e.getContainerPath?.()??"",i=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"<exact-id>",s=e.getType?.()??e.config?.type??"";return`${e.config?.name??""}|${r}|${i}|${s}|${t}`}registerResourceSubject(e,t){const r=parsePodResourceRef(e,t)?.templateValues.id;if(!r)return;const i=this.buildShortIdSubjectIndexKey(e,r),s=this.shortIdSubjectIndex.get(i)??new Set;s.add(t),this.shortIdSubjectIndex.set(i,s)}unregisterResourceSubject(e,t){const r=parsePodResourceRef(e,t)?.templateValues.id;if(!r)return;const i=this.buildShortIdSubjectIndexKey(e,r),s=this.shortIdSubjectIndex.get(i);s&&(s.delete(t),s.size===0&&this.shortIdSubjectIndex.delete(i))}lookupIndexedResourceSubject(e,t){const r=this.shortIdSubjectIndex.get(this.buildShortIdSubjectIndexKey(e,t));if(!r||r.size===0)return null;if(r.size>1)throw new Error(`Indexed short id '${t}' for resource '${e.config?.name??"resource"}' is ambiguous. Use a base-relative resource id or full IRI to disambiguate.`);return Array.from(r)[0]??null}getStrategy(e){return this.strategyFactory.getStrategy(e)}getShapeManager(){return this.services.getShapeManager()}getUriResolver(){return this.services.getUriResolver()}getDiscovery(){return this.services.getDiscovery()}setSchema(e){const t=new Map,r=new Map;for(const[i,s]of Object.entries(e))if(s&&typeof s=="object"&&"config"in s){const o=s,a=o.getType?.()||o.config?.type,c=o.config?.name||i;if(r.set(c,o),a){const l=t.get(a)||[];l.push(o),t.set(a,l)}}this.currentTableRegistry=t,this.currentTableNameRegistry=r,this.refreshBaseUrlFromRuntime()}refreshBaseUrlFromRuntime(){const e=this.runtime.getPodUrl();e&&(this.podUrl!==e&&(this.podUrl=e,this.preparedContainers.clear(),this.preparedResources.clear()),this.uriResolver.setPodUrl(this.podUrl),this.resolverFactory.setPodBaseUrl(this.podUrl),this.strategyFactory.setPodUrl(this.podUrl),this.typeIndexManager.updateConfig({...this.typeIndexManager.getConfig(),podUrl:this.podUrl}),this.ldpExecutor.setBaseUri(this.podUrl),(this.currentTableRegistry.size>0||this.currentTableNameRegistry.size>0)&&(this.ldpExecutor.setTableRegistry(this.currentTableRegistry,this.currentTableNameRegistry),this.sparqlConverter.setTableRegistry(this.currentTableRegistry,this.currentTableNameRegistry,this.podUrl)))}async findSubjectsForCondition(e,t,r){const i=this.buildSubjectLookupPlan(t,e),s=this.sparqlConverter.convertSelectPlan(i),o=this.normalizeResourceUrl(r);return(await this.executeOnResource(o,s)).map(c=>this.extractSubjectFromRow(c)).filter(c=>!!c)}async connect(){await this.runtime.connect(),this.refreshBaseUrlFromRuntime()}async disconnect(){await this.runtime.disconnect()}isConnected(){return this.runtime.isConnected()}extractUserPathFromWebId(){if(!this.webId)return"";try{const t=new URL(this.webId).pathname.split("/");if(t.length>=2)return`/${t[1]}/`}catch(e){console.warn("Failed to parse webId:",this.webId,e)}return""}resolveTableResource(e){const t=e.getSparqlEndpoint?.();if(t)return{mode:"sparql",endpoint:this.isAbsoluteUrl(t)?t:this.resolveAbsoluteUrl(t)};const{containerUrl:r,resourceUrl:i}=this.resolveLdpResource(e);return{mode:"ldp",containerUrl:r,resourceUrl:i}}resolveTableUrls(e){return this.resolveLdpResource(e)}resolveLdpResource(e){const t=typeof e.getResourcePath=="function"?e.getResourcePath():void 0;if(t){const w=this.resolveAbsoluteUrl(t);if(t.endsWith("/")){const P=w.endsWith("/")?w:`${w}/`;return{containerUrl:P,resourceUrl:P}}const R=this.normalizeResourceUrl(w),b=R.lastIndexOf("/");return{containerUrl:b>=0?`${R.slice(0,b+1)}`:`${R}/`,resourceUrl:R}}const r=e.getContainerPath()||"/data/",i=r.startsWith("http://")||r.startsWith("https://"),s=w=>w.endsWith("/")?w:`${w}/`;if(i){if(r.endsWith("/")){const b=s(r);return{containerUrl:b,resourceUrl:`${b}${e.config.name}.ttl`}}const w=r,_=w.lastIndexOf("/");if(_===-1)throw new Error(`Invalid containerPath for table ${e.config.name}: ${r}`);return{containerUrl:s(w.slice(0,_+1)),resourceUrl:w}}const o=this.extractUserPathFromWebId(),a=r.replace(/^\/+/,""),c=this.podUrl.endsWith("/")?this.podUrl:`${this.podUrl}/`,l=o.replace(/^\/+/,""),d=l&&a.startsWith(l);if(r.endsWith("/")){const w=d?a:`${l}${a}`,_=s(`${c}${w.replace(/^\/+/,"")}`);return{containerUrl:_,resourceUrl:`${_}${e.config.name}.ttl`}}const f=d?a:`${l}${a}`,u=f.lastIndexOf("/"),p=u>=0?f.slice(0,u+1):l,g=s(`${c}${p.replace(/^\/+/,"")}`),y=`${c}${f.replace(/^\/+/,"")}`;return{containerUrl:g,resourceUrl:y}}async resourceExists(e){const t=this.normalizeResourceUrl(e);if(this.preparedResources.has(t))return!0;try{const r=await this.runtime.getFetch()(t,{method:"HEAD"});return r.ok||r.status===409?(this.markResourcePrepared(t),!0):r.status===404?!1:r.status===405?(await this.runtime.getFetch()(t,{method:"GET",headers:{Accept:"text/turtle"}})).ok?(this.markResourcePrepared(t),!0):!1:r.status===401||r.status===403?(this.markResourcePrepared(t),!0):r.ok}catch(r){this.debugLogger.warn("[PodDialect] Failed to check resource existence via HEAD, falling back to GET",r);try{return(await this.runtime.getFetch()(t,{method:"GET",headers:{Accept:"text/turtle"}})).ok?(this.markResourcePrepared(t),!0):!1}catch(i){return this.debugLogger.warn("[PodDialect] Resource existence fallback GET failed",i),!1}}}normalizeResourceUrl(e){if(!e)return e;let t=e;for(;t.endsWith("/")&&!t.endsWith("://");)t=t.slice(0,-1);return t}normalizeContainerKey(e){const t=e.startsWith("http")?e:this.resolveAbsoluteUrl(e);return t.endsWith("/")?t:`${t}/`}normalizeResourceKey(e){const t=e.startsWith("http")?e:this.resolveAbsoluteUrl(e);return this.normalizeResourceUrl(t)}isStorageRootContainer(e){const t=this.runtime.getStorageUrl()??this.runtime.getPodUrl();return this.normalizeContainerKey(e)===this.normalizeContainerKey(t)}markContainerPrepared(e){this.preparedContainers.add(this.normalizeContainerKey(e))}markResourcePrepared(e){this.preparedResources.add(this.normalizeResourceKey(e))}isAbsoluteUrl(e){return/^https?:\/\//i.test(e)}resolveAbsoluteUrl(e){if(!e)return this.podUrl.replace(/\/$/,"");if(this.isAbsoluteUrl(e))return e;const t=e.replace(/^(\.\/)+/,""),r=this.podUrl.endsWith("/")?this.podUrl:`${this.podUrl}/`,i=t.endsWith("/"),o=this.extractUserPathFromWebId().replace(/^\/+|\/+$/g,"");let c=t.replace(/^\/+/,"");const l=o.length>0?`${o}/`:"";if(o.length>0){let f=!1;try{f=new URL(r).pathname.replace(/^\/+|\/+$/g,"").startsWith(o)}catch{f=!1}!f&&(c.length===0||c!==o&&!c.startsWith(l))&&(c=c.length>0?`${o}/${c}`:o)}i&&!c.endsWith("/")&&(c=`${c}/`);const d=new URL(c,r).toString();return!i&&d.endsWith("/")?d.replace(/\/$/,""):d}async ensureResourceExists(e,t={}){const{createIfMissing:r=!0}=t,i=this.normalizeResourceUrl(e);if(this.preparedResources.has(i))return;if(await this.resourceExists(i)){this.markResourcePrepared(i);return}if(!r)throw new Error(`Resource not found: ${i}`);for(let o=0;o<3;o++)try{const a=await this.runtime.getFetch()(i,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:""});if(a.ok||[201,202,204,409].includes(a.status)){await this.sparqlExecutor.invalidateHttpCache(i),this.markResourcePrepared(i);return}if(a.status>=500){this.debugLogger.warn(`[PodDialect] ensureResourceExists attempt ${o+1}/3 failed with ${a.status}, retrying...`),await new Promise(l=>setTimeout(l,1e3));continue}const c=await this.readErrorResponseBody(a);throw new Error(this.formatResourcePreparationError("Failed to create resource",a.status,a.statusText,i,c))}catch(a){if(o===2)throw this.debugLogger.error("[PodDialect] ensureResourceExists failed after 3 attempts:",a),a;this.debugLogger.warn(`[PodDialect] ensureResourceExists attempt ${o+1}/3 failed with error:`,a),await new Promise(c=>setTimeout(c,1e3))}}async executeOnResource(e,t,r){const i=this.normalizeResourceUrl(e);if(r?.mode==="sparql")return await this.executeOnSparqlEndpoint(r.endpoint,t);if(t.type==="SELECT"||t.type==="ASK")return await this.sparqlExecutor.queryContainer(i,t);throw new Error("LDP mode does not support SPARQL UPDATE; use N3 patch helpers instead.")}getFetchForEndpoint(e){return getFetchForOrigin(e,this.podUrl,this.runtime.getFetch())}async executeOnSparqlEndpoint(e,t){const r=this.getFetchForEndpoint(e);if(t.type==="SELECT"||t.type==="ASK")return isSameOrigin(e,this.podUrl)?await this.sparqlExecutor.executeQueryWithSource(t,e,"sparql"):await new ComunicaSPARQLExecutor({sources:[e],fetch,logging:!1,createQueryEngine:this.config.createQueryEngine}).executeQueryWithSource(t,e,"sparql");const i=await r(e,{method:"POST",headers:{"Content-Type":"application/sparql-update"},body:t.query});if(!i.ok){const s=await i.text().catch(()=>"");throw new Error(`SPARQL endpoint update failed: ${i.status} ${i.statusText}${s?` - ${s}`:""}`)}return[{success:!0,source:e,status:i.status,via:"sparql-endpoint"}]}async ensureTableResourcePath(e){const t=typeof e.config.type=="string"?e.config.type:String(e.config.type),r=e.getResourcePath?.();if(!e.config.typeIndex){if(r&&r.trim().length>0)return;console.log(`[AutoDiscover] Table ${e.config.name} has no resourcePath, using default container path`),e.config.containerPath="/data/";return}console.log(`[AutoDiscover] Table ${e.config.name} has typeIndex enabled, discovering from TypeIndex/SAI...`);try{const s=(await this.discovery.discover(t))[0];if(s){let o=s.container;o.endsWith("/")||(o+="/"),s.subjectTemplate&&(e.setSubjectTemplate(s.subjectTemplate),console.log(`[AutoDiscover] ✓ Applied subjectTemplate from discovery: ${s.subjectTemplate}`));const a=this.uriResolver.getResourceMode(e);let c;a==="document"?c=o:c=`${o}${e.config.name}.ttl`,console.log(`[AutoDiscover] ✓ Found resource path from TypeIndex: ${c} (mode: ${a})`),e.setBase(c),await this.tryDiscoverSparqlEndpoint(e,o)}else{if(r&&r.trim().length>0){console.log(`[AutoDiscover] No discovery result, using configured path: ${r}`);return}throw new Error(`[AutoDiscover] No data location found for type ${t}. Please ensure the data is registered in TypeIndex or SAI Registry.`)}}catch(i){if(r&&r.trim().length>0){console.warn("[AutoDiscover] Discovery process failed, using configured path:",r);return}throw console.warn("[AutoDiscover] Discovery process failed:",i),i}}async tryDiscoverSparqlEndpoint(e,t){if(e.getSparqlEndpoint())return;const r=`${t.replace(/\/$/,"")}/-/sparql`;try{(await this.runtime.getFetch()(r,{method:"OPTIONS"})).ok&&(console.log(`[AutoDiscover] ✓ Found SPARQL endpoint: ${r}`),e.setSparqlEndpoint(r))}catch{}}async query(e){return this.executor.query(e)}collectSelectSources(e){const t=new Set,{resourceUrl:r}=this.resolveTableUrls(e.baseTable);if(t.add(r),e.joins)for(const i of e.joins){const{resourceUrl:s}=this.resolveTableUrls(i.table);t.add(s)}return Array.from(t)}buildIdInConditionFromSubjects(e){if(!(!e||e.length===0))return new BinaryExpression("@id","IN",e)}isInsertPlan(e){return!!(e&&typeof e.table<"u"&&Array.isArray(e.rows))}isUpdatePlan(e){return!!(e&&typeof e.table<"u"&&"data"in e)}isDeletePlan(e){if(!e)return!1;const t=e;return typeof t.table>"u"?!1:typeof t.rows>"u"&&typeof t.data>"u"}isSelectPlan(e){return e?typeof e.baseTable<"u":!1}buildSubjectLookupPlan(e,t){const r=e.config.name??"table";return{baseTable:e,baseAlias:r,selectAll:!0,conditionTree:t,aliasToTable:new Map([[r,e]]),tableToAlias:new Map([[e,r]])}}isQueryConditionNode(e){return e instanceof BinaryExpression||e instanceof LogicalExpression||e instanceof UnaryExpression}extractSubjectFromRow(e){const t=e.subject??e["?subject"];return t?typeof t=="string"?t:hasStringValue(t)?t.value:null:null}conditionTargetsIdentifier(e){if(!e)return!1;if(e.type==="binary_expr"){const t=e.left,r=typeof t=="string"?t:t instanceof PodColumnBase?t.name:void 0;if(r==="@id"||r==="id")return!0}if(e.type==="logical_expr"){const t=e.expressions;if(Array.isArray(t))return t.some(r=>this.isQueryConditionNode(r)&&this.conditionTargetsIdentifier(r))}if(e.type==="unary_expr"){const t=e.value;if(t&&typeof t=="object"&&"type"in t)return this.conditionTargetsIdentifier(t)}return!1}async rewriteIdentifierConditionWithSubjects(e,t){const r=this.getResolver(t);try{const i=await r.resolveSubjectsForMutation(t,e,async()=>[],async()=>[]);return this.buildIdInConditionFromSubjects(i)}catch(i){const s=t.getSubjectTemplate?.()??t.config?.subjectTemplate??"<exact-id>";throw(i instanceof Error?i.message:String(i)).includes("missing required variable")?new Error(`Cannot resolve mutation target for table "${t.config.name??"unknown"}" with subjectTemplate "${s}" from where() alone. Use an explicit @id via db.updateByIri()/db.deleteByIri() (or the internal whereByIri()).`):i}}async ensureIdentifierCondition(e,t,r){if(e)return this.conditionTargetsIdentifier(e)?await this.rewriteIdentifierConditionWithSubjects(e,t):await this.rewriteWhereConditionWithSubjects(e,t,r)}async rewriteWhereConditionWithSubjects(e,t,r){if(!e)return;const i=await this.findSubjectsForCondition(e,t,r);return this.buildIdInConditionFromSubjects(i)}async executeSql(e,t){const r=e.queryChunks.join("");let i;if(r.toLowerCase().includes("select"))i="select";else if(r.toLowerCase().includes("insert"))i="insert";else if(r.toLowerCase().includes("update"))i="update";else if(r.toLowerCase().includes("delete"))i="delete";else throw new Error(`Unsupported SQL operation: ${r}`);const s={type:i,table:t,sql:e,values:e.params||[]};return this.query(s)}addNamespace(e,t){this.sparqlConverter.addPrefix(e,t)}getConfig(){return{podUrl:this.podUrl,webId:this.webId,connected:this.runtime.isConnected()}}getAuthenticatedFetch(){return this.runtime.getFetch()}getSPARQLConverter(){return this.sparqlConverter}getSPARQLExecutor(){return this.sparqlExecutor}getPodUrl(){return this.runtime.getPodUrl()}getWebId(){return this.runtime.getWebId()}async discoverDataLocations(e,t){return this.discovery.discover(e,t)}async discoverAll(){return this.discovery.discoverAll?this.discovery.discoverAll():[]}async discoverByApp(e){return this.discovery.discoverByApp?this.discovery.discoverByApp(e):[]}addSource(e){this.sparqlExecutor.addSource(e)}removeSource(e){this.sparqlExecutor.removeSource(e)}getSources(){return this.sparqlExecutor.getSources()}async addSourcesFromTypeIndex(){try{const e=await this.typeIndexManager.discoverTypes();for(const t of e)if(t.instanceContainer)this.sparqlExecutor.addSource(t.instanceContainer);else if(t.containerPath){const r=t.containerPath.startsWith("http")?t.containerPath:`${this.podUrl}${t.containerPath}`;this.sparqlExecutor.addSource(r)}console.log(`✅ 从 TypeIndex 自动添加了 ${e.length} 个数据源`)}catch(e){console.warn("⚠️ 无法从 TypeIndex 自动添加数据源:",e)}}async queryContainer(e,t,r){const i=this.sparqlConverter.parseDrizzleAST(t,r),s=this.sparqlConverter.convertSelect(i,r),o=r?.config?.containerPath||e;return this.sparqlExecutor.queryContainer(o,s)}async getPodMetadata(){if(!this.runtime.isConnected())throw new Error("Not connected to Pod");return{podUrl:this.podUrl,webId:this.webId,connected:this.runtime.isConnected(),sources:this.sparqlExecutor.getSources()}}stripSPARQLProlog(e){return e.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim()}looksLikeRawSQL(e){const t=this.stripSPARQLProlog(e);return!!(/^SELECT\b[\s\S]*\bFROM\b\s+(?!<|[?$])/i.test(t)&&!/\{/m.test(t)||/^INSERT\s+INTO\b/i.test(t)||/^UPDATE\s+[A-Za-z_`"][\w$`"]*\s+SET\b/i.test(t)||/^DELETE\s+FROM\b/i.test(t))}inferSPARQLQueryType(e){const r=this.stripSPARQLProlog(e).match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(r){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return r;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}async executeSPARQL(e){if(!this.runtime.isConnected())throw new Error("Not connected to Pod");if(this.looksLikeRawSQL(e))throw new Error("executeSPARQL only accepts SPARQL text; raw SQL is not supported in Solid dialect");const t=this.inferSPARQLQueryType(e);if(!t)throw new Error("Unsupported SPARQL query type. Supported types: SELECT, ASK, INSERT, DELETE, UPDATE");const r={type:t,query:e,prefixes:{}};return this.sparqlExecutor.executeQuery(r)}async transaction(e){console.log("Starting transaction");try{const t=await e(this);return console.log("Transaction completed successfully"),t}catch(t){throw console.error("Transaction failed:",t),t}}getResourcePreparationMode(){return this.config.resourcePreparation??"best-effort"}shouldSkipResourcePreparation(){return this.getResourcePreparationMode()==="off"}shouldUseWriteTimeResourcePreparation(){const e=this.getResourcePreparationMode();return e==="best-effort"||e==="off"}shouldContinueAfterResourcePreparationError(){return this.getResourcePreparationMode()==="best-effort"}async registerTable(e){if(this.shouldSkipResourcePreparation()){e.markInitialized?.(!0);return}if(e.config.autoRegister===!1){e.markInitialized?.(!0);return}const t=e.config.name??JSON.stringify(e.config);if(this.registeredTables.has(t)){e.markInitialized?.(!0);return}try{const r=this.resolveTableResource(e);if(r.mode!=="sparql")if(this.shouldUseWriteTimeResourcePreparation())try{e.setBase?.(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] setBase failed for ${e.config.name}:`,i)}else{await this.ensureContainerExists(r.containerUrl);try{await this.ensureResourceExists(r.resourceUrl,{createIfMissing:!0}),this.markResourcePrepared(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] ensureResourceExists failed for ${r.resourceUrl}:`,i)}this.markContainerPrepared(r.containerUrl);try{e.setBase?.(r.resourceUrl)}catch(i){this.debugLogger.warn(`[registerTable] setBase failed for ${e.config.name}:`,i)}}}catch(r){if(this.debugLogger.warn(`[registerTable] Resource preparation failed for ${e.config.name}:`,r),this.config.resourcePreparation==="strict")throw r}this.registeredTables.add(t),this.shouldUseWriteTimeResourcePreparation()||await this.discovery.register(e,{registryPath:e.config.saiRegistryPath}),e.markInitialized?.(!0)}async findTypeIndex(){return this.typeIndexManager.findTypeIndex()}async createTypeIndex(){return this.typeIndexManager.createTypeIndex()}async discoverTypes(e){return this.typeIndexManager.discoverTypes(e)}async autoDiscoverAndRegister(e){return this.typeIndexManager.autoDiscoverAndRegister(e)}async discoverTypesFromProfile(){return this.typeIndexManager.discoverTypesFromProfile()}async discoverSpecificType(e){return this.typeIndexManager.discoverSpecificType(e)}async discoverSpecificTypes(e){return this.typeIndexManager.discoverSpecificTypes(e)}async discoverTable(e){return this.typeIndexManager.discoverTable(e)}async discoverTables(e){return this.typeIndexManager.discoverTables(e)}async isTypeRegistered(e,t){return this.typeIndexManager.isTypeRegistered(e,t)}getTypeIndexManager(){return this.typeIndexManager}async ensureContainerExists(e){try{const t=this.normalizeContainerKey(e);if(this.preparedContainers.has(t))return;if(this.isStorageRootContainer(t)){this.markContainerPrepared(t);return}const r=await this.runtime.getFetch()(t,{method:"HEAD"});if(r.status===401||r.status===403){this.debugLogger.log(`[Container] ${t} 不允许 HEAD,视为已存在`),this.markContainerPrepared(t);return}if(r.status===404||r.status===500){const i=this.getParentContainer(t);i&&i!==t&&(this.debugLogger.log(`[Container] 先创建父容器: ${i}`),await this.ensureContainerExists(i)),this.debugLogger.log(`[Container] 创建容器: ${t}`);const s=await this.createContainerWithRetry(t);if(s.ok)this.debugLogger.log(`[Container] 容器创建成功: ${s.status}`),await this.sparqlExecutor.invalidateHttpCache(t),this.markContainerPrepared(t);else if(s.status===409)this.debugLogger.log(`[Container] 容器已存在(409冲突): ${t}`),this.markContainerPrepared(t);else{const o=await this.readErrorResponseBody(s);throw new Error(this.formatResourcePreparationError("Failed to create container",s.status,s.statusText,t,o))}}else if(r.status===200)this.debugLogger.log(`[Container] 容器已存在: ${t}`),this.markContainerPrepared(t);else if(r.status===409)this.debugLogger.log(`[Container] 容器已存在(409冲突): ${t}`),this.markContainerPrepared(t);else if(!r.ok)throw new Error(this.formatResourcePreparationError("Failed to check container",r.status,r.statusText,t))}catch(t){throw this.debugLogger.error("[Container] 确保容器存在时出错:",t),t}}async createContainerWithRetry(e){let t=null;for(let r=0;r<3;r+=1){const i=await this.runtime.getFetch()(e,{method:"PUT",headers:{"Content-Type":"text/turtle",Link:'<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'}});if(t=i,i.ok||i.status===409||i.status<500)return i;this.debugLogger.warn(`[Container] 创建容器失败 ${r+1}/3: ${i.status} ${i.statusText} (${e})`),r<2&&await this.sleep(250*(r+1))}return t}async sleep(e){await new Promise(t=>setTimeout(t,e))}async readErrorResponseBody(e){const t=e;if(typeof t.text!="function")return"";try{return(await t.text()).trim().slice(0,1e3)}catch{return""}}formatResourcePreparationError(e,t,r,i,s=""){const o=s?` - ${s}`:"";return`${e}: ${t} ${r} (${i})${o}`}getParentContainer(e){try{const t=new URL(e),r=t.pathname.split("/").filter(i=>i.length>0);return r.length<=1?null:(r.pop(),t.pathname="/"+r.join("/")+"/",t.toString())}catch(t){return this.debugLogger.error("[Container] 解析父容器 URL 失败:",t),null}}async listContainerResources(e){const t=this.normalizeContainerKey(e),r=[];try{const i={type:"SELECT",query:`
167
+ PREFIX ldp: <http://www.w3.org/ns/ldp#>
168
+ SELECT ?resource WHERE {
169
+ <${t}> ldp:contains ?resource .
170
+ }
171
+ `,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},s=await this.sparqlExecutor.queryContainer(t,i);for(const o of s){const a=o.resource;if(a){const c=hasStringValue(a)?a.value:String(a);r.push(c)}}}catch(i){console.warn("[listContainerResources] SPARQL query failed:",i)}return r}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},r=new PodDialect(t);e?.autoConnect&&r.connect().catch(console.error),e?.schema&&r.setSchema(e.schema);const i=new PodAsyncSession(r);return new PodDatabase(r,i,e?.schema)}export{DeleteQueryBuilder,DrizzleShapeManager,FederatedQueryExecutor,INTEROP,InsertQueryBuilder,NotificationsClient,ProviderCache,SHACL,SHAPETREES,SelectQueryBuilder,SolidSchema,UpdateQueryBuilder,XSD,and,boolean$2 as boolean,buildPodResourceIri,buildPodResourceIriForDatabase,buildPodResourceIriForResource,date$3 as date,drizzle,eq,extractPodResourceTemplateValue,id,inArray,integer$1 as integer,isSolidSchema,normalizePodDataResourceId,object$1 as object,parsePodResourceRef,podTable,renderDefaultIdTemplate,resolvePodBaseUrl,resolvePodBaseUrlFromDatabase,resolvePodResourceId,resolvePodResourceIriForDatabase,resolveRowSubject,solidSchema,string$2 as string,uri};