json.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. /*
  3. Copyright 2023 The Sigstore Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. Object.defineProperty(exports, "__esModule", { value: true });
  15. exports.canonicalize = canonicalize;
  16. // JSON canonicalization per https://github.com/cyberphone/json-canonicalization
  17. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18. function canonicalize(object) {
  19. let buffer = '';
  20. if (object === null || typeof object !== 'object' || object.toJSON != null) {
  21. // Primitives or toJSONable objects
  22. buffer += JSON.stringify(object);
  23. }
  24. else if (Array.isArray(object)) {
  25. // Array - maintain element order
  26. buffer += '[';
  27. let first = true;
  28. object.forEach((element) => {
  29. if (!first) {
  30. buffer += ',';
  31. }
  32. first = false;
  33. // recursive call
  34. buffer += canonicalize(element);
  35. });
  36. buffer += ']';
  37. }
  38. else {
  39. // Object - Sort properties before serializing
  40. buffer += '{';
  41. let first = true;
  42. Object.keys(object)
  43. .sort()
  44. .forEach((property) => {
  45. if (!first) {
  46. buffer += ',';
  47. }
  48. first = false;
  49. buffer += JSON.stringify(property);
  50. buffer += ':';
  51. // recursive call
  52. buffer += canonicalize(object[property]);
  53. });
  54. buffer += '}';
  55. }
  56. return buffer;
  57. }