"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.injectWcpTelemetryClientCode = void 0;
var fs = _interopRequireWildcard(require("fs"));
var path = _interopRequireWildcard(require("path"));
var _nodeFetch = _interopRequireDefault(require("node-fetch"));
var _wcp = require("@webiny/wcp");
var _plugins = require("@webiny/cli-plugin-deploy-pulumi/plugins");
const injectWcpTelemetryClientCode = exports.injectWcpTelemetryClientCode = new _plugins.AfterBuildPlugin(async ({
  projectApplication
}, context) => {
  if (!projectApplication.project.config.id) {
    return;
  }
  const workspacePath = projectApplication.paths.workspace;
  const handlersPaths = [path.join(workspacePath, "graphql", "build")];

  // 1. Download telemetry client code.
  const latestTelemetryClientUrl = (0, _wcp.getWcpApiUrl)("/clients/latest.js");
  try {
    const response = await (0, _nodeFetch.default)(latestTelemetryClientUrl);
    if (!response.ok) {
      throw new Error(`Failed to download telemetry client: ${response.status} - ${response.statusText}`);
    }
    const telemetryCodeAsString = await response.text();

    // 2. Wrap the initially built code with the telemetry client code.
    for (let i = 0; i < handlersPaths.length; i++) {
      const current = handlersPaths[i];

      // 2.1 Move initially built `handler.js` into `_handler.js`.
      const builtHandlerPath = path.join(current, "handler.js");
      const renamedHandlerPath = path.join(current, "_handler.js");
      fs.renameSync(builtHandlerPath, renamedHandlerPath);

      // 2.2 Write downloaded telemetry client code as a new `handler.js`.
      fs.writeFileSync(builtHandlerPath, telemetryCodeAsString);
    }
  } catch (e) {
    context.warning(`WCP client is unavailable; telemetry was disabled.`);
    context.debug(e);
  }
});
injectWcpTelemetryClientCode.name = "api.after-build.inject-wcp-telemetry-client-code";

//# sourceMappingURL=injectWcpTelemetryClientCode.js.map