schemes.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. 'use strict'
  2. const { isUUID } = require('./utils')
  3. const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu
  4. const supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',
  5. 'wss', 'urn', 'urn:uuid'])
  6. /** @typedef {supportedSchemeNames[number]} SchemeName */
  7. /**
  8. * @param {string} name
  9. * @returns {name is SchemeName}
  10. */
  11. function isValidSchemeName (name) {
  12. return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1
  13. }
  14. /**
  15. * @callback SchemeFn
  16. * @param {import('../types/index').URIComponent} component
  17. * @param {import('../types/index').Options} options
  18. * @returns {import('../types/index').URIComponent}
  19. */
  20. /**
  21. * @typedef {Object} SchemeHandler
  22. * @property {SchemeName} scheme - The scheme name.
  23. * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.
  24. * @property {SchemeFn} parse - Function to parse the URI component for this scheme.
  25. * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.
  26. * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.
  27. * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.
  28. * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.
  29. */
  30. /**
  31. * @param {import('../types/index').URIComponent} wsComponent
  32. * @returns {boolean}
  33. */
  34. function wsIsSecure (wsComponent) {
  35. if (wsComponent.secure === true) {
  36. return true
  37. } else if (wsComponent.secure === false) {
  38. return false
  39. } else if (wsComponent.scheme) {
  40. return (
  41. wsComponent.scheme.length === 3 &&
  42. (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&
  43. (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&
  44. (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')
  45. )
  46. } else {
  47. return false
  48. }
  49. }
  50. /** @type {SchemeFn} */
  51. function httpParse (component) {
  52. if (!component.host) {
  53. component.error = component.error || 'HTTP URIs must have a host.'
  54. }
  55. return component
  56. }
  57. /** @type {SchemeFn} */
  58. function httpSerialize (component) {
  59. const secure = String(component.scheme).toLowerCase() === 'https'
  60. // normalize the default port
  61. if (component.port === (secure ? 443 : 80) || component.port === '') {
  62. component.port = undefined
  63. }
  64. // normalize the empty path
  65. if (!component.path) {
  66. component.path = '/'
  67. }
  68. // NOTE: We do not parse query strings for HTTP URIs
  69. // as WWW Form Url Encoded query strings are part of the HTML4+ spec,
  70. // and not the HTTP spec.
  71. return component
  72. }
  73. /** @type {SchemeFn} */
  74. function wsParse (wsComponent) {
  75. // indicate if the secure flag is set
  76. wsComponent.secure = wsIsSecure(wsComponent)
  77. // construct resouce name
  78. wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')
  79. wsComponent.path = undefined
  80. wsComponent.query = undefined
  81. return wsComponent
  82. }
  83. /** @type {SchemeFn} */
  84. function wsSerialize (wsComponent) {
  85. // normalize the default port
  86. if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {
  87. wsComponent.port = undefined
  88. }
  89. // ensure scheme matches secure flag
  90. if (typeof wsComponent.secure === 'boolean') {
  91. wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')
  92. wsComponent.secure = undefined
  93. }
  94. // reconstruct path from resource name
  95. if (wsComponent.resourceName) {
  96. const queryIndex = wsComponent.resourceName.indexOf('?')
  97. const path = queryIndex === -1
  98. ? wsComponent.resourceName
  99. : wsComponent.resourceName.slice(0, queryIndex)
  100. wsComponent.path = (path && path !== '/' ? path : undefined)
  101. wsComponent.query = queryIndex === -1
  102. ? undefined
  103. : wsComponent.resourceName.slice(queryIndex + 1)
  104. wsComponent.resourceName = undefined
  105. }
  106. // forbid fragment component
  107. wsComponent.fragment = undefined
  108. return wsComponent
  109. }
  110. /** @type {SchemeFn} */
  111. function urnParse (urnComponent, options) {
  112. if (!urnComponent.path) {
  113. urnComponent.error = 'URN can not be parsed'
  114. return urnComponent
  115. }
  116. const matches = urnComponent.path.match(URN_REG)
  117. if (matches && matches[0] === urnComponent.path) {
  118. const scheme = options.scheme || urnComponent.scheme || 'urn'
  119. urnComponent.nid = matches[1].toLowerCase()
  120. urnComponent.nss = matches[2]
  121. const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`
  122. const schemeHandler = getSchemeHandler(urnScheme)
  123. urnComponent.path = undefined
  124. if (schemeHandler) {
  125. urnComponent = schemeHandler.parse(urnComponent, options)
  126. }
  127. } else {
  128. urnComponent.error = urnComponent.error || 'URN can not be parsed.'
  129. }
  130. return urnComponent
  131. }
  132. /** @type {SchemeFn} */
  133. function urnSerialize (urnComponent, options) {
  134. if (urnComponent.nid === undefined) {
  135. throw new Error('URN without nid cannot be serialized')
  136. }
  137. const scheme = options.scheme || urnComponent.scheme || 'urn'
  138. const nid = urnComponent.nid.toLowerCase()
  139. const urnScheme = `${scheme}:${options.nid || nid}`
  140. const schemeHandler = getSchemeHandler(urnScheme)
  141. if (schemeHandler) {
  142. urnComponent = schemeHandler.serialize(urnComponent, options)
  143. }
  144. const uriComponent = urnComponent
  145. const nss = urnComponent.nss
  146. uriComponent.path = `${nid || options.nid}:${nss}`
  147. options.skipEscape = true
  148. return uriComponent
  149. }
  150. /** @type {SchemeFn} */
  151. function urnuuidParse (urnComponent, options) {
  152. const uuidComponent = urnComponent
  153. uuidComponent.uuid = uuidComponent.nss
  154. uuidComponent.nss = undefined
  155. if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
  156. uuidComponent.error = uuidComponent.error || 'UUID is not valid.'
  157. }
  158. return uuidComponent
  159. }
  160. /** @type {SchemeFn} */
  161. function urnuuidSerialize (uuidComponent) {
  162. const urnComponent = uuidComponent
  163. // normalize UUID
  164. urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()
  165. return urnComponent
  166. }
  167. const http = /** @type {SchemeHandler} */ ({
  168. scheme: 'http',
  169. domainHost: true,
  170. parse: httpParse,
  171. serialize: httpSerialize
  172. })
  173. const https = /** @type {SchemeHandler} */ ({
  174. scheme: 'https',
  175. domainHost: http.domainHost,
  176. parse: httpParse,
  177. serialize: httpSerialize
  178. })
  179. const ws = /** @type {SchemeHandler} */ ({
  180. scheme: 'ws',
  181. domainHost: true,
  182. parse: wsParse,
  183. serialize: wsSerialize
  184. })
  185. const wss = /** @type {SchemeHandler} */ ({
  186. scheme: 'wss',
  187. domainHost: ws.domainHost,
  188. parse: ws.parse,
  189. serialize: ws.serialize
  190. })
  191. const urn = /** @type {SchemeHandler} */ ({
  192. scheme: 'urn',
  193. parse: urnParse,
  194. serialize: urnSerialize,
  195. skipNormalize: true
  196. })
  197. const urnuuid = /** @type {SchemeHandler} */ ({
  198. scheme: 'urn:uuid',
  199. parse: urnuuidParse,
  200. serialize: urnuuidSerialize,
  201. skipNormalize: true
  202. })
  203. const SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({
  204. http,
  205. https,
  206. ws,
  207. wss,
  208. urn,
  209. 'urn:uuid': urnuuid
  210. })
  211. Object.setPrototypeOf(SCHEMES, null)
  212. /**
  213. * @param {string|undefined} scheme
  214. * @returns {SchemeHandler|undefined}
  215. */
  216. function getSchemeHandler (scheme) {
  217. return (
  218. scheme && (
  219. SCHEMES[/** @type {SchemeName} */ (scheme)] ||
  220. SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])
  221. ) ||
  222. undefined
  223. }
  224. module.exports = {
  225. wsIsSecure,
  226. SCHEMES,
  227. isValidSchemeName,
  228. getSchemeHandler,
  229. }