1+ import { RegExpGroups } from "../utils/RegExpGroups" ;
2+
13import { Result , ResultErr , ResultOk } from "@polywrap/result" ;
24
35// $start: UriConfig
@@ -18,7 +20,7 @@ export interface UriConfig {
1820/**
1921 * A Polywrap URI. Some examples of valid URIs are:
2022 * wrap://ipfs/QmHASH
21- * wrap://ens/sub.dimain .eth
23+ * wrap://ens/sub.domain .eth
2224 * wrap://fs/directory/file.txt
2325 * wrap://uns/domain.crypto
2426 *
@@ -135,17 +137,10 @@ export class Uri {
135137 }
136138
137139 // Extract the authoriy & path
138- const result = processed . match ( / w r a p : \/ \/ ( [ a - z ] [ a - z 0 - 9 - _ ] + ) \/ ( .* ) / ) ;
139- let uriParts : string [ ] ;
140-
141- // Remove all empty strings
142- if ( result ) {
143- uriParts = result . filter ( ( str ) => ! ! str ) ;
144- } else {
145- uriParts = [ ] ;
146- }
140+ const re = / ^ w r a p : \/ \/ ( (?< authority > [ a - z ] [ a - z 0 - 9 - _ ] + ) \/ ) ? (?< path > .* ) $ / ;
141+ const result : RegExpGroups < "authority" | "path" > = re . exec ( processed ) ;
147142
148- if ( uriParts . length !== 3 ) {
143+ if ( ! result || ! result . groups || ! result . groups . path ) {
149144 return ResultErr (
150145 Error (
151146 `URI is malformed, here are some examples of valid URIs:\n` +
@@ -157,10 +152,30 @@ export class Uri {
157152 ) ;
158153 }
159154
155+ let { authority, path } = result . groups ;
156+
157+ if ( ! authority ) {
158+ const inferred = Uri . inferAuthority ( path ) ;
159+ if ( ! inferred ) {
160+ return ResultErr (
161+ Error (
162+ `URI authority is missing, here are some examples of valid URIs:\n` +
163+ `wrap://ipfs/QmHASH\n` +
164+ `wrap://ens/domain.eth\n` +
165+ `ens/domain.eth\n\n` +
166+ `Invalid URI Received: ${ uri } `
167+ )
168+ ) ;
169+ }
170+ authority = inferred . authority ;
171+ path = inferred . path ;
172+ processed = `wrap://${ authority } /${ path } ` ;
173+ }
174+
160175 return ResultOk ( {
161176 uri : processed ,
162- authority : uriParts [ 1 ] ,
163- path : uriParts [ 2 ] ,
177+ authority,
178+ path,
164179 } ) ;
165180 }
166181
@@ -194,4 +209,26 @@ export class Uri {
194209 public toJSON ( ) : string /* $ */ {
195210 return this . _config . uri ;
196211 }
212+
213+ private static inferAuthority ( path : string ) : UriConfig | undefined {
214+ let authority : string | undefined ;
215+
216+ if ( path . startsWith ( "https://" ) ) {
217+ authority = "https" ;
218+ } else if ( path . startsWith ( "http://" ) ) {
219+ authority = "http" ;
220+ } else if ( path . startsWith ( "ipfs://" ) ) {
221+ authority = "ipfs" ;
222+ path = path . substring ( 7 ) ;
223+ } else if ( path . startsWith ( "ens://" ) ) {
224+ authority = "ens" ;
225+ path = path . substring ( 6 ) ;
226+ }
227+
228+ if ( ! authority ) {
229+ return undefined ;
230+ }
231+
232+ return { authority, path, uri : `wrap://${ authority } /${ path } ` } ;
233+ }
197234}
0 commit comments