@kanonak-protocol/sdk 5.37.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/CredentialProvider.d.ts +69 -49
- package/dist/auth/ExecCredentialProvider.d.ts +55 -0
- package/dist/auth/OAuthDiscovery.d.ts +38 -10
- package/dist/auth/TokenCredentialProvider.d.ts +26 -6
- package/dist/auth/challenges.d.ts +17 -0
- package/dist/auth/credentialAnswer.d.ts +34 -0
- package/dist/auth/credentialConfig.d.ts +32 -0
- package/dist/auth/credentialedFetch.d.ts +33 -22
- package/dist/auth/index.d.ts +10 -4
- package/dist/auth/scope.d.ts +30 -0
- package/dist/browser.d.ts +4 -2
- package/dist/browser.js +1 -1
- package/dist/chunk-22DSABP6.js +1 -0
- package/dist/{chunk-HKX27KBZ.js → chunk-7F2EAT5Y.js} +1 -1
- package/dist/{chunk-LE26SEJU.js → chunk-A3HRXFVX.js} +1 -1
- package/dist/{chunk-4CXAZH3C.js → chunk-ADSDFJUO.js} +1 -1
- package/dist/{chunk-W5AOJ5SJ.js → chunk-GKIX3OD6.js} +1 -1
- package/dist/chunk-HKQTB65D.js +2 -0
- package/dist/{chunk-R4QCVB5M.js → chunk-O6SOU5Y2.js} +1 -1
- package/dist/chunk-PNBTIGX7.js +2 -0
- package/dist/{chunk-DONOB6RA.js → chunk-SBO34ENZ.js} +1 -1
- package/dist/chunk-TYVZXABI.js +155 -0
- package/dist/http/HttpError.d.ts +38 -0
- package/dist/http/kanonakFetch.d.ts +5 -2
- package/dist/index.d.ts +8 -2
- package/dist/index.js +2 -1
- package/dist/parsing/index.js +1 -1
- package/dist/producer/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/search/index.js +1 -1
- package/dist/server/index.js +5 -5
- package/dist/transformations/index.js +2 -2
- package/dist/transformations/v3/CompiledTransformationV3.d.ts +28 -27
- package/dist/transformations/v3/TransformationUriConstantsV3.d.ts +27 -0
- package/dist/validation/index.js +1 -1
- package/package.json +5 -4
- package/vectors/credential-helper-vectors.json +1039 -0
- package/dist/chunk-2WUZKSLB.js +0 -2
- package/dist/chunk-3353RWDC.js +0 -1
- package/dist/chunk-EG47OOJC.js +0 -155
- package/dist/chunk-OOYGILH4.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as X}from"./chunk-7JBKOJB4.js";import{a as H,b as J,fa as Q,ga as _,ha as Z,ja as E,pa as ne}from"./chunk-NUTHBBDZ.js";import{J as ee,K as te,c as P,d as w,e as k,f as L,g as q,i as M,j as I,k as T,l as O,m as R,n as j,o as N,r as x,s as U,z as Y}from"./chunk-D4QGPMRW.js";import{a as D}from"./chunk-FUUTGGJS.js";import{b as G}from"./chunk-F67UH4FD.js";import{k as W}from"./chunk-QILEJIFU.js";function re(p,t){for(let n of p)n instanceof P&&ae(n,ee(n),n.name,t)}function ae(p,t,n,r){let a=t.indexOf("#");r({kanonak:p,address:t,path:a<0?n:`${n}.${t.slice(a+1)}`});for(let i of ce(p))for(let{value:o,address:c}of te(p,i,t))o.item instanceof w&&ae(o.item,c,n,r)}function ce(p){let t=new Map;for(let n of p.statement){let r=n.predicate?.subject;if(!r)continue;let a=`${r.publisher}/${r.package_}/${r.name}`;t.has(a)||t.set(a,r)}return[...t.values()]}var oe="kanonak.org",pe="transformations",je=3,e=p=>({publisher:oe,package_:pe,name:p}),h=p=>({publisher:oe,package_:"math",name:p}),ve={Power:h("Power"),Modulo:h("Modulo"),Minimum:h("Minimum"),Maximum:h("Maximum"),Exp:h("Exp"),Ln:h("Ln"),Log10:h("Log10"),Sqrt:h("Sqrt"),Floor:h("Floor"),Ceil:h("Ceil"),Round:h("Round"),Sign:h("Sign"),Clip:h("Clip"),clipValue:h("clipValue"),clipLower:h("clipLower"),clipUpper:h("clipUpper")},A={Transformation:e("Transformation"),InstanceTransformation:e("InstanceTransformation"),SetTransformation:e("SetTransformation"),inputPattern:e("inputPattern"),rule:e("rule"),artifactName:e("artifactName"),outputs:e("outputs"),formatOverrides:e("formatOverrides"),partitionBy:e("partitionBy"),InputPattern:e("InputPattern"),matchesClass:e("matchesClass"),requires:e("requires"),sortBy:e("sortBy"),SortKey:e("SortKey"),byProperty:e("byProperty"),order:e("order"),SortOrder:e("SortOrder"),ascending:e("ascending"),descending:e("descending"),OutputFormat:e("OutputFormat"),backendUri:e("backendUri"),FormatOverride:e("FormatOverride"),formatTarget:e("formatTarget"),metadataKeys:e("metadataKeys"),metadataRenames:e("metadataRenames"),trailingNewline:e("trailingNewline"),omitWrapper:e("omitWrapper"),RenameEntry:e("RenameEntry"),fromKey:e("fromKey"),toKey:e("toKey"),FMT_MARKDOWN_FRONTMATTER:e("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:e("plain-markdown"),FMT_TOML:e("toml"),FMT_JSON:e("json"),FMT_HTML:e("html"),FMT_SVG:e("svg"),Expression:e("Expression"),ListSourcedExpression:e("ListSourcedExpression"),ListAggregate:e("ListAggregate"),IteratingExpression:e("IteratingExpression"),BuildAstNode:e("BuildAstNode"),astClass:e("astClass"),set:e("set"),AstFieldBinding:e("AstFieldBinding"),field:e("field"),bindValue:e("bindValue"),When:e("When"),condition:e("condition"),thenBuild:e("thenBuild"),elseBuild:e("elseBuild"),Concat:e("Concat"),parts:e("parts"),Fallback:e("Fallback"),primary:e("primary"),alternate:e("alternate"),StringLiteral:e("StringLiteral"),stringLiteral:e("stringLiteral"),IntegerLiteral:e("IntegerLiteral"),integerLiteral:e("integerLiteral"),DecimalLiteral:e("DecimalLiteral"),decimalLiteral:e("decimalLiteral"),BooleanLiteral:e("BooleanLiteral"),booleanLiteral:e("booleanLiteral"),VarRef:e("VarRef"),varName:e("varName"),PropertyRead:e("PropertyRead"),readSource:e("readSource"),readProp:e("readProp"),Traverse:e("Traverse"),traverseSource:e("traverseSource"),through:e("through"),step:e("step"),UriName:e("UriName"),uriNameOf:e("uriNameOf"),UriPublisher:e("UriPublisher"),uriPublisherOf:e("uriPublisherOf"),UriPackage:e("UriPackage"),uriPackageOf:e("uriPackageOf"),UriVersion:e("UriVersion"),uriVersionOf:e("uriVersionOf"),SubjectUri:e("SubjectUri"),subjectOf:e("subjectOf"),UriLiteral:e("UriLiteral"),refTo:e("refTo"),DisplayLabel:e("DisplayLabel"),labelTarget:e("labelTarget"),labelSource:e("labelSource"),ResolveRef:e("ResolveRef"),resolveSource:e("resolveSource"),Normalize:e("Normalize"),normSource:e("normSource"),normKind:e("normKind"),NormalizeKind:e("NormalizeKind"),NORM_TRIM_END:e("trim-end"),NORM_TO_UPPER:e("to-upper"),NORM_TO_LOWER:e("to-lower"),NORM_FIRST_CHAR:e("first-char"),UnescapedString:e("UnescapedString"),unescapedSource:e("unescapedSource"),IsSet:e("IsSet"),checkExpr:e("checkExpr"),ExpressionFragment:e("ExpressionFragment"),body:e("body"),CallFragment:e("CallFragment"),fragmentRef:e("fragmentRef"),source:e("source"),Join:e("Join"),separator:e("separator"),Count:e("Count"),Sum:e("Sum"),Min:e("Min"),Max:e("Max"),Average:e("Average"),loopVar:e("loopVar"),ForEach:e("ForEach"),emit:e("emit"),ListMap:e("ListMap"),mapBody:e("mapBody"),Filter:e("Filter"),predicate:e("predicate"),PartitionBy:e("PartitionBy"),partitionKey:e("partitionKey"),DistinctBy:e("DistinctBy"),distinctKey:e("distinctKey"),Partition:e("Partition"),key:e("key"),members:e("members"),AllStatements:e("AllStatements"),statementsOf:e("statementsOf"),StatementPredicate:e("StatementPredicate"),predicateOf:e("predicateOf"),StatementValue:e("StatementValue"),valueOf:e("valueOf"),DateFormat:e("DateFormat"),dateSource:e("dateSource"),dateFormat:e("dateFormat"),NumberFormat:e("NumberFormat"),numberSource:e("numberSource"),numberStyle:e("numberStyle"),fractionDigits:e("fractionDigits"),currencyCode:e("currencyCode"),BinaryArithmetic:e("BinaryArithmetic"),arithLeft:e("arithLeft"),arithRight:e("arithRight"),Add:e("Add"),Subtract:e("Subtract"),Multiply:e("Multiply"),Divide:e("Divide"),Reverse:e("Reverse"),WindowedMap:e("WindowedMap"),windowSize:e("windowSize"),windowVar:e("windowVar"),windowBody:e("windowBody"),PairwiseMap:e("PairwiseMap"),firstVar:e("firstVar"),secondVar:e("secondVar"),pairBody:e("pairBody"),Scan:e("Scan"),initialState:e("initialState"),stateVar:e("stateVar"),elementVar:e("elementVar"),accumulate:e("accumulate"),ListItemAt:e("ListItemAt"),itemIndex:e("itemIndex"),BinaryComparison:e("BinaryComparison"),compareLeft:e("compareLeft"),compareRight:e("compareRight"),Equals:e("Equals"),GreaterThan:e("GreaterThan"),LessThan:e("LessThan"),GreaterThanOrEqual:e("GreaterThanOrEqual"),LessThanOrEqual:e("LessThanOrEqual"),Not:e("Not"),operand:e("operand"),BooleanLogic:e("BooleanLogic"),operands:e("operands"),And:e("And"),Or:e("Or"),Contains:e("Contains"),haystack:e("haystack"),needle:e("needle"),Matches:e("Matches"),matchSource:e("matchSource"),pattern:e("pattern"),UnaryNumericOp:e("UnaryNumericOp"),value:e("value"),Abs:e("Abs"),Negate:e("Negate"),KindPredicate:e("KindPredicate"),IsReference:e("IsReference"),IsEmbedded:e("IsEmbedded"),IsList:e("IsList"),kindCheck:e("kindCheck"),IsString:e("IsString"),IsNumber:e("IsNumber"),IsBoolean:e("IsBoolean"),StatementObject:e("StatementObject"),statementSource:e("statementSource"),Let:e("Let"),letName:e("letName"),letValue:e("letValue"),letBody:e("letBody"),GetStatementByName:e("GetStatementByName"),inSubject:e("inSubject"),byName:e("byName"),RenderMarkdown:e("RenderMarkdown"),renderSource:e("renderSource"),renderProp:e("renderProp"),renderFormat:e("renderFormat"),RenderFormat:e("RenderFormat"),RENDER_HTML:e("render-html"),RENDER_MARKDOWN:e("render-markdown")};import{Carrier as K,carrierOf as me}from"@kanonak-protocol/canonical";function V(p){return me(`${p.publisher}/${p.package_}/${p.name}`)}var ue=/\[\[([^\[\]\n]+)\]\]/g,fe=/\[\[/g,ie=/```[\s\S]*?```|`[^`\n]*`/g;function le(p){let t=[];for(let n of p.matchAll(ie))t.push([n.index,n.index+n[0].length]);return t}function Me(p){if(!p||!p.includes("[["))return[];let t=le(p),n=i=>t.some(([o,c])=>i>=o&&i<c),r=new Set(C(p).map(i=>i.startOffset)),a=[];for(let i of p.matchAll(fe)){let o=i.index;if(n(o)||r.has(o))continue;let c=p.slice(o,o+48).replace(/\s+/g," ").trim();a.push({startOffset:o,snippet:c})}return a}function C(p){if(!p||!p.includes("[["))return[];let t=[];for(let a of p.matchAll(ie))t.push([a.index,a.index+a[0].length]);let n=a=>t.some(([i,o])=>a>=i&&a<o),r=[];for(let a of p.matchAll(ue)){let i=a.index;if(n(i))continue;let o=a[1],c=o.indexOf("|"),m=(c===-1?o:o.slice(0,c)).trim();if(m.length===0)continue;let s=c===-1?"":o.slice(c+1).trim(),u={reference:m,startOffset:i,endOffset:i+a[0].length};s.length>0&&(u.displayText=s),r.push(u)}return r}import{VersionOperator as de}from"@kanonak-protocol/types/document/models/enums";var ye={..._("range"),name:"range"};function ge(p){let t=p.lastIndexOf(".");return t===-1?p:p.slice(t+1)}var se=class{constructor(t){}async parseKanonaks(t,n){let r=await t.getAllDocumentsAsync(),a=new H(t),i=new J(a);this.knownPropertyClasses.clear();let o=await this.parseAllDocumentsAsync(r,a,i,t),c=await this.mergeAndCanonicalizeAsync(o,t);return await this.learnPropertyClassesAsync(c,r,a)&&(o=await this.parseAllDocumentsAsync(r,a,i,t),c=await this.mergeAndCanonicalizeAsync(o,t)),n&&(n.authored=o),c}knownPropertyClasses=new Map;async learnPropertyClassesAsync(t,n,r){let a=new Map;for(let m of n){let s=m.metadata.namespace_?.toString();s&&a.set(s,m)}let i=[],o=new Set;re(t,({kanonak:m})=>{for(let s of m.unresolvedPredicates){let u=`${s.sourceDoc}::${s.key}`;o.has(u)||(o.add(u),i.push(s))}});let c=!1;for(let m of i){let s=a.get(m.sourceDoc);if(!s)continue;let u=await r.resolveEntityAsync(m.key,s);if(!u)continue;let l=x(u.uri);if(this.knownPropertyClasses.has(l))continue;let d=Y(t,u.uri);if(!d)continue;let f=ne(t,d);f&&(this.knownPropertyClasses.set(l,f),c=!0)}return c}async parseAllDocumentsAsync(t,n,r,a){let i=[];for(let o of t){let c=o.metadata.namespace_?.toString()??"";for(let[m,s]of Object.entries(o.body)){let u=new P,l=this.resolveCanonicalEntity(m,o,c);u.namespace=l.namespace,u.name=l.name,u.sourceKey=m,u.statement=[];let d=await this.parseStatements(s,o,n,r,a);u.statement.push(...d.statements),u.unresolvedPredicates=d.unresolved,F(u,c),i.push(u)}}return i}async mergeAndCanonicalizeAsync(t,n){let r=new Map,a=new Map,i=[];for(let s of t)if(s instanceof P){let u=`${s.namespace}/${s.name}`,l=r.get(u);if(l){let d=a.get(u);for(let f of s.statement){let g=$(f);d.has(g)||(d.add(g),l.statement.push(f))}for(let f of s.unresolvedPredicates)l.unresolvedPredicates.some(g=>g.key===f.key&&g.sourceDoc===f.sourceDoc)||l.unresolvedPredicates.push(f)}else{let d=new P;d.namespace=s.namespace,d.name=s.name,d.sourceDoc=s.sourceDoc,s.sourceKey!==void 0&&(d.sourceKey=s.sourceKey);let f=new Set;for(let g of s.statement){let S=$(g);f.has(S)||(f.add(S),d.statement.push(g))}d.unresolvedPredicates=[...s.unresolvedPredicates],a.set(u,f),r.set(u,d),i.push(d)}}else i.push(s);let o=new Set;for(let s of i)if(s instanceof P){let u=s.namespace||"",l=u.indexOf("/"),d=l>=0?u.slice(0,l):"",f=l>=0?u.slice(l+1):"",g=f.indexOf("@"),S=g>=0?f.slice(0,g):f;o.add(`${d}/${S}/${s.name}`)}let c=s=>o.has(`${s.publisher}/${s.package_}/${s.name}`),m=new Map;for(let s of Z()){let u=await n.getDocumentsByNamespaceAsync(s.publisher,s.package_);m.set(s.package_,W(u).chosen?.metadata.namespace_?.version??void 0)}for(let s of t)s instanceof P&&this.canonicalizeStatementBuiltins(s.statement,c,m);return i}canonicalizeStatementBuiltins(t,n,r){for(let a of t){let i=a.predicate?.subject;if(E(i,n,r),a instanceof O)a.object instanceof k&&E(a.object.subject,n,r);else if(a instanceof R)a.object&&this.canonicalizeStatementBuiltins(a.object.statement,n,r);else if(a instanceof j)for(let o of a.object??[])o instanceof k?E(o.subject,n,r):o instanceof w&&this.canonicalizeStatementBuiltins(o.statement,n,r)}}resolveCanonicalEntity(t,n,r){if(!t.includes(".")||!n.metadata?.imports)return{namespace:r,name:t};let a=t.indexOf("."),i=t.substring(0,a),o=t.substring(a+1);for(let[c,m]of Object.entries(n.metadata.imports))for(let s of m)if((s.alias??s.packageName)===i){let l=s.version;return{namespace:`${c}/${s.packageName}@${l.major}.${l.minor}.${l.patch}`,name:o}}return{namespace:r,name:t}}async parseStatements(t,n,r,a,i){let o=[],c=[];if(typeof t!="object"||t===null||Array.isArray(t))return{statements:o,unresolved:c};let m=n.metadata.namespace_?.toString()??"";for(let[s,u]of Object.entries(t))try{let l=await this.getPropertyMetadata(s,n,r,i,a);if(!l){let f=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;Q(f)||c.push({key:s,sourceDoc:m});continue}let d=await this.parsePropertyValue(s,u,l,n,r,a,i);d&&(d instanceof q&&(d.sourceKey=s),o.push(d))}catch(l){throw new Error(`Failed to parse property '${s}': ${l.message}`,{cause:l})}return{statements:o,unresolved:c}}async getPropertyMetadata(t,n,r,a,i){let o=await r.resolveEntityAsync(t,n);if(!o)return;let c=o.entity,m=c.type?.toString()??"",s=m.includes(".")?m.substring(m.lastIndexOf(".")+1):m,u=new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]),l=this.knownPropertyClasses.get(x(o.uri));if(!u.has(s)&&!l)return;let d=l??i.getPropertyTypeClassification(m),f,g=async()=>{if(f)return f;if(!(o.isImported&&o.definedInNamespace))return f=n,n;if(typeof a.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${t}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let v=await a.getDocumentAsync(o.definedInNamespace);if(!v)throw new Error(`Cannot resolve the range of imported property '${t}': defining document '${o.definedInNamespace}' was not found in the repository.`);return f=v,v},S=await this.readDefinitionSlot(c,ye,g,r),y=S==null?void 0:String(S),b;if(d==="ObjectProperty")b="ObjectProperty";else if(d==="DatatypeProperty")b="DatatypeProperty";else{let v=y&&y.includes(".")?y.substring(y.lastIndexOf(".")+1):y??"";(y?i.isKnownXsdDatatypeName(y):!1)||v==="Literal"?b="DatatypeProperty":b="ObjectProperty"}let z;return y&&(z=(await r.resolveEntityAsync(y,await g()))?.uri),{propertyUri:o.uri.toString(),propertyType:b,range:y,rangeUri:z,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async readDefinitionSlot(t,n,r,a){let i=Object.keys(t).filter(s=>ge(s)===n.name);if(i.length===0)return;let o=await r(),c=_(n.name),m=c!==void 0&&c.publisher===n.publisher&&c.package_===n.package_;for(let s of i){let u=await a.resolveEntityAsync(s,o);if(u){if(U(u.uri,n))return t[s];continue}if(!s.includes(".")&&m)return t[s]}}async parsePropertyValue(t,n,r,a,i,o,c){let m=r.propertyUri;if(n!=null){if(Array.isArray(n))return this.parseListValue(m,n,r,a,i,o,c);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(m,n,r,a,i,o);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(m,n,r,a,i,o,c)}}async parseDatatypeValue(t,n,r,a,i,o){let c;if(typeof n=="string"){if(o.isSubstitutableDatatype(r.rangeUri))return await this.parseSubstitutableValue(t,n,a,i);c=n}else if(typeof n=="number"||typeof n=="boolean")c=String(n);else return;return this.typedScalarStatement(t,c,r)}typedScalarStatement(t,n,r){let a=k.parse(t),i=r.rangeUri?V(r.rangeUri):void 0;if(i===K.Boolean){let c=new T;return c.predicate=a,c.object=n==="true"||n==="1",c.carrier=i,c.lexical=n,c}if(i===K.Integer||i===K.Decimal||i===K.Double||i===K.Float){let c=new I;return c.predicate=a,c.object=Number(n),c.carrier=i,c.lexical=n,c}let o=M.parse(t,n);return i&&(o.carrier=i,o.lexical=n),o}typedListLiteral(t,n){let r=new L,a=n.rangeUri?V(n.rangeUri):void 0;return a===K.Boolean?r.value=t==="true"||t==="1":a===K.Integer||a===K.Decimal||a===K.Double||a===K.Float?r.value=Number(t):r.value=t,a&&(r.carrier=a,r.lexical=t),r}async parseSubstitutableValue(t,n,r,a){let i=new N;return i.predicate=k.parse(t),i.object=n,i.links=await this.resolveMarkdownLinks(n,r,a),i}async resolveMarkdownLinks(t,n,r){let a=[];for(let i of C(t)){let o=this.linkReference(i.reference,n);if(!o){let m=await r.resolveEntityAsync(i.reference,n);m&&(o=new k,o.subject=m.uri)}let c={reference:i.reference,startOffset:i.startOffset,endOffset:i.endOffset};i.displayText!==void 0&&(c.displayText=i.displayText),o!==void 0&&(c.target=o),a.push(c)}return a}async parseObjectValue(t,n,r,a,i,o,c){if(typeof n=="string"){if(r.rangeUri&&U(r.rangeUri,A.Expression))return this.coerceExpressionLiteral(t,n,r.rangeUri);let m=await this.resolveReference(n,a,i);if(!m)return;let s=new O;return s.predicate=k.parse(t),s.object=m,s}if(typeof n=="object"&&!Array.isArray(n)){let m=await this.parseStatements(n,a,i,o,c);if(m.statements.length>0){let l=new w;l.statement=m.statements,l.unresolvedPredicates=m.unresolved,r.rangeUri&&(l.rangeType=r.rangeUri);let d=new R;return d.predicate=k.parse(t),d.object=l,d}let s=[];for(let[l,d]of Object.entries(n))if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let f=new w;f.name=l,f.sourceKey=l,r.rangeUri&&(f.rangeType=r.rangeUri);let g=await this.parseStatements(d,a,i,o,c);f.statement=g.statements,f.unresolvedPredicates=g.unresolved,s.push(f)}else if(typeof d=="string"){let f=await this.resolveReference(d,a,i);f&&(f.sourceKey=l,s.push(f))}if(s.length>0){let l=new j;return l.predicate=k.parse(t),l.object=s,l}let u=new R;return u.predicate=k.parse(t),u.object=new w,r.rangeUri&&(u.object.rangeType=r.rangeUri),u}}coerceExpressionLiteral(t,n,r){let a=new w,i=new O,o=new k;o.subject=new D("kanonak.org","core-rdf","type"),i.predicate=o;let c=new k;c.subject=new D(r.publisher,r.package_,A.StringLiteral.name,r.version),i.object=c;let m=new M,s=new k;s.subject=new D(r.publisher,r.package_,A.stringLiteral.name,r.version),m.predicate=s,m.object=n,a.statement=[i,m];let u=new R;return u.predicate=k.parse(t),u.object=a,u}async parseListValue(t,n,r,a,i,o,c){let m=[],s=r.propertyType==="DatatypeProperty",u=r.rangeUri?.publisher==="kanonak.org"&&r.rangeUri?.package_==="core-rdf"&&r.rangeUri?.name==="List"||!r.rangeUri&&(r.range?.includes(".")?r.range.substring(r.range.lastIndexOf(".")+1):r.range)==="List";for(let d=0;d<n.length;d++){let f=n[d],g=y=>{y.sourceKey=d,m.push(y)},S=typeof f=="string"||typeof f=="number"||typeof f=="boolean";if(s&&S){let y=typeof f=="string"?f:String(f),b=this.typedListLiteral(y,r);o.isSubstitutableDatatype(r.rangeUri)&&(b.links=await this.resolveMarkdownLinks(y,a,i)),g(b);continue}if(u&&S){if(typeof f=="string"){let y=await i.resolveEntityAsync(f,a);if(y){let b=new k;b.subject=y.uri,g(b)}else{let b=new L;b.value=f,g(b)}}else{let y=new L;y.value=f,g(y)}continue}if(typeof f=="string"){let y=await this.resolveReference(f,a,i);y&&g(y)}else if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let y=new w;r.rangeUri&&(y.rangeType=r.rangeUri);let b=await this.parseStatements(f,a,i,o,c);y.statement=b.statements,y.unresolvedPredicates=b.unresolved,g(y)}}let l=new j;return l.predicate=k.parse(t),l.object=m,l}linkReference(t,n){let r=t.indexOf(".");if(r<=0||!n.metadata?.imports)return;let a=t.substring(0,r),i=t.substring(r+1);for(let[o,c]of Object.entries(n.metadata.imports))for(let m of c){if(!G(m)||(m.alias??m.packageName)!==a)continue;let s=new k,u=m.versionOperator===de.Exact?m.version:void 0;return s.subject=new D(o,m.packageName,i,u),s}}async resolveReference(t,n,r){let a=this.linkReference(t,n);if(a)return a;let i=await r.resolveEntityAsync(t,n);if(i){let c=new k;return c.subject=i.uri,c}let o=n.metadata?.namespace_;if(o){let{KanonakUri:c}=await import("./KanonakUri-4VJGV3FN.js");if(t.includes(".")){let s=t.indexOf("."),u=t.substring(0,s),l=t.substring(s+1);if(n.metadata?.imports){for(let[d,f]of Object.entries(n.metadata.imports))for(let g of f)if((g.alias??g.packageName)===u){let y=new k;return y.subject=new c(d,g.packageName,l,g.version),y}}}let m=new k;return m.subject=new c(o.publisher,o.package_,t,o.version??void 0),m}return null}async saveKanonaks(t,n){let r=new Map;for(let a of t)a instanceof P&&a.namespace&&(r.has(a.namespace)||r.set(a.namespace,[]),r.get(a.namespace).push(a));for(let[a,i]of r){let o=await this.convertKanonaksToDocument(a,i),c=`${a.split("@")[0]}.yml`;await n.saveDocumentAsync(o,c)}}async serializeToYaml(t,n){let r=t.filter(o=>o instanceof P&&o.namespace===n);if(r.length===0)throw new Error(`No kanonaks found with namespace '${n}'`);let a=await this.convertKanonaksToDocument(n,r);return new X().save(a)}async convertKanonaksToDocument(t,n){let a={metadata:{namespace_:t,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of n){let c={};for(let m of o.statement){let[s,u]=this.convertStatementToProperty(m);s&&u!==null&&u!==void 0&&(c[s]=u),this.collectImportsFromStatement(m,t,i)}a.body[o.name]=c}return a}convertStatementToProperty(t){if(t instanceof M)return[t.predicate.subject.name,t.object];if(t instanceof I)return[t.predicate.subject.name,t.object];if(t instanceof T)return[t.predicate.subject.name,t.object];if(t instanceof O)return[t.predicate.subject.name,t.object.subject.name];if(t instanceof j){let n=this.convertKanonakListToValue(t.object);return[t.predicate.subject.name,n]}else if(t instanceof R){let n=this.convertEmbeddedKanonakToValue(t.object);return[t.predicate.subject.name,n]}return[null,null]}convertKanonakListToValue(t){let n=[];for(let r of t)r instanceof k?n.push(r.subject.name):r instanceof w&&n.push(this.convertEmbeddedKanonakToValue(r));return n}convertEmbeddedKanonakToValue(t){let n={};for(let r of t.statement){let[a,i]=this.convertStatementToProperty(r);a&&i!==null&&i!==void 0&&(n[a]=i)}return n}collectImportsFromStatement(t,n,r){}};function F(p,t){p.sourceDoc=t;for(let n of p.statement)if(n instanceof R)F(n.object,t);else if(n instanceof j)for(let r of n.object)r instanceof w&&F(r,t)}function $(p){let t=p.predicate?.subject;return(t?`${t.publisher}/${t.package_}/${t.name}`:"?")+"="+ke(p)}function ke(p){return p instanceof N?"m:"+String(p.object):p instanceof M?"s:"+String(p.object):p instanceof I?"n:"+String(p.object):p instanceof T?"b:"+String(p.object):p instanceof O?"r:"+B(p.object):p instanceof R?"e:"+B(p.object):p instanceof j?"l:["+(p.object??[]).map(B).join("|")+"]":"x"}function B(p){if(!p)return"";if(p instanceof k){let t=p.subject;return"R("+(t?`${t.publisher}/${t.package_}/${t.name}`:"")+")"}return p instanceof w?"E("+(p.statement??[]).map($).join(";")+")":p instanceof L?"L("+String(p.value)+")":"N"}export{re as a,oe as b,pe as c,je as d,ve as e,A as f,K as g,V as h,Me as i,C as j,se as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as b,o as A}from"./chunk-OOYGILH4.js";import{a as P}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-7JBKOJB4.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as F}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,p=r.metadata.namespace_.version;return K(p,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),p=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,p,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=F(n).toString(),s;for(let[m,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&p.metadata.namespace_){s=p.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return F(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as H}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||H(_(),".kanonak","packages")}var w=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as N}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return b(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:N.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as B,readdirSync as V}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of V(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||C(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new P(e);for(let m of C(u))try{let p=e.parse(B(m,"utf-8")),l=p.metadata?.namespace_,h=l?.version;l&&h&&await n.saveDocumentAsync(p,`${l.publisher}/${l.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(m,p,l)=>s.get(`${m}|${p}|${l}`)??null,onFetch:(m,p,l,h)=>{s.set(`${m}|${p}|${l}`,h)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new k(n,o,r)}export{y as a,S as b,D as c,d,w as e,k as f,v as g,C as h,j as i};
|
|
1
|
+
import{n as b,t as A}from"./chunk-HKQTB65D.js";import{a as P}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-7JBKOJB4.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as F}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,p=r.metadata.namespace_.version;return K(p,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),p=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,p,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=F(n).toString(),s;for(let[m,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&p.metadata.namespace_){s=p.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return F(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as H}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||H(_(),".kanonak","packages")}var w=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as N}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return b(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:N.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as B,readdirSync as V}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of V(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||C(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new P(e);for(let m of C(u))try{let p=e.parse(B(m,"utf-8")),l=p.metadata?.namespace_,h=l?.version;l&&h&&await n.saveDocumentAsync(p,`${l.publisher}/${l.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(m,p,l)=>s.get(`${m}|${p}|${l}`)??null,onFetch:(m,p,l,h)=>{s.set(`${m}|${p}|${l}`,h)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new k(n,o,r)}export{y as a,S as b,D as c,d,w as e,k as f,v as g,C as h,j as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{k as $}from"./chunk-22DSABP6.js";import{c as l,d as u,e as b,f as C,g as a,ka as U}from"./chunk-NUTHBBDZ.js";import{c as S,d as j,e as O,f as x,i as I,j as T,k as g,l as v,m as L,n as q}from"./chunk-D4QGPMRW.js";var d=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let r=b(e);return this.all.has(r)?!1:(this.all.add(r),this.tripleList.push(e),h(this.byPIdx,e.p,e),h(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&h(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(b(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let r=this.byPIdx.get(e);return r?r.slice():[]}bySubjectPredicate(e,r){let t=this.bySPIdx.get(`${e}|${r}`);return t?t.slice():[]}byPredicateObject(e,r){let t=this.byPOIdx.get(`${e}|${r}`);return t?t.slice():[]}subjectsWithPredicateObject(e,r){let t=this.byPOIdx.get(`${e}|${r}`);if(!t)return[];let s=new Set;for(let n of t)s.add(n.s);return Array.from(s)}uriObjectsOf(e,r){let t=this.bySPIdx.get(`${e}|${r}`);if(!t)return[];let s=new Set;for(let n of t)n.o.kind==="uri"&&s.add(n.o.key);return Array.from(s)}hasUri(e,r,t){return this.all.has(`${e}|${r}|u:${t}`)}hasTriple(e,r,t){return this.all.has(`${e}|${r}|${C(t)}`)}};function h(o,e,r){let t=o.get(e);t?t.push(r):o.set(e,[r])}var _={name:"rdfs2",apply(o,e){let r=!1;for(let t of o.byPredicate(e.domain)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.byPredicate(s))o.add(a(i.s,e.type,n))&&(r=!0)}return r}},E={name:"rdfs3",apply(o,e){let r=!1;for(let t of o.byPredicate(e.range)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.byPredicate(s))i.o.kind==="uri"&&o.add(a(i.o.key,e.type,n))&&(r=!0)}return r}},A={name:"rdfs5",apply(o,e){let r=!1;for(let t of o.byPredicate(e.subPropertyOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.bySubjectPredicate(n,e.subPropertyOf))i.o.kind==="uri"&&o.add(a(s,e.subPropertyOf,i.o.key))&&(r=!0)}return r}},V={name:"rdfs7",apply(o,e){let r=!1;for(let t of o.byPredicate(e.subPropertyOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicate(s)){let p={s:i.s,p:n,o:i.o};o.add(p)&&(r=!0)}}return r}},W={name:"rdfs9",apply(o,e){let r=!1;for(let t of o.byPredicate(e.subClassOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicateObject(e.type,s))o.add(a(i.s,e.type,n))&&(r=!0)}return r}},F={name:"rdfs11",apply(o,e){let r=!1;for(let t of o.byPredicate(e.subClassOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.bySubjectPredicate(n,e.subClassOf))i.o.kind==="uri"&&o.add(a(s,e.subClassOf,i.o.key))&&(r=!0)}return r}},k=[_,E,A,V,W,F];var N={name:"prp-trp",apply(o,e){let r=!1,t=o.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let s of t){let n=o.byPredicate(s);for(let i of n){if(i.o.kind!=="uri")continue;let p=i.o.key;for(let c of o.bySubjectPredicate(p,s))c.o.kind==="uri"&&i.s!==c.o.key&&o.add(a(i.s,s,c.o.key))&&(r=!0)}}return r}},D={name:"prp-symp",apply(o,e){let r=!1,t=o.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let s of t)for(let n of o.byPredicate(s))n.o.kind==="uri"&&o.add(a(n.o.key,s,n.s))&&(r=!0);return r}},M={name:"prp-inv1",apply(o,e){let r=!1;for(let t of o.byPredicate(e.inverseOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.byPredicate(s))i.o.kind==="uri"&&o.add(a(i.o.key,n,i.s))&&(r=!0)}return r}},z={name:"prp-inv2",apply(o,e){let r=!1;for(let t of o.byPredicate(e.inverseOf)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(a(i.o.key,s,i.s))&&(r=!0)}return r}},B={name:"prp-eqp1",apply(o,e){let r=!1;for(let t of o.byPredicate(e.equivalentProperty)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicate(s))o.add({s:i.s,p:n,o:i.o})&&(r=!0)}return r}},H={name:"prp-eqp2",apply(o,e){let r=!1;for(let t of o.byPredicate(e.equivalentProperty)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicate(n))o.add({s:i.s,p:s,o:i.o})&&(r=!0)}return r}},G={name:"cax-eqc1",apply(o,e){let r=!1;for(let t of o.byPredicate(e.equivalentClass)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicateObject(e.type,s))o.add(a(i.s,e.type,n))&&(r=!0)}return r}},J={name:"cax-eqc2",apply(o,e){let r=!1;for(let t of o.byPredicate(e.equivalentClass)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.byPredicateObject(e.type,n))o.add(a(i.s,e.type,s))&&(r=!0)}return r}},Q={name:"eq-rep-s",apply(o,e){let r=!1;for(let t of o.byPredicate(e.sameAs)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n){for(let i of o.snapshot())i.s===s&&o.add({s:n,p:i.p,o:i.o})&&(r=!0);for(let i of o.snapshot())i.s===n&&o.add({s,p:i.p,o:i.o})&&(r=!0)}}return r}},X={name:"eq-rep-o",apply(o,e){let r=!1;for(let t of o.byPredicate(e.sameAs)){if(t.o.kind!=="uri")continue;let s=t.s,n=t.o.key;if(s!==n)for(let i of o.snapshot())i.o.kind==="uri"&&(i.o.key===s?o.add(a(i.s,i.p,n))&&(r=!0):i.o.key===n&&o.add(a(i.s,i.p,s))&&(r=!0))}return r}},K=[N,D,M,z,B,H,G,J,Q,X];var y=class{constructor(e,r){this.store=e;this.vocabulary=r}store;vocabulary;getInstancesOfClass(e){let r=f(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,r)}getSubclasses(e){let r=f(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,r).filter(s=>s!==r)}getSuperclasses(e){let r=f(e);return this.store.uriObjectsOf(r,this.vocabulary.subClassOf).filter(t=>t!==r)}getTypesOfIndividual(e){return this.store.uriObjectsOf(f(e),this.vocabulary.type)}isInstanceOf(e,r){return this.store.hasUri(f(e),this.vocabulary.type,f(r))}getPropertyClosure(e){let r=f(e),t={},s=new Map;for(let n of this.store.byPredicate(r)){if(n.o.kind!=="uri")continue;let i=s.get(n.s);i||(i=new Set,s.set(n.s,i),t[n.s]=[]),i.has(n.o.key)||(i.add(n.o.key),t[n.s].push(n.o.key))}return t}getPropertyClosures(e){let r={};for(let t of e)r[f(t)]=this.getPropertyClosure(t);return r}triples(){return this.store.snapshot()}size(){return this.store.size()}};function f(o){return typeof o=="string"?o:u(o.publisher,o.package_,o.name)}var P=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new U,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let r=new d,s=await new $().parseKanonaks(e),n=new R;for(let c of s)if(c instanceof S){let m=Y(c);if(!m)continue;for(let w of c.statement)this.emitStatement(m,w,r,n)}let i=[...k];this.profile==="owl-rl-classification"&&i.push(...K);let p=0;for(;p<this.maxIterations;){let c=!1;for(let m of i)m.apply(r,this.vocabulary)&&(c=!0);if(!c)break;p++}return new y(r,this.vocabulary)}emitStatement(e,r,t,s){let n=Z(r);if(n){if(r instanceof I){t.add({s:e,p:n,o:{kind:"literal",lexical:r.object,datatype:"string"}});return}if(r instanceof T){t.add({s:e,p:n,o:{kind:"literal",lexical:String(r.object),datatype:"number"}});return}if(r instanceof g){t.add({s:e,p:n,o:{kind:"literal",lexical:String(r.object),datatype:"boolean"}});return}if(r instanceof v){let i=l(r.object.subject);t.add(a(e,n,i));return}if(r instanceof L){let i=s.next();t.add({s:e,p:n,o:{kind:"blank",id:i}}),this.emitEmbedded(i,r.object,t,s);return}if(r instanceof q){for(let i of r.object??[])this.emitListItem(e,n,i,t,s);return}}}emitListItem(e,r,t,s,n){if(t instanceof O)s.add(a(e,r,l(t.subject)));else if(t instanceof j){let i=n.next();s.add({s:e,p:r,o:{kind:"blank",id:i}}),this.emitEmbedded(i,t,s,n)}else if(t instanceof x){let i=typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":"string";s.add({s:e,p:r,o:{kind:"literal",lexical:String(t.value),datatype:i}})}}emitEmbedded(e,r,t,s){let n=`_:${e}`;for(let i of r.statement)this.emitStatement(n,i,t,s)}},R=class{counter=0;next(){return`b${this.counter++}`}};function Y(o){let e=o.namespace??"",r=e.indexOf("@"),t=r===-1?e:e.substring(0,r),s=t.indexOf("/");if(s===-1)return null;let n=t.substring(0,s),i=t.substring(s+1);return!n||!i||!o.name?null:u(n,i,o.name)}function Z(o){let e=o.predicate;return e?.subject?l(e.subject):null}export{d as a,k as b,K as c,y as d,P as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{g as U,k as B}from"./chunk-22DSABP6.js";import{a as K}from"./chunk-7JBKOJB4.js";import{ga as _}from"./chunk-NUTHBBDZ.js";import{L as N,b as j,c as d,d as m,e as p,f as E,h as R,i as $,j as A,k as v,l as S,m as V,n as g,p as D}from"./chunk-D4QGPMRW.js";import{b as C,e as l}from"./chunk-QILEJIFU.js";import*as P from"js-yaml";import{canonicalForm as Y,canonicalHash as ee}from"@kanonak-protocol/canonical";function k(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}import{CANONICAL_FORM_VERSION as Pe}from"@kanonak-protocol/canonical";function ke(n){return Y(k(n)?n:F(n))}function O(n){return ee(k(n)?n:F(n))}function F(n){let e=[];for(let t of n)t instanceof d&&e.push({uri:se(t),statements:h(t.statement)});return{subjects:e}}function h(n){let e=[];for(let t of n){let r=ie(t);if(!r)continue;if(t instanceof g&&ne(t.predicate.subject)){e.push(...re(t,r));continue}let o=oe(t);o&&e.push({predicate:r,value:o})}return e}function ne(n){let e=_("type");return e!==void 0&&n.name==="type"&&n.publisher===e.publisher&&n.package_===e.package_}var H=new TextEncoder;function te(n,e){let t=H.encode(n),r=H.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function re(n,e){let t=[];for(let r of n.object){if(!(r instanceof p))throw new Error(`canonicalForm: a multi-valued type statement must contain only entity references, got ${r.constructor?.name??typeof r}`);t.push(b(r))}t.sort(te);for(let r=1;r<t.length;r++)if(t[r-1]===t[r])throw new Error(`canonicalForm: duplicate type ${t[r]} in a multi-valued type statement`);return t.map(r=>({predicate:e,value:{ref:r}}))}function oe(n){if(n instanceof R&&n.carrier)return{lit:n.lexical??String(n.object),datatype:z(n.carrier)};if(n instanceof $)return{raw:n.object};if(n instanceof A)return{raw:n.lexical??String(n.object)};if(n instanceof v)return{raw:n.lexical??String(n.object)};if(n instanceof S)return{ref:b(n.object)};if(n instanceof V)return M(n.object);if(n instanceof g)return{list:n.object.map(ae)}}function M(n){let e=h(n.statement);return n.name&&n.name.length>0?{embed:{name:n.name,statements:e}}:{embed:{statements:e}}}function ae(n){if(n instanceof p)return{ref:b(n)};if(n instanceof m)return M(n);if(n instanceof E){if(n.carrier)return{lit:n.lexical??String(n.value),datatype:z(n.carrier)};let e=n.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(n instanceof j)return{embed:{statements:h(n.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function z(n){return n===U.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${n}`}function ie(n){let e=n.predicate;if(e)return L(e.subject)}function se(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function b(n){return L(n.subject)}function L(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}import{VersionOperator as T}from"@kanonak-protocol/types/document/models/enums";var ce="0.0.0",w=class{constructor(e,t=new K,r){this.repository=e;this.parser=t;this.objectParser=r??new B(this.parser)}repository;parser;objectParser;imports(){return new f}serializeValue(e,t){return G(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Z(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:W(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:W(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return P.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[q]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(P.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new N(a,this.repository))).filter(u=>u instanceof d&&u.namespace===i&&u.name!==q);for(let u of c)u.namespace="ephemeral";return O(c)}},q="__pkgbuilder_probe__";function W(n){return new TextEncoder().encode(n).length}function Z(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var f=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=T.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,l(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,ce,o??t,T.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:C(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=J(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function G(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>G(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof m)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(ue(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function J(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ue(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var I=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${l(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=D(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Q={async authorize(){return{allowed:!0}}},X={async record(){}},y=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},x=class{inner;ctx;policy;meter;constructor(e,t,r=Q,o=X){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new y(e,t.reason)}};export{ke as a,O as b,Pe as c,w as d,Z as e,f,J as g,I as h,Q as i,X as j,y as k,x as l};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{j as A}from"./chunk-22DSABP6.js";import{a as E}from"./chunk-7JBKOJB4.js";import{na as $}from"./chunk-NUTHBBDZ.js";import{c as V,d as I,e as N,f as x,g as U,l as W,m as J,n as _,o as B}from"./chunk-D4QGPMRW.js";var R=class{propertyUri;propertyType;range;rangeUri;isImported;definedInNamespace};import{parseDocument as H,LineCounter as Q,isMap as b,isPair as f,isScalar as l,isSeq as j}from"yaml";var L=class r{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let n=new r,t=new Q,o=H(e,{lineCounter:t});if(o.errors.length>0||!b(o.contents))return n;O(o.contents,[],t,n);for(let i of o.contents.items){if(!f(i)||!l(i.key))continue;let s=String(i.key.value),u=i.key.range;if(!u)continue;n.entities.set(s,g(u,t));let a=i.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?n.entityBlocks.set(s,g([u[0],u[1],c[2]],t)):n.entityBlocks.set(s,g(u,t)),b(i.value)){let k=new Map,d=new Map,p=new Map;for(let S of i.value.items){if(!f(S)||!l(S.key))continue;let h=String(S.key.value),m=S.key.range;m&&k.set(h,g(m,t));let P=S.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let v=P.range;d.set(h,g(v,t))}if(j(P)){let v=[];for(let K of P.items)K&&typeof K=="object"&&"range"in K&&Array.isArray(K.range)&&v.push(g(K.range,t));v.length>0&&p.set(h,v)}}k.size>0&&n.properties.set(s,k),d.size>0&&n.propertyValues.set(s,d),p.size>0&&n.valueListItems.set(s,p);let y=Y(i.value,t);y.length>0&&n.importPackages.set(s,y)}}return n}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,n){for(let[t,o]of this.entityBlocks)if(C(o,e,n))return t}findPropertyAtPosition(e,n){let t=this.findEntityAtPosition(e,n);if(!t)return;let o=this.properties.get(t),i=this.propertyValues.get(t);if(!o&&!i)return{entityName:t};let s,u;if(i)for(let[a,c]of i)C(c,e,n)&&(!u||q(c,u))&&(s=a,u=c);if(o)for(let[a,c]of o)C(c,e,n)&&(!u||q(c,u))&&(s=a,u=c);return s?{entityName:t,propertyName:s}:{entityName:t}}getPropertyPosition(e,n){return this.properties.get(e)?.get(n)}getPropertyValuePosition(e,n){return this.propertyValues.get(e)?.get(n)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[n,t]of this.importPackages)for(let o of t)e.push({entityName:n,entry:o});return e}findPropertySourceName(e,n){let t=this.properties.get(e);if(t){if(t.has(n))return n;for(let o of t.keys()){let i=o.lastIndexOf(".");if((i===-1?o:o.substring(i+1))===n)return o}}}getListItemPosition(e,n,t){let o=this.valueListItems.get(e)?.get(n);if(!(!o||t<0||t>=o.length))return o[t]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,n){this.nestedKeys.set(e,n)}setNestedValuePosition(e,n){this.nestedValues.set(e,n)}getMostSpecificPosition(e,n,t){if(e){if(n!==void 0){if(t!==void 0){let s=this.getListItemPosition(e,n,t);if(s)return s}let o=this.getPropertyValuePosition(e,n);if(o)return o;let i=this.getPropertyPosition(e,n);if(i)return i}return this.getEntityPosition(e)}}};function Y(r,e){let n=[];if(!b(r))return n;let t=r.items.find(o=>f(o)&&l(o.key)&&String(o.key.value)==="imports");if(!t||!f(t)||!j(t.value))return n;for(let o of t.value.items){if(!b(o))continue;let i=o.items.find(a=>f(a)&&l(a.key)&&String(a.key.value)==="publisher");if(!i||!f(i)||!l(i.value))continue;let s=String(i.value.value),u=o.items.find(a=>f(a)&&l(a.key)&&String(a.key.value)==="packages");if(!(!u||!f(u)||!j(u.value)))for(let a of u.value.items){if(!b(a))continue;let c=a.items.find(m=>f(m)&&l(m.key)&&String(m.key.value)==="package");if(!c||!f(c)||!l(c.value)||!c.value.range)continue;let k=String(c.value.value),d=a.items.find(m=>f(m)&&l(m.key)&&String(m.key.value)==="version"),p=d&&f(d)&&l(d.value)?String(d.value.value):"",y=a.items.find(m=>f(m)&&l(m.key)&&String(m.key.value)==="alias"),S=y&&f(y)&&l(y.value)?String(y.value.value):void 0,h=S!==void 0?{publisher:s,package_:k,version:p,alias:S,position:g(c.value.range,e)}:{publisher:s,package_:k,version:p,position:g(c.value.range,e)};n.push(h)}}return n}function C(r,e,n){return!(e<r.line||e>r.endLine||e===r.line&&n<r.column||e===r.endLine&&n>r.endColumn)}function q(r,e){let n=r.endLine-r.line,t=e.endLine-e.line;if(n!==t)return n<t;let o=r.endLine===r.line?r.endColumn-r.column:Number.MAX_SAFE_INTEGER,i=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return o<i}function O(r,e,n,t){if(b(r)){for(let o of r.items){if(!f(o)||!l(o.key))continue;let i=String(o.key.value),s=[...e,i],u=JSON.stringify(s);o.key.range&&t.setNestedKeyPosition(u,g(o.key.range,n));let a=o.value,c=z(a);c&&t.setNestedValuePosition(u,g(c,n)),O(a,s,n,t)}return}if(j(r)){for(let o=0;o<r.items.length;o++){let i=r.items[o],s=[...e,o],u=JSON.stringify(s),a=z(i);a&&t.setNestedValuePosition(u,g(a,n)),O(i,s,n,t)}return}}function z(r){if(!r||typeof r!="object"||!("range"in r))return;let e=r.range;return Array.isArray(e)&&e.length>=3?e:void 0}function g(r,e){let n=e.linePos(r[0]),t=e.linePos(r[2]);return{line:n.line-1,column:n.col-1,endLine:t.line-1,endColumn:t.col-1}}function Z(r,e){let t=(e??new E).parse(r),o=L.fromContent(r);return{document:t,positions:o}}function T(r,e,n,t,o){if(e<t.line||e>t.endLine||e===t.line&&n<t.column||e===t.endLine&&n>=t.endColumn)return;let i=M(o,t.line,t.column),s=M(o,t.endLine,t.endColumn);if(i<0||s<0)return;let u=o.substring(i,s),a=A(u);if(a.length!==r.links.length)return;let c=e-t.line,k=e===t.line?n-t.column:n,d=M(u,c,k);if(!(d<0))for(let p=0;p<a.length;p++){let y=a[p];if(d>=y.startOffset&&d<y.endOffset)return r.links[p]}}function G(r,e){let n=M(e,r.line,r.column),t=M(e,r.endLine,r.endColumn);if(n<0||t<0)return;let o=e.substring(n,t);return A(o).map(i=>{let s=F(e,n+i.startOffset),u=F(e,n+i.endOffset);return{line:s.line,column:s.column,endLine:u.line,endColumn:u.column}})}function F(r,e){let n=0,t=0;for(let o=0;o<e&&o<r.length;o++)r[o]===`
|
|
2
2
|
`&&(n++,t=o+1);return{line:n,column:e-t}}function M(r,e,n){let t=0,o=0;for(let i=0;i<r.length;i++){if(t===e)return Math.min(o+n,r.length);r[i]===`
|
|
3
3
|
`&&(t++,o=i+1)}return t===e?Math.min(o+n,r.length):-1}function ee(r,e,n){let t=[];for(let o of r){if(!(o instanceof V)||typeof o.sourceKey!="string")continue;let i=[o.sourceKey],s=$(o);s&&t.push({role:"subject",uri:s,range:w(e.getEntityPosition(o.sourceKey),i,"key"),path:i}),D(o.statement,i,e,n,t)}return t}function ne(r,e,n){let t;for(let o of r)te(o.range,e,n)&&(!t||oe(o.range,t.range))&&(t=o);return t}function D(r,e,n,t,o){for(let i of r){if(!(i instanceof U)||i.sourceKey===void 0)continue;let s=[...e,i.sourceKey],u=i.predicate?.subject;if(u&&o.push({role:"predicate",uri:u,range:w(n.getNodeKeyPosition(s),s,"key"),path:s}),i instanceof W)o.push({role:"reference",uri:i.object.subject,range:w(n.getNodeValuePosition(s),s,"value"),path:s});else if(i instanceof B)X(i.links,s,n,t,o);else if(i instanceof J)i.object&&D(i.object.statement,s,n,t,o);else if(i instanceof _)for(let a of i.object??[]){if(!(a instanceof N||a instanceof I||a instanceof x)||a.sourceKey===void 0)continue;let c=[...s,a.sourceKey];a instanceof N?o.push({role:"reference",uri:a.subject,range:w(n.getNodeValuePosition(c),c,"value"),path:c}):a instanceof I?D(a.statement,c,n,t,o):a.links&&X(a.links,c,n,t,o)}}}function X(r,e,n,t,o){if(t===void 0||r.length===0)return;let i=G(w(n.getNodeValuePosition(e),e,"value"),t);if(!i||i.length!==r.length)throw new Error(`sourceSymbols: the prose value at ${JSON.stringify(e)} has ${r.length} resolved [[reference]](s) but ${i?.length??0} in its source text \u2014 the source text is not the text this document was parsed from.`);r.forEach((s,u)=>{s.target&&o.push({role:"reference",uri:s.target.subject,range:i[u],path:e})})}function w(r,e,n){if(!r)throw new Error(`sourceSymbols: no source ${n} position for ${JSON.stringify(e)}. The object model has a node the position index does not \u2014 the positions were not built from the text this document was parsed from.`);return r}function te(r,e,n){return!(e<r.line||e>r.endLine||e===r.line&&n<r.column||e===r.endLine&&n>r.endColumn)}function oe(r,e){let n=r.endLine-r.line,t=e.endLine-e.line;return n!==t?n<t:r.endColumn-r.column<e.endColumn-e.column}export{R as a,L as b,Z as c,T as d,ee as e,ne as f};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as k}from"./chunk-SC5M74NM.js";import{a as A}from"./chunk-7JBKOJB4.js";import{e as m,g as R,j as x}from"./chunk-QILEJIFU.js";var F=class extends Error{constructor(t,n,r,s,i){super(t);this.url=n;this.status=r;this.problem=s;this.retryAfterSeconds=i;this.name="KanonakHttpError"}url;status;problem;retryAfterSeconds},E=300;async function u(o,e,t){let n=await $(t),r=y(t.headers.get("retry-after")),s=`Failed to fetch ${o}: ${e} ${await M(t)}`;return new F(s,e,t.status,n,r)}async function M(o){let e=await $(o),t=y(o.headers.get("retry-after")),n=e?O(e):await S(o),r=`(${o.status}${o.statusText?` ${o.statusText}`:""})`;return n&&(r+=`: ${n}`),t!==void 0&&(r+=` [the server asks to retry after ${t}s]`),r}function y(o){if(!o)return;let e=o.trim();if(/^\d+$/.test(e))return Number(e);let t=Date.parse(e);if(!Number.isNaN(t))return Math.max(0,Math.ceil((t-Date.now())/1e3))}function L(o){return(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase()}async function $(o){if(L(o)!=="application/problem+json")return;let e;try{e=await o.clone().json()}catch{return}if(!e||typeof e!="object")return;let t=e,n={};return typeof t.type=="string"&&(n.type=t.type),typeof t.title=="string"&&(n.title=t.title),typeof t.status=="number"&&(n.status=t.status),typeof t.detail=="string"&&(n.detail=t.detail),typeof t.instance=="string"&&(n.instance=t.instance),n}function O(o){return[o.title,o.detail].filter(e=>!!e&&e.trim()!=="").join(" \u2014 ")}async function S(o){let e=L(o);if(e!=="text/plain"&&e!=="application/json")return"";let t;try{t=await o.clone().text()}catch{return""}let n=t.replace(/\s+/g," ").trim();return n.length>E?`${n.slice(0,E)}\u2026`:n}var h=class extends Error{constructor(e){super(e),this.name="CredentialError"}};var H="@kanonak-protocol/sdk (+https://kanonak.org)",P=H;function ee(o){P=o}function te(){return P}function p(o){let e;try{e=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(e.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${e.href} (only https:// is supported).`)}var j=new Set([429,502,503,504]),q=4,N=500,_=2e4;function g(o,e){p(o);let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",P),B(o,{...e,headers:t})}var w=q;function ne(o){w=Math.max(0,o)}async function B(o,e){let t;for(let n=0;n<=w;n++){let r;try{r=await fetch(o,e)}catch(i){if(t=i,n>=w)throw i;await D(b(n,void 0));continue}if(!j.has(r.status)||n>=w)return r;let s=y(r.headers.get("retry-after"));if(s!==void 0&&s*1e3>_)return r;await D(b(n,s))}throw t??new Error("kanonakFetch: exhausted retries")}function b(o,e){if(e!==void 0)return e*1e3;let t=Math.min(_,N*2**o);return Math.floor(t/2+Math.random()*(t/2))}function D(o){return new Promise(e=>setTimeout(e,o))}var V="https://{publisher}/{package}/{version}.kan.yml",U={version:1};function ae(){return{version:1}}var v=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(t,e):g(t))}catch(i){if(i instanceof h)throw i;return U}if(n.status===404)return U;if(!n.ok)throw await u("publisher config",t,n);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(W(t,"package_url_template",r.package_url_template),s.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(i=>typeof i=="string")&&(s.featured_packages=r.featured_packages),s}resolvePackageUrl(e,t,n,r){let s=r.package_url_template??V,i=G(s,{publisher:e,package:t,version:n});return p(i),i}};function W(o,e,t){if(!t.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${e} must be an absolute https:// URL template (got "${t}").`)}function G(o,e){let t=o;for(let[r,s]of Object.entries(e))t=t.replaceAll(`{${r}}`,s);let n=t.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return t}import K from"js-yaml";function ue(o,e,t){return o.packages[`${e}/${t}`]?.version}var X=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
2
|
+
`,z="sha256:";function I(o){let e=K.load(o);return!e||typeof e!="object"||e.version!=="1"?null:{version:"1",lastUpdated:e.lastUpdated??"",packages:e.packages??{}}}function ge(o){let e={};for(let n of Object.keys(o.packages).sort())e[n]=o.packages[n];let t=K.dump({...o,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return X+t}async function fe(o){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),t=Array.from(new Uint8Array(e),n=>n.toString(16).padStart(2,"0")).join("");return`${z}${t}`}var d=class{configResolver;fetchFn;lockCache=new Map;packageLockCache=new Map;constructor(e){this.configResolver=e?.configResolver??new v(e?.fetchFn),this.fetchFn=e?.fetchFn}getConfig(e){return this.configResolver.getConfig(e)}async getPackageUrl(e,t,n){let r=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,n,r)}getLock(e){let t=this.lockCache.get(e);return t||(t=this.fetchLock(e),this.lockCache.set(e,t),t.catch(()=>{this.lockCache.get(e)===t&&this.lockCache.delete(e)})),t}async getPackageLockEntry(e,t){let n=`${e}/${t}`,r=this.packageLockCache.get(n);return r||(r=this.fetchLock(e,t),this.packageLockCache.set(n,r),r.catch(()=>{this.packageLockCache.get(n)===r&&this.packageLockCache.delete(n)})),(await r)?.packages[n]??null}async fetchLock(e,t){let n=t?`https://${e}/${t}/kanonak.lock`:`https://${e}/kanonak.lock`,r;try{r=this.fetchFn?await this.fetchFn(n,e):await g(n)}catch(s){if(s instanceof h)throw s;return null}if(r.status===404)return null;if(!r.ok)throw await u("publisher lock",n,r);return I(await r.text())}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";function Y(o,e){let t=R(o);return t?x(t,e):!1}var T=class{parser=new A;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new d({fetchFn:e.fetchFn}):new d}async getHighestCompatibleVersionAsync(e,t){if(t.versionOperator===C.Exact){let s=await this.fromMemoOrCache(e,t.packageName,m(t.version));if(s)return s}let r=(await this.publisherIndex.getLock(e))?.packages[`${e}/${t.packageName}`]??await this.publisherIndex.getPackageLockEntry(e,t.packageName)??void 0;return r&&Y(r.version,t)?this.fetchPinned(e,t.packageName,r):r&&t.versionOperator!==C.Exact?null:this.resolveByDirectFetch(e,t)}async fetchPinned(e,t,n){let r=n.version,s=`${e}/${t}@${r}`,i=await this.fromMemoOrCache(e,t,r);if(i)return i;let a=n.resolved,c=this.fetchFn?await this.fetchFn(a,e):await g(a);if(!c.ok)throw await u("Kanonak package",a,c);let l=await c.text(),f=this.parser.parse(l);return k(f,e,t,r),this.onFetch&&await this.onFetch(e,t,r,l),this.documents.set(s,f),this.contentCache.set(s,l),f}async fromMemoOrCache(e,t,n){let r=`${e}/${t}@${n}`,s=this.documents.get(r);if(s)return s;if(!this.getFromCache)return null;let i=await this.getFromCache(e,t,n);if(i==null)return null;let a;try{a=this.parser.parse(i),k(a,e,t,n)}catch(c){throw new Error(`Cached content for ${r} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(r,a),this.contentCache.set(r,i),a}async resolveByDirectFetch(e,t){let n=t.packageName,s=t.versionOperator===C.Exact?await this.publisherIndex.getPackageUrl(e,n,m(t.version)):`https://${e}/${n}.kan.yml`,i=await this.fetchFollowing(s,e);if(!i)return null;let a=this.parser.parse(i.content),c=a.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${n}`);let l=m(c.version);k(a,e,n,l);let f=`${e}/${n}@${l}`;return this.onFetch&&await this.onFetch(e,n,l,i.content),this.documents.set(f,a),this.contentCache.set(f,i.content),a}async fetchFollowing(e,t,n=4){let r=e;for(let s=0;s<n;s++){p(r);let i=this.fetchFn?await this.fetchFn(r,t):await g(r,{redirect:"manual"});if(i.status===301||i.status===302){let a=i.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(a,r).toString();continue}if(i.status===404)return null;if(!i.ok)throw await u("Kanonak package",r,i);return{url:r,content:await i.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===e&&r.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,n,r,s]=t;return this.publisherIndex.getPackageUrl(n,r,s)}};export{F as a,u as b,M as c,y as d,h as e,H as f,ee as g,te as h,p as i,g as j,ne as k,ae as l,v as m,ue as n,z as o,I as p,ge as q,fe as r,d as s,T as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Pt}from"./chunk-VORVR5BZ.js";import{c as wt,g as Ut,h as ct,i as pt,j as At,k as Nt,l as Tt,s as lt,t as xt,u as _t}from"./chunk-EG47OOJC.js";import{a as F,e as z,h as Ct,j as O}from"./chunk-3353RWDC.js";import{a as Vt}from"./chunk-7JBKOJB4.js";import{$ as ne,_ as st,aa as $t,b as vt,ba as It,fa as nt,ga as jt,ma as j,na as x,oa as H,pa as q,qa as Q,ta as Ot,ua as Y,va as pe}from"./chunk-NUTHBBDZ.js";import{A as St,C as W,D as ee,E as te,F as E,G as C,H as T,L as B,c as k,d as V,e as N,f as tt,l as ce,m as J,n as L,o as ot,r as R,s as Z,u as Dt,v as M,w as oe,x as A,z as b}from"./chunk-D4QGPMRW.js";import{a as Et}from"./chunk-FUUTGGJS.js";import{b as se,c as Kt}from"./chunk-F67UH4FD.js";import{e as U}from"./chunk-QILEJIFU.js";var le=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var K=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(K||{});var d=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var mt=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var re=class{constructor(e){this.underlying=e;this.repository=new ut(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e=await this.underlying.getAllDocumentsAsync();await Pt(e,this.repository);let t={};return{merged:await new O().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},ut=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function $(p,e,t){return t?t.getKanonaks():new O().parseKanonaks(new me(p,e))}async function P(p,e,t){let o=await $(p,e,t),n=rt(p);return n?o.filter(r=>r instanceof k&&r.namespace===n):[]}async function ue(p,e,t){let o=rt(p);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new O().parseKanonaks(new me(p,e),r),n=r.authored??[]}return n.filter(r=>r instanceof k&&r.sourceDoc===o)}function rt(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var me=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var de=class{constructor(e={}){this.options=e}options;ruleName="LinkTarget";async validateAsync(e,t,o){let n=[],r=new Map;for(let[s,l]of Object.entries(e.metadata?.imports??{}))for(let m of l)se(m)&&r.set(`${s}/${m.packageName}`,{publisher:s,import_:m});if(r.size===0)return n;let a=new Map,i=(s,l,m)=>{let u=`${s.publisher}/${s.package_}`;if(!r.has(u))return;let f=a.get(u)??[];f.push({uri:s,where:l,predicate:m}),a.set(u,f)},c=await P(e,t,o);F(c,({kanonak:s,path:l})=>{for(let m of s.statement){let u=m.predicate?.subject?.name??"(unknown)";if(m instanceof ce)i(m.object.subject,l,u);else if(m instanceof L)for(let f of m.object)f instanceof N&&i(f.subject,l,u);else if(m instanceof ot)for(let f of m.links)f.target&&i(f.target.subject,l,u)}});for(let[s,l]of a){let{publisher:m,import_:u}=r.get(s),f=null,h;try{f=await t.getHighestCompatibleVersionAsync(m,u)}catch(y){h=y instanceof Error?y.message:String(y)}if(!f){let y=l[0],g=`${l.length} reference${l.length===1?"":"s"}, first at '${y.where}.${y.predicate}'`;this.options.offline?n.push(this.finding("Warning",y.where,y.predicate,s,`Link target package '${s}' could not be resolved offline (${g}); the link is UNVERIFIED, not known to be broken.`,"Run without --offline to verify the link over HTTP, or add the package to the workspace or cache.")):n.push(this.finding("Error",y.where,y.predicate,s,`Link target package '${s}' could not be resolved${h?` (${h})`:""} \u2014 ${g}.`,"Check the publisher and package name of the link import; a link must dereference even though it is not a dependency. Use --offline to validate without the network (the link is then reported as unverified)."));continue}for(let{uri:y,where:g,predicate:D}of l)Object.prototype.hasOwnProperty.call(f.body,y.name)||n.push(this.finding("Error",g,D,`${s}/${y.name}`,`Link to '${y.name}' in '${D}' at '${g}' does not dereference: package '${s}' (resolved to ${f.metadata.namespace_?.toString()??s}) defines no resource named '${y.name}'.`,`Check for a typo, or a resource renamed or removed in '${s}'; a link addresses a resource by name in its package's current version unless the import is pinned with '='.`))}return n}finding(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.actualValue=n,i.expectedValue="A link that dereferences to a resource its target package defines",i.message=r,i.suggestion=a,i}};var fe=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):[A-Za-z_][A-Za-z0-9_.-]*$/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&p.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),c=e.split(".")[0],s=new d;s.ruleType=this.ruleName,s.severity="Error",s.entityName=c,s.propertyName=e,s.actualValue=n,s.expectedValue=i,s.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var ye=class p{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=p.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&p.RESERVED_WORDS.has(n.toLowerCase())){let i=new d;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!p.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${i}`,c.suggestion=i,t.push(c)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new d;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var he=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let c=[];if(Array.isArray(i))for(let s of i){let l=s?.toString();l&&l==="Property"&&!o&&c.push(l)}else{let s=i?.toString();s&&s==="Property"&&!o&&c.push(s)}for(let s of c){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),u=new d;u.ruleType=this.ruleName,u.severity="Error",u.entityName=n,u.propertyName="type",u.actualValue=s,u.expectedValue=m,u.message=`Invalid property type '${s}'. Use '${m}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ke=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=o,c.propertyName="type",c.message=`Subject Kanonak '${o}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
|
|
1
|
+
import{a as Pt}from"./chunk-VORVR5BZ.js";import{c as wt,g as Ut,h as ct,i as pt,j as At,k as Nt,l as Tt,s as lt,t as xt,u as _t}from"./chunk-TYVZXABI.js";import{a as F,f as z,i as Ct,k as O}from"./chunk-22DSABP6.js";import{a as Vt}from"./chunk-7JBKOJB4.js";import{$ as ne,_ as st,aa as $t,b as vt,ba as It,fa as nt,ga as jt,ma as j,na as x,oa as H,pa as q,qa as Q,ta as Ot,ua as Y,va as pe}from"./chunk-NUTHBBDZ.js";import{A as St,C as W,D as ee,E as te,F as E,G as C,H as T,L as B,c as k,d as V,e as N,f as tt,l as ce,m as J,n as L,o as ot,r as R,s as Z,u as Dt,v as M,w as oe,x as A,z as b}from"./chunk-D4QGPMRW.js";import{a as Et}from"./chunk-FUUTGGJS.js";import{b as se,c as Kt}from"./chunk-F67UH4FD.js";import{e as U}from"./chunk-QILEJIFU.js";var le=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var K=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(K||{});var d=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var mt=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var re=class{constructor(e){this.underlying=e;this.repository=new ut(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e=await this.underlying.getAllDocumentsAsync();await Pt(e,this.repository);let t={};return{merged:await new O().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},ut=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function $(p,e,t){return t?t.getKanonaks():new O().parseKanonaks(new me(p,e))}async function P(p,e,t){let o=await $(p,e,t),n=rt(p);return n?o.filter(r=>r instanceof k&&r.namespace===n):[]}async function ue(p,e,t){let o=rt(p);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new O().parseKanonaks(new me(p,e),r),n=r.authored??[]}return n.filter(r=>r instanceof k&&r.sourceDoc===o)}function rt(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var me=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var de=class{constructor(e={}){this.options=e}options;ruleName="LinkTarget";async validateAsync(e,t,o){let n=[],r=new Map;for(let[s,l]of Object.entries(e.metadata?.imports??{}))for(let m of l)se(m)&&r.set(`${s}/${m.packageName}`,{publisher:s,import_:m});if(r.size===0)return n;let a=new Map,i=(s,l,m)=>{let u=`${s.publisher}/${s.package_}`;if(!r.has(u))return;let f=a.get(u)??[];f.push({uri:s,where:l,predicate:m}),a.set(u,f)},c=await P(e,t,o);F(c,({kanonak:s,path:l})=>{for(let m of s.statement){let u=m.predicate?.subject?.name??"(unknown)";if(m instanceof ce)i(m.object.subject,l,u);else if(m instanceof L)for(let f of m.object)f instanceof N&&i(f.subject,l,u);else if(m instanceof ot)for(let f of m.links)f.target&&i(f.target.subject,l,u)}});for(let[s,l]of a){let{publisher:m,import_:u}=r.get(s),f=null,h;try{f=await t.getHighestCompatibleVersionAsync(m,u)}catch(y){h=y instanceof Error?y.message:String(y)}if(!f){let y=l[0],g=`${l.length} reference${l.length===1?"":"s"}, first at '${y.where}.${y.predicate}'`;this.options.offline?n.push(this.finding("Warning",y.where,y.predicate,s,`Link target package '${s}' could not be resolved offline (${g}); the link is UNVERIFIED, not known to be broken.`,"Run without --offline to verify the link over HTTP, or add the package to the workspace or cache.")):n.push(this.finding("Error",y.where,y.predicate,s,`Link target package '${s}' could not be resolved${h?` (${h})`:""} \u2014 ${g}.`,"Check the publisher and package name of the link import; a link must dereference even though it is not a dependency. Use --offline to validate without the network (the link is then reported as unverified)."));continue}for(let{uri:y,where:g,predicate:D}of l)Object.prototype.hasOwnProperty.call(f.body,y.name)||n.push(this.finding("Error",g,D,`${s}/${y.name}`,`Link to '${y.name}' in '${D}' at '${g}' does not dereference: package '${s}' (resolved to ${f.metadata.namespace_?.toString()??s}) defines no resource named '${y.name}'.`,`Check for a typo, or a resource renamed or removed in '${s}'; a link addresses a resource by name in its package's current version unless the import is pinned with '='.`))}return n}finding(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.actualValue=n,i.expectedValue="A link that dereferences to a resource its target package defines",i.message=r,i.suggestion=a,i}};var fe=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):[A-Za-z_][A-Za-z0-9_.-]*$/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&p.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),c=e.split(".")[0],s=new d;s.ruleType=this.ruleName,s.severity="Error",s.entityName=c,s.propertyName=e,s.actualValue=n,s.expectedValue=i,s.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var ye=class p{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=p.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&p.RESERVED_WORDS.has(n.toLowerCase())){let i=new d;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!p.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${i}`,c.suggestion=i,t.push(c)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new d;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var he=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let c=[];if(Array.isArray(i))for(let s of i){let l=s?.toString();l&&l==="Property"&&!o&&c.push(l)}else{let s=i?.toString();s&&s==="Property"&&!o&&c.push(s)}for(let s of c){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),u=new d;u.ruleType=this.ruleName,u.severity="Error",u.entityName=n,u.propertyName="type",u.actualValue=s,u.expectedValue=m,u.message=`Invalid property type '${s}'. Use '${m}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ke=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=o,c.propertyName="type",c.message=`Subject Kanonak '${o}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
|
|
2
2
|
type: Scene
|
|
3
3
|
|
|
4
4
|
Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(c)}}return t}};var lo=new Set(["EphemeralPackage"]),ge=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!lo.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as I,b as K,c as ee,e as T,j}from"./chunk-HKQTB65D.js";import{k as re}from"./chunk-22DSABP6.js";import{ma as _,pa as z}from"./chunk-NUTHBBDZ.js";import{c as G,o as te}from"./chunk-D4QGPMRW.js";var se=(i=>(i.Class="Class",i.DatatypeProperty="DatatypeProperty",i.ObjectProperty="ObjectProperty",i.AnnotationProperty="AnnotationProperty",i.Instance="Instance",i.Datatype="Datatype",i.Shape="Shape",i.Unknown="Unknown",i))(se||{}),ae=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(ae||{}),H=class{static async buildFromRepository(e,r){let s=await new re().parseKanonaks(e),o=await e.getAllDocumentsAsync(),c=[],p=[],i=new Set,h=new Set,b=new Map;for(let g of s){let a=g;if(a.name&&(_.isClassType(a)&&i.add(a.name),g instanceof G)){let d=z(s,g);(d==="ObjectProperty"||d==="Property")&&h.add(a.name)}}for(let g of o)for(let[a,d]of Object.entries(g.body))h.has(a)&&d?.range&&typeof d.range=="string"&&b.set(a,d.range);let w=new Map;for(let g of s){let a=g;a.name&&w.set(a.name,a)}for(let g of o){let a=g.metadata.namespace_,d=a?`${a.publisher}/${a.package_}`:"",u=a?.version?`${a.version.major}.${a.version.minor}.${a.version.patch}`:"",y=ne(g);for(let[f,l]of Object.entries(g.body)){if(!l||typeof l!="object")continue;let A=w.get(f),m="Unknown";if(A){let E=A,k=A instanceof G?z(s,A):void 0;_.isClassType(E)?m="Class":k==="ObjectProperty"?m="ObjectProperty":k==="DatatypeProperty"?m="DatatypeProperty":k==="AnnotationProperty"?m="AnnotationProperty":_.isDatatypeType(E)?m="Datatype":k==="Property"?m="ObjectProperty":_.isShapeType(E)?m="Shape":_.isInstanceOfKnownClass(E,i)&&(m="Instance")}let C=d&&u?`${d}/${f}@${u}`:f,R={};for(let[E,k]of Object.entries(l))E!=="type"&&(typeof k!="object"||k===null)&&(R[E]=k);c.push({id:C,label:l.label??f,type:m,namespace:d,properties:R}),oe(C,l,m,i,h,p,d,u,y,r),q(C,l,h,b,c,p,d,u,y),Ce(C,A,p)}}return{nodes:c,edges:p}}static buildFromDocument(e,r){let n=[],s=[],o=e.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",i=new Set,h=new Set,b=new Map,w=ne(e);for(let[d,u]of Object.entries(e.body)){let y=u?.type;y&&(be(y,w)&&i.add(d),Pe(y,w)&&(h.add(d),u.range&&typeof u.range=="string"&&b.set(d,u.range)))}for(let[d,u]of Object.entries(e.body)){if(!u||typeof u!="object")continue;let y=u.type,f=Ae(y,d,i,w),l=p&&c?`${p}/${d}@${c}`:d,A={};for(let[m,C]of Object.entries(u))m!=="type"&&(typeof C!="object"||C===null)&&(A[m]=C);n.push({id:l,label:u.label??d,type:f,namespace:p,properties:A}),oe(l,u,f,i,h,s,p,c,w,r),q(l,u,h,b,n,s,p,c,w)}let g=new Set(n.map(d=>d.id)),a=s.filter(d=>g.has(d.source)&&g.has(d.target));return{nodes:n,edges:a}}};function ne(t,e){let r=new Map;if(t.metadata?.imports)for(let[n,s]of Object.entries(t.metadata.imports))for(let o of s){let c=o.alias??o.packageName,p=o.version,i=`${p.major}.${p.minor}.${p.patch}`;r.set(c,{publisher:n,package_:o.packageName,version:i})}return r}var ie={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ke=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(t,e){if(t.includes(".")){let r=t.indexOf("."),n=t.substring(0,r),s=t.substring(r+1),o=e.get(n);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function be(t,e){let r=W(t,e);return r?ie[r]==="Class":!1}function Pe(t,e){let r=W(t,e);return r?ke.has(r):!1}function Ae(t,e,r,n){if(!t||t==="Package")return"Unknown";let s=W(t,n);if(s){let c=ie[s];if(c)return c;let p=s.split("/").pop()?.split("@")[0]??"";return r.has(p)?"Instance":"Unknown"}let o=t.split(".").pop()??t;return r.has(o)?"Instance":"Unknown"}var ce=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function oe(t,e,r,n,s,o,c,p,i,h){let b=e.type,w=e.subClassOf;if(w){let f=Array.isArray(w)?w:[w];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subClassOf",label:"subClassOf"})}let g=e.subPropertyOf;if(g){let f=Array.isArray(g)?g:[g];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subPropertyOf",label:"subPropertyOf"})}let a=e.domain,d=e.range;if(h?.includePropertyEdges){let f=[[a,"domain","domain"],[d,"range","range"]];for(let[l,A,m]of f)if(l!=null)for(let C of Array.isArray(l)?l:[l])typeof C=="string"&&o.push({source:t,target:O(C,c,p,i),type:A,label:m})}if(r==="Instance"&&b){let f=b.split(".").pop()??b;o.push({source:t,target:O(f,c,p,i),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[f,l]of Object.entries(e)){if(ce.has(f)||!s.has(f))continue;let A=Array.isArray(l)?l:[l];for(let m of A)typeof m=="string"&&Ee(m)&&o.push({source:t,target:O(m,c,p,i),type:"propertyValue",label:f,propertyId:O(f,c,p,i)})}if((r==="ObjectProperty"||r==="DatatypeProperty"||a&&d)&&a&&d){let f=typeof a=="string"?a:null,l=typeof d=="string"?d:null;f&&l&&o.push({source:O(f,c,p,i),target:O(l,c,p,i),type:"objectRelationship",label:e.label??t.split("/").pop()??"",propertyId:t})}}function q(t,e,r,n,s,o,c,p,i){for(let[h,b]of Object.entries(e)){if(ce.has(h)||typeof b!="object"||b===null||Array.isArray(b))continue;let w=b,g=`${t}/${h}`,a=n.get(h),d=a?a.split(".").pop()??a:"Unknown",u={};for(let[f,l]of Object.entries(w))(typeof l!="object"||l===null)&&(u[f]=l);s.push({id:g,label:`${d} (embedded)`,type:"Instance",namespace:c,properties:u});let y=c&&p?`${c}/${h}@${p}`:h;o.push({source:t,target:g,type:"propertyValue",label:h,propertyId:r.has(h)?y:void 0}),a&&o.push({source:g,target:O(d,c,p,i),type:"instanceOf",label:"type (inferred)"}),q(g,w,r,n,s,o,c,p,i)}}function Ce(t,e,r){let n=e?.statement;if(Array.isArray(n))for(let s of n){if(!(s instanceof te))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let p=c.target?.subject;if(!p)continue;let i=p.version,h=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";r.push({source:t,target:`${p.publisher}/${p.package_}/${p.name}${h}`,type:"embeddedLink",label:o})}}}function Ee(t){return!(!t||t.includes(" ")||t.includes(`
|
|
2
|
+
`)||t.startsWith("http://")||t.startsWith("https://")||/^\d{4}-\d{2}/.test(t)||/^\d+(\.\d+)?$/.test(t))}function O(t,e,r,n){if(t.includes("@")&&t.includes("/"))return t;if(t.includes(".")){let s=t.indexOf("."),o=t.substring(0,s),c=t.substring(s+1);if(n){let p=n.get(o);if(p)return`${p.publisher}/${p.package_}/${c}@${p.version}`}return e&&r?`${e}/${c}@${r}`:c}return e&&r?`${e}/${t}@${r}`:t}function M(t){let e=t.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}function v(t){let e;try{e=new URL(t)}catch{throw new Error(`credential scope '${t}' is not an absolute URL`)}if(e.protocol!=="https:")throw new Error(`credential scope '${t}' is not https`);if(e.username||e.password)throw new Error(`credential scope '${t}' carries userinfo`);if(e.search||t.includes("?"))throw new Error(`credential scope '${t}' has a query`);if(e.hash||t.includes("#"))throw new Error(`credential scope '${t}' has a fragment`);let r=e.pathname;return{origin:e.origin,prefix:r.endsWith("/")?r:`${r}/`}}function N(t,e){let r=typeof t=="string"?v(t):t,n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="https:"||n.origin!==r.origin)return!1;let s=n.pathname;return s.startsWith(r.prefix)||`${s}/`===r.prefix}function V(t,e){let r,n=-1;for(let s of t){let o=v(s.scope);N(o,e)&&o.prefix.length>n&&(r=s,n=o.prefix.length)}return r}var Oe="key_thumbprint",x=class{cache=new Map;wellKnownCache=new Map;metadataUrlCache=new Map;async protectedResourceMetadata(e){let r=new URL(e).href,n=this.wellKnownCache.get(r);return n||(n=this.fetchWellKnown(r),this.wellKnownCache.set(r,n)),n}async protectedResourceMetadataAt(e,r){let n=new URL(e).href,s=this.metadataUrlCache.get(n);s||(s=this.fetchMetadataAt(n),this.metadataUrlCache.set(n,s));let o=await s,c;try{c=N(v(o.resource),r)}catch(p){throw new Error(`Protected resource metadata at ${n} names an unusable resource '${o.resource}': ${p.message}`)}if(!c)throw new Error(`Protected resource metadata at ${n} names the resource '${o.resource}', which does not contain the requested ${r}. RFC 9728 \xA73.3 forbids using it.`);return o}async fetchWellKnown(e){let r=new URL(e),n=r.pathname==="/"?"":r.pathname,s=`${r.origin}/.well-known/oauth-protected-resource${n}`,o=await j(s,{redirect:"manual"});if(o.status===404||o.status===410||o.status>=300&&o.status<400)return null;if(!o.ok)throw await K("protected resource metadata",s,o);if(!pe(o.headers.get("content-type")))return null;let c=de(s,await o.text());if(!URL.canParse(c.resource)||new URL(c.resource).href!==e)throw new Error(`Protected resource metadata at ${s} names the resource '${c.resource}', not '${e}'. RFC 9728 \xA73.3 forbids using it.`);return c}async fetchMetadataAt(e){let r=await j(e,{redirect:"manual"});if(!r.ok)throw await K("protected resource metadata",e,r);if(!pe(r.headers.get("content-type")))throw new Error(`Protected resource metadata at ${e} is not a JSON document (${r.headers.get("content-type")??"no content type"})`);return de(e,await r.text())}async discover(e){let r=M(e);if(this.cache.has(r))return this.cache.get(r);let n=`https://${r}/.well-known/oauth-authorization-server`,s=await this.tryEndpoint(n);if(!s){let o=`https://${r}/.well-known/openid-configuration`;s=await this.tryEndpoint(o)}return this.cache.set(r,s),s}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(r=>r.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(r=>r.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let r;try{r=await fetch(e)}catch(s){let o=s instanceof Error?s.message:String(s);return o.includes("ENOTFOUND")||o.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${o})`),console.error(" If the server is behind a VPN, ensure you are connected.")):o.includes("CERT")||o.includes("SSL")||o.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${o})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${o}`),null}if(!r.ok)return r.status===404||(r.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):r.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${r.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await r.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:$(n.issuer),authorizationEndpoint:$(n.authorization_endpoint),tokenEndpoint:$(n.token_endpoint),registrationEndpoint:$(n.registration_endpoint),revocationEndpoint:$(n.revocation_endpoint),scopesSupported:S(n.scopes_supported),responseTypesSupported:S(n.response_types_supported),grantTypesSupported:S(n.grant_types_supported),codeChallengeMethodsSupported:S(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:S(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:S(n.dpop_signing_alg_values_supported),enrollmentEndpoint:$(n.enrollment_endpoint),enrollmentIssuanceProtocols:S(n.enrollment_issuance_protocols),enrollmentKeyTypes:S(n.enrollment_key_types),enrollmentScopesSupported:S(n.enrollment_scopes_supported),enrollmentConsentBindingParam:$(n.enrollment_consent_binding_param),sessionEndpoint:$(n.session_endpoint),sessionEndpointAuthMethod:$(n.session_endpoint_auth_method)}}};function pe(t){let e=(t??"").split(";")[0].trim().toLowerCase();return e==="application/json"||e.endsWith("+json")}function de(t,e){let r;try{r=JSON.parse(e)}catch{throw new Error(`Protected resource metadata at ${t} is not valid JSON`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Protected resource metadata at ${t} is not a JSON object`);let n=r;if(typeof n.resource!="string")throw new Error(`Protected resource metadata at ${t} has no "resource"`);let s=n.authorization_servers;if(s!==void 0&&!(Array.isArray(s)&&s.every(o=>typeof o=="string")))throw new Error(`Protected resource metadata at ${t} has an "authorization_servers" that is not a list of strings`);return{resource:n.resource,authorizationServers:s??[]}}function $(t){return typeof t=="string"?t:null}function S(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):null}var D=1,$e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Se=/[\r\n\0]/;function P(t,e){return{ok:!1,problem:t,message:e}}function L(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U(t,e,r){if(!L(e))return P("malformed","the answer is not a JSON object");if(e.status==="declined")return e.reason!==void 0&&typeof e.reason!="string"?P("reason",`a decline's "reason" must be a string`):{ok:!0,answer:e.reason===void 0?{status:"declined"}:{status:"declined",reason:e.reason}};if(e.status!=="credential")return P("status",`"status" must be "credential" or "declined", not ${JSON.stringify(e.status)}`);let n=e.headers;if(!L(n)||Object.keys(n).length===0)return P("headers",'a credential needs "headers": an object with at least one header');let s={};for(let[i,h]of Object.entries(n)){if(!$e.test(i))return P("headers",`header name ${JSON.stringify(i)} is not a valid field name`);if(typeof h!="string"||Se.test(h))return P("headers",`header '${i}' must be a string without CR, LF or NUL`);s[i]=h}if(typeof e.scope!="string")return P("scope",'a credential needs a "scope" string');let o;try{o=v(e.scope)}catch(i){return P("scope",i.message)}if(!N(o,t.resource))return P("scope-excludes-resource",`scope '${e.scope}' does not contain the requested resource ${t.resource}`);let c;if(e.expiresAt!==void 0){if(typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt))return P("expires-at",'"expiresAt" must be a number of Unix seconds');if(e.expiresAt<=r)return P("expired",`the credential expired at ${e.expiresAt} (now ${Math.floor(r)})`);c=e.expiresAt}let p={status:"credential",headers:s,scope:e.scope};return c!==void 0&&(p.expiresAt=c),{ok:!0,answer:p}}function Re(t,e,r){return L(e)?e.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(e.version)}`):U(t,e,r):P("malformed","the answer is not a JSON object")}function Te(t){return L(t)?t.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(t.version)}`):t.status!=="erased"?P("status",`"status" must be "erased", not ${JSON.stringify(t.status)}`):{ok:!0,answer:{status:"erased"}}:P("malformed","the answer is not a JSON object")}function B(t){let e=new J(t),r=[];for(e.skipListSeparators();!e.atEnd();){let n=e.token();if(!n)throw e.error("expected an auth-scheme");let s={scheme:n,params:{}};r.push(s);let o=e.skipSpaces();if(e.atEnd()||e.peek()===","){e.skipListSeparators();continue}if(!o)throw e.error(`expected a space after the auth-scheme '${n}'`);let c=e.tryParam();if(c)for(ue(s,c,e);e.skipOws(),!e.atEnd();){if(e.peek()!==",")throw e.error('expected "," between auth-params');if(e.skipListSeparators(),e.atEnd())break;let p=e.pos,i=e.tryParam();if(!i){e.pos=p;break}ue(s,i,e)}else{let p=e.token68();if(!p)throw e.error(`expected a token68 or auth-params after '${n}'`);if(s.token68=p,e.skipOws(),!e.atEnd()&&e.peek()!==",")throw e.error("unexpected text after token68")}e.skipListSeparators()}return r}function ue(t,[e,r],n){if(Object.prototype.hasOwnProperty.call(t.params,e))throw n.error(`auth-param '${e}' appears twice in the '${t.scheme}' challenge`);t.params[e]=r}var ve=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/,xe=/[A-Za-z0-9\-._~+/]/,J=class{constructor(e){this.s=e}s;pos=0;atEnd(){return this.pos>=this.s.length}peek(){return this.s[this.pos]}error(e){return new Error(`Malformed WWW-Authenticate (${e} at offset ${this.pos}): ${this.s}`)}skipSpaces(){let e=this.pos;for(;!this.atEnd()&&(this.peek()===" "||this.peek()===" ");)this.pos++;return this.pos>e}skipOws(){this.skipSpaces()}skipListSeparators(){for(;;){if(this.skipOws(),this.peek()!==",")return;this.pos++}}token(){let e=this.pos;for(;!this.atEnd()&&ve.test(this.peek());)this.pos++;return this.s.slice(e,this.pos)}token68(){let e=this.pos;for(;!this.atEnd()&&xe.test(this.peek());)this.pos++;if(this.pos===e)return"";for(;!this.atEnd()&&this.peek()==="=";)this.pos++;return this.s.slice(e,this.pos)}tryParam(){let e=this.pos,r=this.token();if(!r)return null;if(this.skipOws(),this.peek()!=="=")return this.pos=e,null;this.pos++,this.skipOws();let n;if(this.peek()==='"')n=this.quotedString();else if(n=this.token(),!n)return this.pos=e,null;return[r.toLowerCase(),n]}quotedString(){this.pos++;let e="";for(;;){if(this.atEnd())throw this.error("unterminated quoted-string");let r=this.s[this.pos++];if(r==='"')return e;if(r==="\\"){if(this.atEnd())throw this.error("unterminated quoted-pair");e+=this.s[this.pos++]}else e+=r}}};var ye=30;function _e(t,e={}){let r=e.discovery??new x,n=e.nowSeconds??(()=>Date.now()/1e3),s=[],o=new WeakSet,c=new Map,p=new Map,i=a=>{let d=n();return s=s.filter(u=>u.expiresAt===void 0||u.expiresAt-ye>d),V(s,a)},h=(a,d)=>{let u=(p.get(a)??Promise.resolve()).then(d);return p.set(a,u.then(()=>{},()=>{})),u},b=a=>{let d=c.get(a);return d||(d=r.protectedResourceMetadata(a).then(u=>u!==null,u=>{if(u instanceof I&&(u.status===401||u.status===403))return!0;throw new T(`Could not learn whether ${a} requires a credential: ${me(u)}`)}),c.set(a,d)),d},w=async(a,d)=>{let u=U(d,await le(()=>a.get(d),d.resource),n());if(!u.ok)throw new T(`The credential provider answered for ${d.resource} outside the protocol (${u.problem}): ${u.message}`);let y=u.answer;if(y.status==="declined")return y.reason===void 0?{}:{declined:y.reason};let f={headers:y.headers,scope:y.scope};return y.expiresAt!==void 0&&(f.expiresAt=y.expiresAt),s=s.filter(l=>l.scope!==f.scope),s.push(f),f},g=(a,d,u)=>j(a,{method:d,redirect:"manual",headers:u?.headers??{}});return async(a,d,u="GET")=>{let y=new URL(a).origin,f=i(a);if(!f&&t&&await b(y)){let k=await h(y,async()=>i(a)??w(t,{resource:a,method:u}));fe(k)&&(f=k)}let l=await g(a,u,f);if(l.status!==401&&l.status!==403)return l;let A=ge(l,a),m=l.status===401;if(!m&&!he(A))return l;if(c.set(y,Promise.resolve(!0)),!t)throw await Y(`${a} requires a credential, and no credential provider is configured`,l);let C={resource:a,method:u,challenges:A},R=await h(y,async()=>{let k=i(a);if(k&&k!==f)return k;if(m&&f&&!o.has(f)){o.add(f);let Q=f;s=s.filter(we=>we!==Q),await le(()=>t.erase({...C,scope:Q.scope}),a)}return w(t,C)});if(!fe(R)){let k=R.declined?`: ${R.declined}`:"";throw await Y(`${a} requires a credential, and the credential provider declined${k}`,l)}let E=await g(a,u,R);if(E.status===401||E.status===403&&he(ge(E,a)))throw await Y(`${a} rejected the credential for ${R.scope} after asking the provider again`,E);return E}}async function le(t,e){try{return await t()}catch(r){throw r instanceof T?r:new T(`The credential provider failed for ${e}: ${me(r)}`)}}function me(t){return t instanceof Error?t.message:String(t)}function fe(t){return"scope"in t}function he(t){return t.some(e=>e.params.error==="insufficient_scope")}function ge(t,e){let r=t.headers.get("www-authenticate");if(!r)return[];try{return B(r)}catch(n){throw new T(`${e} answered ${t.status} with a challenge that cannot be read: ${n.message}`)}}async function Y(t,e){return new T(`${t}. The server answered ${await ee(e)}`)}var F="KANONAK_TOKEN";function Ne(){return typeof process<"u"&&process.env?process.env:{}}function Z(t){return`${F}_${M(t).toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var X=class{tokens;env;discovery;constructor(e={}){this.tokens=e.tokens??{},this.env=e.env??Ne(),this.discovery=e.discovery??new x}async get(e){let r=await this.metadataFor(e);if("declined"in r)return{status:"declined",reason:r.declined};let n=r.metadata;if(n.authorizationServers.length===0)return{status:"declined",reason:`the protected-resource metadata for ${n.resource} names no authorization server`};let s=n.authorizationServers.map(o=>new URL(o).host);for(let o of s){let c=this.tokens[o]??this.env[Z(o)]??this.env[F];if(c)return{status:"credential",headers:{Authorization:`Bearer ${c}`},scope:n.resource}}return{status:"declined",reason:`no token is configured for ${s.join(" or ")}: set ${s.map(Z).join(" or ")}, or ${F}`}}async erase(){}async metadataFor(e){let r=e.challenges?.find(o=>o.params.resource_metadata!==void 0)?.params.resource_metadata;if(r!==void 0)return{metadata:await this.discovery.protectedResourceMetadataAt(r,e.resource)};let n=new URL(e.resource).origin,s;try{s=await this.discovery.protectedResourceMetadata(n)}catch(o){if(o instanceof I&&(o.status===401||o.status===403))return{declined:`${n} requires a credential even for its protected-resource metadata, and its challenge names no resource_metadata`};throw o}return s?{metadata:s}:{declined:`${n} publishes no RFC 9728 protected-resource metadata naming its authorization server, so no token is presented to it`}}};export{se as a,ae as b,H as c,M as d,v as e,N as f,V as g,Oe as h,x as i,D as j,U as k,Re as l,Te as m,B as n,ye as o,_e as p,F as q,Z as r,X as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{o as i,p as o,q as r}from"./chunk-HKQTB65D.js";import{readFileSync as c,writeFileSync as l,existsSync as s}from"fs";import{createHash as a}from"crypto";var n="kanonak.lock";function f(e=n){return s(e)?o(c(e,"utf-8")):null}function k(e,t=n){e.lastUpdated=new Date().toISOString(),l(t,r(e),"utf-8")}function L(e){let t=a("sha256").update(e).digest("hex");return`${i}${t}`}export{f as a,k as b,L as c};
|