pointer.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. "use strict";
  2. module.exports = Pointer;
  3. const $Ref = require("./ref");
  4. const url = require("./util/url");
  5. const { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } = require("./util/errors");
  6. const slashes = /\//g;
  7. const tildes = /~/g;
  8. const escapedSlash = /~1/g;
  9. const escapedTilde = /~0/g;
  10. /**
  11. * This class represents a single JSON pointer and its resolved value.
  12. *
  13. * @param {$Ref} $ref
  14. * @param {string} path
  15. * @param {string} [friendlyPath] - The original user-specified path (used for error messages)
  16. * @constructor
  17. */
  18. function Pointer ($ref, path, friendlyPath) {
  19. /**
  20. * The {@link $Ref} object that contains this {@link Pointer} object.
  21. * @type {$Ref}
  22. */
  23. this.$ref = $ref;
  24. /**
  25. * The file path or URL, containing the JSON pointer in the hash.
  26. * This path is relative to the path of the main JSON schema file.
  27. * @type {string}
  28. */
  29. this.path = path;
  30. /**
  31. * The original path or URL, used for error messages.
  32. * @type {string}
  33. */
  34. this.originalPath = friendlyPath || path;
  35. /**
  36. * The value of the JSON pointer.
  37. * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
  38. * @type {?*}
  39. */
  40. this.value = undefined;
  41. /**
  42. * Indicates whether the pointer references itself.
  43. * @type {boolean}
  44. */
  45. this.circular = false;
  46. /**
  47. * The number of indirect references that were traversed to resolve the value.
  48. * Resolving a single pointer may require resolving multiple $Refs.
  49. * @type {number}
  50. */
  51. this.indirections = 0;
  52. }
  53. /**
  54. * Resolves the value of a nested property within the given object.
  55. *
  56. * @param {*} obj - The object that will be crawled
  57. * @param {$RefParserOptions} options
  58. * @param {string} pathFromRoot - the path of place that initiated resolving
  59. *
  60. * @returns {Pointer}
  61. * Returns a JSON pointer whose {@link Pointer#value} is the resolved value.
  62. * If resolving this value required resolving other JSON references, then
  63. * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path
  64. * of the resolved value.
  65. */
  66. Pointer.prototype.resolve = function (obj, options, pathFromRoot) {
  67. let tokens = Pointer.parse(this.path, this.originalPath);
  68. // Crawl the object, one token at a time
  69. this.value = unwrapOrThrow(obj);
  70. for (let i = 0; i < tokens.length; i++) {
  71. if (resolveIf$Ref(this, options)) {
  72. // The $ref path has changed, so append the remaining tokens to the path
  73. this.path = Pointer.join(this.path, tokens.slice(i));
  74. }
  75. if (typeof this.value === "object" && this.value !== null && "$ref" in this.value) {
  76. return this;
  77. }
  78. let token = tokens[i];
  79. if (this.value[token] === undefined || this.value[token] === null) {
  80. this.value = null;
  81. throw new MissingPointerError(token, decodeURI(this.originalPath));
  82. }
  83. else {
  84. this.value = this.value[token];
  85. }
  86. }
  87. // Resolve the final value
  88. if (!this.value || this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot) {
  89. resolveIf$Ref(this, options);
  90. }
  91. return this;
  92. };
  93. /**
  94. * Sets the value of a nested property within the given object.
  95. *
  96. * @param {*} obj - The object that will be crawled
  97. * @param {*} value - the value to assign
  98. * @param {$RefParserOptions} options
  99. *
  100. * @returns {*}
  101. * Returns the modified object, or an entirely new object if the entire object is overwritten.
  102. */
  103. Pointer.prototype.set = function (obj, value, options) {
  104. let tokens = Pointer.parse(this.path);
  105. let token;
  106. if (tokens.length === 0) {
  107. // There are no tokens, replace the entire object with the new value
  108. this.value = value;
  109. return value;
  110. }
  111. // Crawl the object, one token at a time
  112. this.value = unwrapOrThrow(obj);
  113. for (let i = 0; i < tokens.length - 1; i++) {
  114. resolveIf$Ref(this, options);
  115. token = tokens[i];
  116. if (this.value && this.value[token] !== undefined) {
  117. // The token exists
  118. this.value = this.value[token];
  119. }
  120. else {
  121. // The token doesn't exist, so create it
  122. this.value = setValue(this, token, {});
  123. }
  124. }
  125. // Set the value of the final token
  126. resolveIf$Ref(this, options);
  127. token = tokens[tokens.length - 1];
  128. setValue(this, token, value);
  129. // Return the updated object
  130. return obj;
  131. };
  132. /**
  133. * Parses a JSON pointer (or a path containing a JSON pointer in the hash)
  134. * and returns an array of the pointer's tokens.
  135. * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"])
  136. *
  137. * The pointer is parsed according to RFC 6901
  138. * {@link https://tools.ietf.org/html/rfc6901#section-3}
  139. *
  140. * @param {string} path
  141. * @param {string} [originalPath]
  142. * @returns {string[]}
  143. */
  144. Pointer.parse = function (path, originalPath) {
  145. // Get the JSON pointer from the path's hash
  146. let pointer = url.getHash(path).substr(1);
  147. // If there's no pointer, then there are no tokens,
  148. // so return an empty array
  149. if (!pointer) {
  150. return [];
  151. }
  152. // Split into an array
  153. pointer = pointer.split("/");
  154. // Decode each part, according to RFC 6901
  155. for (let i = 0; i < pointer.length; i++) {
  156. pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, "/").replace(escapedTilde, "~"));
  157. }
  158. if (pointer[0] !== "") {
  159. throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath);
  160. }
  161. return pointer.slice(1);
  162. };
  163. /**
  164. * Creates a JSON pointer path, by joining one or more tokens to a base path.
  165. *
  166. * @param {string} base - The base path (e.g. "schema.json#/definitions/person")
  167. * @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"])
  168. * @returns {string}
  169. */
  170. Pointer.join = function (base, tokens) {
  171. // Ensure that the base path contains a hash
  172. if (base.indexOf("#") === -1) {
  173. base += "#";
  174. }
  175. // Append each token to the base path
  176. tokens = Array.isArray(tokens) ? tokens : [tokens];
  177. for (let i = 0; i < tokens.length; i++) {
  178. let token = tokens[i];
  179. // Encode the token, according to RFC 6901
  180. base += "/" + encodeURIComponent(token.replace(tildes, "~0").replace(slashes, "~1"));
  181. }
  182. return base;
  183. };
  184. /**
  185. * If the given pointer's {@link Pointer#value} is a JSON reference,
  186. * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.
  187. * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the
  188. * resolution path of the new value.
  189. *
  190. * @param {Pointer} pointer
  191. * @param {$RefParserOptions} options
  192. * @returns {boolean} - Returns `true` if the resolution path changed
  193. */
  194. function resolveIf$Ref (pointer, options) {
  195. // Is the value a JSON reference? (and allowed?)
  196. if ($Ref.isAllowed$Ref(pointer.value, options)) {
  197. let $refPath = url.resolve(pointer.path, pointer.value.$ref);
  198. if ($refPath === pointer.path) {
  199. // The value is a reference to itself, so there's nothing to do.
  200. pointer.circular = true;
  201. }
  202. else {
  203. let resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options);
  204. if (resolved === null) {
  205. return false;
  206. }
  207. pointer.indirections += resolved.indirections + 1;
  208. if ($Ref.isExtended$Ref(pointer.value)) {
  209. // This JSON reference "extends" the resolved value, rather than simply pointing to it.
  210. // So the resolved path does NOT change. Just the value does.
  211. pointer.value = $Ref.dereference(pointer.value, resolved.value);
  212. return false;
  213. }
  214. else {
  215. // Resolve the reference
  216. pointer.$ref = resolved.$ref;
  217. pointer.path = resolved.path;
  218. pointer.value = resolved.value;
  219. }
  220. return true;
  221. }
  222. }
  223. }
  224. /**
  225. * Sets the specified token value of the {@link Pointer#value}.
  226. *
  227. * The token is evaluated according to RFC 6901.
  228. * {@link https://tools.ietf.org/html/rfc6901#section-4}
  229. *
  230. * @param {Pointer} pointer - The JSON Pointer whose value will be modified
  231. * @param {string} token - A JSON Pointer token that indicates how to modify `obj`
  232. * @param {*} value - The value to assign
  233. * @returns {*} - Returns the assigned value
  234. */
  235. function setValue (pointer, token, value) {
  236. if (pointer.value && typeof pointer.value === "object") {
  237. if (token === "-" && Array.isArray(pointer.value)) {
  238. pointer.value.push(value);
  239. }
  240. else {
  241. pointer.value[token] = value;
  242. }
  243. }
  244. else {
  245. throw new JSONParserError(`Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`);
  246. }
  247. return value;
  248. }
  249. function unwrapOrThrow (value) {
  250. if (isHandledError(value)) {
  251. throw value;
  252. }
  253. return value;
  254. }