@sentry/wizard
Version:
Sentry wizard helping you to configure your project
173 lines (172 loc) • 7.33 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateWranglerConfig = void 0;
// @ts-expect-error - clack is ESM and TS complains about that. It works though
const prompts_1 = __importDefault(require("@clack/prompts"));
const chalk_1 = __importDefault(require("chalk"));
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const find_wrangler_config_1 = require("./find-wrangler-config");
const clack_1 = require("../../utils/clack");
const ast_utils_1 = require("../../utils/ast-utils");
const recast = __importStar(require("recast"));
const b = recast.types.builders;
const getTomlConfigSnippet = () => {
return (0, clack_1.makeCodeSnippet)(true, (unchanged, plus) => plus(`
compatibility_flags = ["nodejs_als"]
compatibility_date = "${new Date().toISOString().slice(0, 10)}"
[version_metadata]
binding = "CF_VERSION_METADATA"`));
};
/**
* Updates the wrangler config file with the provided configuration
* Handles .toml (instructions only), .json, and .jsonc formats
* For arrays: merges and deduplicates values
* For objects: deep merges
* For other types: overwrites
*/
async function updateWranglerConfig(updates) {
const configFile = (0, find_wrangler_config_1.findWranglerConfig)();
if (!configFile) {
prompts_1.default.log.warn('No wrangler config file found.');
return false;
}
const configPath = node_path_1.default.join(process.cwd(), configFile);
try {
const configContent = node_fs_1.default.readFileSync(configPath, 'utf-8');
const extname = node_path_1.default.extname(configFile);
switch (extname) {
case '.jsonc':
case '.json':
updateJsoncConfig(configPath, configContent, updates);
prompts_1.default.log.success(`Updated ${chalk_1.default.cyan(configFile)} with Sentry configuration.`);
break;
case '.toml':
await (0, clack_1.showCopyPasteInstructions)({
filename: configFile,
codeSnippet: getTomlConfigSnippet(),
});
break;
}
return true;
}
catch (error) {
prompts_1.default.log.error(`Failed to update ${chalk_1.default.cyan(configFile)}: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
exports.updateWranglerConfig = updateWranglerConfig;
/**
* Sets a string property in a JSON/JSONC config object.
* Overwrites any existing value.
*
* @param jsonObject The object expression to update
* @param propertyName The name of the string property
* @param value The string value to set
*/
function setStringProperty(jsonObject, propertyName, value) {
(0, ast_utils_1.setOrUpdateObjectProperty)(jsonObject, propertyName, b.stringLiteral(value));
}
/**
* Merges an array property in a JSON/JSONC config object.
* Extracts existing array values, merges with new values, and deduplicates.
*
* @param jsonObject The object expression to update
* @param propertyName The name of the array property
* @param newValues The new array values to merge in
*/
function mergeArrayProperty(jsonObject, propertyName, newValues) {
const existingProperty = (0, ast_utils_1.getObjectProperty)(jsonObject, propertyName);
const existingValues = [];
// Extract existing values from the AST if they exist
if (existingProperty && existingProperty.value.type === 'ArrayExpression') {
existingProperty.value.elements.forEach((element) => {
if (element &&
(element.type === 'StringLiteral' || element.type === 'Literal') &&
typeof element.value === 'string') {
existingValues.push(element.value);
}
});
}
// Merge existing and new values, deduplicate
const allValues = [...existingValues, ...newValues];
const uniqueValues = Array.from(new Set(allValues));
(0, ast_utils_1.setOrUpdateObjectProperty)(jsonObject, propertyName, b.arrayExpression(uniqueValues.map((value) => b.stringLiteral(value))));
}
/**
* Merges properties into a nested object property in a JSON/JSONC config object.
* Gets or creates the nested ObjectExpression if it doesn't exist,
* then merges the provided properties into it, preserving existing properties.
*
* @param jsonObject The object expression to update
* @param propertyName The name of the nested object property
* @param updates The properties to merge into the nested object
*/
function setObjectProperty(jsonObject, propertyName, updates) {
const existingProperty = (0, ast_utils_1.getObjectProperty)(jsonObject, propertyName);
let nestedObject;
if (existingProperty && existingProperty.value.type === 'ObjectExpression') {
nestedObject = existingProperty.value;
}
else {
nestedObject = b.objectExpression([]);
(0, ast_utils_1.setOrUpdateObjectProperty)(jsonObject, propertyName, nestedObject);
}
updateJsoncObject(nestedObject, updates);
}
function updateJsoncObject(jsonObject, updates) {
for (const [key, value] of Object.entries(updates)) {
if (value === null || value === undefined) {
continue;
}
if (typeof value === 'string') {
setStringProperty(jsonObject, key, value);
}
else if (Array.isArray(value)) {
mergeArrayProperty(jsonObject, key, value);
}
else if (typeof value === 'object') {
setObjectProperty(jsonObject, key, value);
}
}
}
/**
* Updates a JSON/JSONC config file using jsonc-parser
* Preserves comments and formatting while merging values
*/
function updateJsoncConfig(configPath, content, updates) {
const { jsonObject, ast } = (0, ast_utils_1.parseJsonC)(content);
if (!jsonObject) {
throw new Error('Failed to parse JSON/JSONC config file');
}
updateJsoncObject(jsonObject, updates);
const code = (0, ast_utils_1.printJsonC)(ast);
node_fs_1.default.writeFileSync(configPath, code, 'utf-8');
}
//# sourceMappingURL=update-wrangler-config.js.map