Fit texture to image

I want to adapt the texture to the image
I thought of something about this,
I tried but it doesn’t work,
I can’t understand the error
Can someone check if there are errors

const photoshop = require("photoshop");
const app = photoshop.app;

async function fitImageToBackground() {
    const activeDocument = app.activeDocument;
    
    if (!activeDocument) {
        console.error("No active document found.");
        return;
    }

    const layer = activeDocument.activeLayers[0];

    if (!layer) {
        console.error("No active layer found.");
        return;
    }

    // Get document dimensions
    const docWidth = activeDocument.width;
    const docHeight = activeDocument.height;
    
    // Get image dimensions
    const imgWidth = layer.bounds[2].as("px") - layer.bounds[0].as("px");
    const imgHeight = layer.bounds[3].as("px") - layer.bounds[1].as("px");

    // Calculate scale factor to fit the image to the document
    const scaleX = docWidth / imgWidth;
    const scaleY = docHeight / imgHeight;
    const scale = Math.max(scaleX, scaleY);

    // Resize the image
    layer.resize(scale * 100, scale * 100);

    // Center the image in the document
    const newImgWidth = layer.bounds[2].as("px") - layer.bounds[0].as("px");
    const newImgHeight = layer.bounds[3].as("px") - layer.bounds[1].as("px");
    
    const offsetX = (docWidth - newImgWidth) / 2;
    const offsetY = (docHeight - newImgHeight) / 2;

    layer.translate(offsetX - layer.bounds[0].as("px"), offsetY - layer.bounds[1].as("px"));
}

// Execute the function to fit the image
fitImageToBackground().catch(console.error);