'use strict';

var base64url = require('base64url');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var base64url__default = /*#__PURE__*/_interopDefault(base64url);

const detachedHeaderParams = {
  b64: false,
  crit: ['b64'],
};

// Taken from https://github.com/transmute-industries/verifiable-data/blob/main/packages/jose-ld/src/JWS/createSigner.ts
async function signJWS(signer, type, options, data) {
  if (!type) {
    return signer.sign({ data });
  }

  const header = {
    alg: type,
    ...options.header,
    ...(options.detached ? detachedHeaderParams : undefined),
  };
  const encodedHeader = base64url__default.default.encode(JSON.stringify(header));
  const encodedPayload = base64url__default.default.encode(
    data instanceof Uint8Array
      ? Buffer.from(data).toString('utf-8')
      : JSON.stringify(data),
  );

  const toBeSigned = options.detached
    ? new Uint8Array(
      Buffer.concat([
        Buffer.from(encodedHeader, 'utf8'),
        Buffer.from('.', 'utf-8'),
        data,
      ]),
    )
    : new Uint8Array(Buffer.from(`${encodedHeader}.${encodedPayload}`));

  const signature = await signer.sign({ data: toBeSigned });

  // If not, encode it ourselves
  return options.detached
    ? `${encodedHeader}..${base64url__default.default.encode(Buffer.from(signature))}`
    : `${encodedHeader}.${encodedPayload}.${base64url__default.default.encode(
      Buffer.from(signature),
    )}`;
}

function createJws({ encodedHeader, verifyData }) {
  const buffer = Buffer.concat([
    Buffer.from(`${encodedHeader}.`, 'utf8'),
    Buffer.from(verifyData.buffer, verifyData.byteOffset, verifyData.length),
  ]);
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
}

exports.createJws = createJws;
exports.signJWS = signJWS;
//# sourceMappingURL=jws.cjs.map
