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