urn.ts (2217B)
1 import { URISchemeHandler, URIComponents, URIOptions } from "../uri"; 2 import { pctEncChar, SCHEMES } from "../uri"; 3 4 export interface URNComponents extends URIComponents { 5 nid?:string; 6 nss?:string; 7 } 8 9 export interface URNOptions extends URIOptions { 10 nid?:string; 11 } 12 13 const NID$ = "(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})"; 14 const PCT_ENCODED$ = "(?:\\%[0-9A-Fa-f]{2})"; 15 const TRANS$$ = "[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]"; 16 const NSS$ = "(?:(?:" + PCT_ENCODED$ + "|" + TRANS$$ + ")+)"; 17 const URN_SCHEME = new RegExp("^urn\\:(" + NID$ + ")$"); 18 const URN_PATH = new RegExp("^(" + NID$ + ")\\:(" + NSS$ + ")$"); 19 const URN_PARSE = /^([^\:]+)\:(.*)/; 20 const URN_EXCLUDED = /[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g; 21 22 //RFC 2141 23 const handler:URISchemeHandler<URNComponents,URNOptions> = { 24 scheme : "urn", 25 26 parse : function (components:URIComponents, options:URNOptions):URNComponents { 27 const matches = components.path && components.path.match(URN_PARSE); 28 let urnComponents = components as URNComponents; 29 30 if (matches) { 31 const scheme = options.scheme || urnComponents.scheme || "urn"; 32 const nid = matches[1].toLowerCase(); 33 const nss = matches[2]; 34 const urnScheme = `${scheme}:${options.nid || nid}`; 35 const schemeHandler = SCHEMES[urnScheme]; 36 37 urnComponents.nid = nid; 38 urnComponents.nss = nss; 39 urnComponents.path = undefined; 40 41 if (schemeHandler) { 42 urnComponents = schemeHandler.parse(urnComponents, options) as URNComponents; 43 } 44 } else { 45 urnComponents.error = urnComponents.error || "URN can not be parsed."; 46 } 47 48 return urnComponents; 49 }, 50 51 serialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents { 52 const scheme = options.scheme || urnComponents.scheme || "urn"; 53 const nid = urnComponents.nid; 54 const urnScheme = `${scheme}:${options.nid || nid}`; 55 const schemeHandler = SCHEMES[urnScheme]; 56 57 if (schemeHandler) { 58 urnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents; 59 } 60 61 const uriComponents = urnComponents as URIComponents; 62 const nss = urnComponents.nss; 63 uriComponents.path = `${nid || options.nid}:${nss}`; 64 65 return uriComponents; 66 }, 67 }; 68 69 export default handler;