---
updatedAt: 2026-11-02T20:14:59.000Z
agentTools:
  siteIndex: https://docs.jfrog.com/llms.txt
  projectIndex: https://docs.jfrog.com/administration/llms.txt
---

# Workers Code Samples

These TypeScript samples work with **every** creation method: [CLI](https://docs.jfrog.com/administration/docs/create-and-manage-workers#jfrog-cli), [UI](https://docs.jfrog.com/administration/docs/create-and-manage-workers#jfrog-platform-ui), [REST API](https://docs.jfrog.com/administration/docs/create-and-manage-workers#rest-api), [MCP Server](https://docs.jfrog.com/administration/docs/create-and-manage-workers#mcp-server), and [Terraform](https://docs.jfrog.com/administration/docs/create-and-manage-workers#terraform). Copy a sample into the UI editor, `worker.ts` (CLI), `sourceCode` (REST API / Terraform), or your MCP workflow.

Worker types are described in [Worker Types](https://docs.jfrog.com/administration/docs/worker-types). For event descriptions, see [Worker Event Types](https://docs.jfrog.com/administration/docs/worker-event-types). Choose how to create and manage Workers in [Create and Manage Workers](https://docs.jfrog.com/administration/docs/create-and-manage-workers).

### Samples in GitHub

* <Anchor target="_blank" href="https://github.com/jfrog/workers-sample/tree/main/samples/artifactory">GitHub: Artifactory Workers Samples</Anchor>
* <Anchor target="_blank" href="https://github.com/jfrog/workers-sample/tree/main/samples/access">GitHub: Access Workers Samples</Anchor>
* [GitHub: Agent Integration Worker Samples](https://github.com/jfrog/workers-sample/blob/main/ai-agents.md)

## Artifactory Workers Code Samples

The following sections provide code samples for workers. For event descriptions, see [Worker Event Types](https://docs.jfrog.com/administration/docs/worker-event-types).

| Worker                               | Code Sample                                                                                           |
| :----------------------------------- | :---------------------------------------------------------------------------------------------------- |
| Before Download Worker               | [Before Download Worker Code Sample](#before-download-worker-code-sample)                             |
| After Download Worker                | [After Download Worker Code Sample](#after-download-worker-code-sample)                               |
| Before Create Property Worker        | [Before Create Property Worker Code Sample](#before-create-property-worker-code-sample)               |
| Before Upload Worker                 | [Before Upload Worker Code Sample](#before-upload-worker-code-sample)                                 |
| After Create Worker                  | [After Create Worker Code Sample](#after-create-worker-code-sample)                                   |
| Before Delete Property Worker        | [Before Delete Property Worker Code Sample](#before-delete-property-worker-code-sample)               |
| Before Delete Worker                 | [Before Delete Worker Code Sample](#before-delete-worker-code-sample)                                 |
| After Move Worker                    | [After Move Worker Code Sample](#after-move-worker-code-sample)                                       |
| After Build Info Save Worker         | [After Build Info Save Worker Code Sample](#after-build-info-save-worker-code-sample)                 |
| Before Copy Worker                   | [Before Copy Worker Code Sample](#before-copy-worker-code-sample)                                     |
| Before Create Worker                 | [Before Create Worker Code Sample](#before-create-worker-code-sample)                                 |
| Before Move Worker                   | [Before Move Worker Code Sample](#before-move-worker-code-sample)                                     |
| Before Remote Info Worker            | [Before Remote Info Worker Code Sample](#before-remote-info-worker-code-sample)                       |
| After Remote Download Worker         | [After Remote Download Worker Code Sample](#after-remote-download-worker-code-sample)                 |
| Before Delete Replication Worker     | [Before Delete Replication Worker Code Sample](#before-delete-replication-worker-code-sample)         |
| Before Directory Replication Worker  | [Before Directory Replication Worker Code Sample](#before-directory-replication-worker-code-sample)   |
| Before File Replication Worker       | [Before File Replication Worker Code Sample](#before-file-replication-worker-code-sample)             |
| Before Property Replication Worker   | [Before Property Replication Worker Code Sample](#before-property-replication-worker-code-sample)     |
| Before Statistics Replication Worker | [Before Statistics Replication Worker Code Sample](#before-statistics-replication-worker-code-sample) |
| After Copy Worker                    | [After Copy Worker Code Sample](#after-copy-worker-code-sample)                                       |
| After Create Property Worker         | [After Create Property Worker Code Sample](#after-create-property-worker-code-sample)                 |
| After Delete Property Worker         | [After Delete Property Worker Code Sample](#after-delete-property-worker-code-sample)                 |
| After Delete Worker                  | [After Delete Worker Code Sample](#after-delete-worker-code-sample)                                   |
| Alt Remote Path Worker               | [Alt Remote Path Worker Code Sample](#alt-remote-path-worker-code-sample)                             |
| Before Remote Download Worker        | [Before Remote Download Worker Code Sample](#before-remote-download-worker-code-sample)               |
| Alt All Responses Worker             | [Alt All Responses Worker Code Sample](#alt-all-responses-worker-code-sample)                         |
| Alt Remote Content Worker            | [Alt Remote Content Worker Code Sample](#alt-remote-content-worker-code-sample)                       |
| After Download Error Worker          | [After Download Error Worker Code Sample](#after-download-error-worker-code-sample)                   |
| Before Download Request Worker       | [Before Download Request Worker Code Sample](#before-download-request-worker-code-sample)             |
| Before Build Info Save Worker        | [Before Build Info Save Worker Code Sample](#before-build-info-save-worker-code-sample)               |
| Before Repository Create Worker      | [Before Repository Create Worker Code Sample](#before-repository-create-worker-code-sample)           |
| Before Repository Update Worker      | [Before Repository Update Worker Code Sample](#before-repository-update-worker-code-sample)           |
| Before Repository Delete Worker      | [Before Repository Delete Worker Code Sample](#before-repository-delete-worker-code-sample)           |
| After Repository Create Worker       | [After Repository Create Worker Code Sample](#after-repository-create-worker-code-sample)             |
| After Repository Update Worker       | [After Repository Update Worker Code Sample](#after-repository-update-worker-code-sample)             |
| After Repository Delete Worker       | [After Repository Delete Worker Code Sample](#after-repository-delete-worker-code-sample)             |

### After Build Info Save Worker Code Sample

The following section provides a sample code for After Build Info Save worker.

```
export default async (
  context: PlatformContext,
  data: AfterBuildInfoSaveRequest
): Promise<AfterBuildInfoSaveResponse> => {
  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    executionStatus: Status.STATUS_SUCCESS,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with upload details sent by Artifactory.

```
{
  "build": {
    "name": "buildName",  // The name of the build, used for identification.
    "number": "buildNumber",  // A unique identifier for this build instance.
    "started": "startDate",  // The date and time when the build process started.
    "buildAgent": "buildAgent",  // The name of the build agent that executed the build.
    "agent": "agent",  // Another identifier for the build agent.
    "durationMillis": 1000,  // Total time taken for the build in milliseconds.
    "principal": "principal",  // The user responsible for initiating the build.
    "artifactoryPrincipal": "artifactoryPrincipal",  // User associated with artifact storage.
    "url": "url",  // A link to the build details or logs.
    "parentName": "parentName",  // Name of the parent build, if applicable.
    "parentNumber": "parentNumber",  // Unique identifier for the parent build.
    "buildRepo": "buildRepo",  // Repository where the source code for the build is stored.
    "modules": [  // List of modules included in this build.
      {
        "id": "module1",  // Unique identifier for the module.
        "artifacts": [  // Collection of artifacts produced by the module.
          {
            "name": "name",  // Name of the artifact (output file/package).
            "type": "type",  // Type/category of the artifact (e.g., jar, zip).
            "remotePath": "remotePath",  // Path where the artifact is stored remotely.
            "properties": "prop2"  // Other metadata related to the artifact.
          }
        ],
        "dependencies": [  // List of dependencies required by the module.
          {
            "id": "id",  // Unique identifier for the dependency.
            "scopes": "scopes",  // Scopes in which the dependency is used (e.g., compile, runtime).
            "requestedBy": "requestedBy"  // Identifies who requested the dependency.
          }
        ]
      }
    ],
    "releaseStatus": "releaseStatus",  // Current status of the build in terms of release readiness.
    "promotionStatuses": [  // History of promotional statuses for this build.
      {
        "status": "status",  // Current status of the promotion process (e.g., promoted, rejected).
        "comment": "comment",  // Remarks associated with the promotional status.
        "repository": "repository",  // Repository related to the promotional status.
        "timestamp": "timestamp",  // Date and time when the promotional status was recorded.
        "user": "user",  // User who made the promotional change.
        "ciUser": "ciUser"  // User under which the CI process ran during promotion.
      }
    ]
  }
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

* **message** : This is a mandatory field.

### After Copy Worker Code Sample

The following section provides a sample code for an After Copy worker.

```
export default async (
  context: PlatformContext,
  data: AfterCopyRequest
): Promise<AfterCopyResponse> => {
  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with copy details sent by Artifactory.

**For Artifactory Versions before 7.122**

```
{
  "metadata": {  // Metadata information about the repository and file
    "repoPath": {  // Path information for the repository
      "key": "local-repo",  // The key or identifier for the local repository
      "path": "folder/subfolder/my-file",  // The location of the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining repo key and path
      "isRoot": false,  // Indicates whether this path is the root of the repository (true/false)
      "isFolder": false  // Indicates whether this is a folder (true) or a file (false)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 means not modified)
    "trustServerChecksums": false,  // Indicates whether server checksums are trusted (true/false)
    "servletContextUrl": "servlet.com",  // URL context for servlet, useful for API interactions
    "skipJarIndexing": false,  // Flag to skip indexing for JAR files (true/false)
    "disableRedirect": false,  // Flag to disable HTTP redirects (true/false)
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "targetRepoPath": {  // Destination path information for the target repository
    "key": "target-repo",  // The key or identifier for the target repository
    "path": "new_folder/my-file",  // The desired location of the file in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates whether this path is the root of the repository (true/false)
    "isFolder": false  // Indicates whether this is a folder (true) or a file (false)
  },
  "properties": {  // Custom properties associated with the file
    "prop1": {  // A custom property named "prop1"
      "value": [  // An array of values for this property
        "value1",  // First value for prop1
        "value2"   // Second value for prop1
      ]
    },
    "size": {  // Custom property representing the size of the file
      "value": "50Gb"  // The size value for this property
    },
    "shaResolution": {  // Custom property for hash resolution
      "value": "sha256"  // Specifies the SHA algorithm used (e.g., sha256)
    }
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  }
}
```

**For Artifactory Versions from 7.122**

```
{
  "metadata": {  // Metadata information about the repository and file
    "repoPath": {  // Path information for the repository
      "key": "local-repo",  // The key or identifier for the local repository
      "path": "folder/subfolder/my-file",  // The location of the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining repo key and path
      "isRoot": false,  // Indicates whether this path is the root of the repository (true/false)
      "isFolder": false  // Indicates whether this is a folder (true) or a file (false)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 means not modified)
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "targetRepoPath": {  // Destination path information for the target repository
    "key": "target-repo",  // The key or identifier for the target repository
    "path": "new_folder/my-file",  // The desired location of the file in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates whether this path is the root of the repository (true/false)
    "isFolder": false  // Indicates whether this is a folder (true) or a file (false)
  },
  "properties": {  // Custom properties associated with the file
    "prop1": {  // A custom property named "prop1"
      "value": [  // An array of values for this property
        "value1",  // First value for prop1
        "value2"   // Second value for prop1
      ]
    },
    "size": {  // Custom property representing the size of the file
      "value": "50Gb"  // The size value for this property
    },
    "shaResolution": {  // Custom property for hash resolution
      "value": "sha256"  // Specifies the SHA algorithm used (e.g., sha256)
    }
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  }
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Create Property Worker Code Sample

The following section provides a sample code for an After Create Property worker.

```
export default async (
  context: PlatformContext,
  data: AfterPropertyCreateRequest
): Promise<AfterPropertyCreateResponse> => {
  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with the created property details sent by Artifactory.

**For Artifactory Versions before 7.122**

```
{
  "metadata": {
    "repoPath": {  // Object containing information about the repository path
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the file/folder in the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining repo key and path
      "isRoot": false,  // Indicates if the path is a root directory
      "isFolder": false  // Indicates if the path is a folder
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates no modification)
    "trustServerChecksums": false,  // Indicates whether server checksums should be trusted
    "servletContextUrl": "servlet.com",  // URL for the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "headers": {
    "Content-Type": {  // Content-Type header for the request
      "value": [
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header for the request
      "value": [
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  },
  "userContext": {  // Object containing user context information
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.122**

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Information about the repository path for the artifact
      "key": "local-repo",  // Unique identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 means not modified)
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
 },
 "userContext": {  // Context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp indicating when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name",  // Name of the property being set or modified
  "values": [  // Array of values associated with the property
    "value1",  // First value of the property
    "value2"   // Second value of the property
  ]
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Create Worker Code Sample

The following section provides a sample code for a After Create worker.

```
export default async (
  context: PlatformContext,
  data: AfterCreateRequest
): Promise<AfterCreateResponse> => {
  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with upload details sent by Artifactory.

```
{
 "metadata": { // Various immutable upload metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false // Is the path a folder?
   },
   "contentLength": 0, // The deploy request content length
   "lastModified": 1, // Last modification time that occurred
   "trustServerChecksums": false, // Is the request trusting the server checksums?
   "servletContextUrl": "base", // The URL that points to Artifactory
   "skipJarIndexing": false, // Is it a request that skips jar indexing?
   "disableRedirect": false, // Is redirect disabled on this request?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context which sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an access token?
   "realm": "realm" // The realm of the user
 },
 "artifactProperties": {  // The properties of the request
   "key": {
     "value": []
   }
 }
}
```

#### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Delete Property Worker Code Sample

The following section provides a sample code for an After Delete Property worker.

```
export default async (
  context: PlatformContext,
  data: AfterPropertyDeleteRequest
): Promise<AfterPropertyDeleteResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with delete property details sent by Artifactory.

**For Artifactory Versions before 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Information about the repository path for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repo key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates no modification)
    "trustServerChecksums": false,  // Indicates whether server checksums should be trusted
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric type identifier for the repository (e.g., local, remote, virtual)
  },
  "userContext": {  // Object containing information about the user context
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the item (artifact)
    "repoPath": {  // Information about the repository path of the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repo key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the artifact
    "created": 1,  // Timestamp of when the artifact was created (assuming Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name"  // Name of a specific property associated with the artifact
}
```

**For Artifactory Versions from 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Information about the repository path for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repo key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates no modification)
    "repoType": 1  // Numeric type identifier for the repository (e.g., local, remote, virtual)
  },
  "userContext": {  // Object containing information about the user context
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the item (artifact)
    "repoPath": {  // Information about the repository path of the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repo key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the artifact
    "created": 1,  // Timestamp of when the artifact was created (assuming Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name"  // Name of a specific property associated with the artifact
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Delete Worker Code Sample

The following section provides a sample code for an After Delete worker.

```
export default async (
  context: PlatformContext,
  data: AfterDeleteRequest
): Promise<AfterDeleteResponse> => {
  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with deleted details sent by Artifactory.

**For Artifactory Versions before 7.122**

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Information about the repository path for the artifact
      "key": "local-repo",  // Unique identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates whether server checksums should be trusted
    "servletContextUrl": "servlet.com",  // URL of the servlet context for accessing the artifact
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the repository type (e.g., local, remote, virtual)
  },
  "headers": {  // HTTP headers for the request
    "Content-Type": {  // Content-Type header to specify the type of content being sent
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header to specify the expected response format
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  },
  "userContext": {  // Context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.122**

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Information about the repository path for the artifact
      "key": "local-repo",  // Unique identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1,  // Numeric identifier representing the type of repository (1 typically denotes a local repository)
    "triggerMetadataCalculation": false,  // Indicates whether metadata calculation should be triggered (false means it does not)
    "allowAsyncDelete": false,  // Indicates if asynchronous deletion of the artifact is allowed (false means it is not)
    "skipTrashcan": false,  // Indicates if the deletion should skip the trashcan (false means it will go to the trashcan)
    "isTriggeredByGc": false,  // Indicates if the deletion was triggered by garbage collection (false means it was not)
    "triggeredByMove": false  // Indicates if the action was triggered by moving the artifact (false means it was not)
 },
 "userContext": {  // Context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp indicating when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  }
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Download Worker Code Sample

The following section provides a sample code for an After Download worker.

Agent integrations for this event are in [Worker to Agent Integrations](#worker-to-agent-integrations).

```
export default async (
  context: PlatformContext,
  data: AfterDownloadRequest
): Promise<AfterDownloadResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Move Worker Code Sample

The following section provides a sample code for an After Move worker.

```
export default async (
  context: PlatformContext,
  data: AfterMoveRequest
): Promise<AfterMoveResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with upload details sent by Artifactory.

**For Artifactory Versions before 7.122**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Information about the current repository path for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates the file has not been modified)
    "trustServerChecksums": false,  // Indicates whether to trust server checksums for validation
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "targetRepoPath": {  // Object containing information about the target repository path for the artifact
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // Path to the specific file in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path combining its repository key
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is not)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "artifactProperties": {  // Object containing properties associated with the artifact
    "prop1": {  // Custom property name
      "value": [  // Array of values associated with the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
    }
  },
  "userContext": {  // Object containing context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.122**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Information about the current repository path for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates the file has not been modified)
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "targetRepoPath": {  // Object containing information about the target repository path for the artifact
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // Path to the specific file in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path combining its repository key
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is not)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "artifactProperties": {  // Object containing properties associated with the artifact
    "prop1": {  // Custom property name
      "value": [  // Array of values associated with the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
    }
  },
  "userContext": {  // Object containing context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### After Remote Download Worker Code Sample

The following section provides a sample code for an After Remote Download worker.

```
export default async (
  context: PlatformContext,
  data: AfterRemoteDownloadRequest
): Promise<AfterRemoteDownloadResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Original path of the artifact before any modifications
      "key": "local-repo",  // Unique key identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Path to the artifact's previous location
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the artifact being referenced
    "headOnly": false,  // Indicates if only the header should be processed (false means body is included)
    "checksum": false,  // Indicates whether a checksum of the file should be calculated
    "recursive": false,  // Indicates if the operation should be performed recursively (false means it is not)
    "modificationTime": 0,  // Timestamp of the last modification (0 indicates no modification)
    "directoryRequest": false,  // Indicates if the request is for a directory (false means for a file)
    "metadata": false,  // Indicates if metadata should be included in the request (false means it is not)
    "lastModified": 1,  // Timestamp of the last modification (assuming it is in Unix time format)
    "ifModifiedSince": 0,  // Timestamp to check if the file has been modified since (0 means no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to a ZIP resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a ZIP resource
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated via a token (true indicates they are)
    "realm": "realm"  // Realm for user authentication context
  },
  "responseHeaders": {  // HTTP headers associated with the response
    "Content-Type": {  // Content-Type header for the response
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the response content type is plain text
      ]
    },
    "Accept": {  // Accept header indicating what response formats the sender can handle
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  }
}
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### Alt Remote Path Worker Code Sample

The following section provides a sample code for an alt remote path worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads via an alternative remote path using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: AltRemotePathRequest
): Promise<AltRemotePathResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
      status = ActionStatus.PROCEED;
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
      status = ActionStatus.WARN;
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
    status = ActionStatus.STOP;
  }

  return {
    message: "proceed",
    status,
    modifiedRepoPath: data.repoPath,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with alt remote path details sent by Artifactory.

```
{
  "repoPath": {  // Object containing information about the path of the artifact in the repository
    "key": "local-repo",  // Unique key identifier for the repository
    "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
    "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
    "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
    "isFolder": false  // Indicates if the path is a folder (false means it is a file)
  },
  "repoType": 1,  // Numeric identifier representing the type of repository (e.g., 1 for local, 2 for remote, etc.)
  "userContext": {  // Object containing information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated with a token (true means they are)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": ActionStatus.PROCEED // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with copying an artifact in storage.
* `ActionStatus.STOP` - The worker does not allow Artifactory to copy an artifact in storage.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with copying an artifact in storage.

### Alt All Responses Worker Code Sample

The following section provides a sample code for an Alt All Responses worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads from alternative responses using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: AltAllResponsesRequest
): Promise<AltAllResponsesResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
      status = ActionStatus.PROCEED;
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
      status = ActionStatus.WARN;
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
    status = ActionStatus.STOP;
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with alt all request details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current path information of the artifact in the repository
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Object containing the original path of the artifact before modification
      "key": "local-repo",  // Unique key identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Previous path to the file before it was modified
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the file being referenced
    "headOnly": false,  // Indicates whether to process only the header of the request (false means process body as well)
    "checksum": false,  // Indicates whether a checksum should be calculated for the file
    "recursive": false,  // Indicates if the operation should be recursive (false means it operates only on the specified file)
    "modificationTime": 0,  // Timestamp of the last modification (0 indicates no modification)
    "directoryRequest": false,  // Indicates if this request pertains to a directory (false means it relates to a file)
    "metadata": false,  // Indicates if metadata should be included in the request (false means it will not)
    "lastModified": 1,  // Timestamp of when the file was last modified (assumed to be Unix timestamp)
    "ifModifiedSince": 0,  // Timestamp to check if the file has been modified since this time (0 means no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to a ZIP resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a ZIP resource (false means it does not)
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the repository type (e.g., local = 1, remote = 2, virtual = 3, etc.)
  },
  "userContext": {  // Object containing context information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated using a token (true means they are)
    "realm": "realm"  // Realm for user authentication context
  },
  "headers": {  // Object containing HTTP headers associated with the request
    "Content-Type": {  // Content-Type header indicating the type of data being sent
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header indicating the formats the client can accept
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": ActionStatus.PROCEED // The instruction of how to proceed
}
```

**message** : This is a mandatory field.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with alt all response events.
* `ActionStatus.STOP` - The worker does not allow Artifactory to alt all response events.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with alt all response events.

### Alt Remote Content Worker Code Sample

The following section provides a sample code for an Alt Remote Content worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads of remote content using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: AltRemoteContentRequest
): Promise<AltRemoteContentResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
      status = ActionStatus.PROCEED;
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
      status = ActionStatus.WARN;
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
    status = ActionStatus.STOP;
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download request details sent by Artifactory.

```
{
  "repoPath": {
    "key": "local-repo",
    "path": "folder/subfolder/my-file",
    "id": "local-repo:folder/subfolder/my-file",
    "isRoot": false,
    "isFolder": false
  },
  "repoType": 1,
  "userContext": {
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",
    "isToken": true,
    "realm": "realm"
  }
}
```

###### Response

```
{
    "message": "proceed", // Message to print to the log. In case of an error, it will be printed as a warning.
    "status": ActionStatus.PROCEED // Numeric status indicating the result of the operation (1 could signify success)
}
```

**message** : This is a mandatory field.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with alt remote content events.
* `ActionStatus.STOP` - The worker does not allow Artifactory to alt remote content events.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with alt remote content events.

### After Download Error Worker Code Sample

The following section provides a sample code for an After Download Error worker.

```
export default async (
  context: PlatformContext,
  data: AfterDownloadErrorRequest
): Promise<AfterDownloadErrorResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download request details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Information about the current repository path for the artifact
      "key": "local-repo",  // Unique identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repo key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Information about the original repository path before any changes
      "key": "local-repo",  // Unique identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Previous path to the file before modification
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is not)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the file
    "headOnly": false,  // Indicates if only the header request is to be processed
    "checksum": false,  // Indicates whether to calculate a checksum for the file
    "recursive": false,  // Indicates if the operation should be recursive (false means it is not)
    "modificationTime": 0,  // Time of last modification (0 indicates no modification)
    "directoryRequest": false,  // Indicates if the request is for a directory
    "metadata": false,  // Indicates if metadata should be included in the request
    "lastModified": 1,  // Timestamp of the last modification (assuming it is Unix timestamp)
    "ifModifiedSince": 0,  // Timestamp to check if the file has been modified since this time (0 indicates no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for the servlet context accessing the artifact
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to zip resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a zip resource
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the repository type (e.g., local, remote, virtual)
  },
  "userContext": {  // Object containing context information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated via a token
    "realm": "realm"  // Realm for user authentication context
  },
  "requestHeaders": {  // HTTP headers associated with the request
    "Content-Type": {  // Content-Type header for the request
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header for the request
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  }
{
```

###### Response

```
{
 "message": "proceed" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### Before Copy Worker Code Sample

The following section provides a sample code for a Before Copy worker.

```
export default async (
  context: PlatformContext,
  data: BeforeCopyRequest
): Promise<BeforeCopyResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;

  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with copy details sent by Artifactory.

**For Artifactory Versions before 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates whether to trust server checksums for validation
    "servletContextUrl": "servlet.com",  // URL for accessing the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Current repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "targetRepoPath": {  // Object containing information about the target repository path for the item
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // Path to where the item will be moved in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is nested)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "properties": {  // Object containing various properties associated with the item
    "prop1": {  // Custom property name
      "value": [  // Array of values associated with the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
    },
    "size": {  // Property related to the size of the item
      "value": "50Gb"  // Size of the item specified as a string
    },
    "shaResolution": {  // Property related to the hashing algorithm used
      "value": "sha256"  // Value indicating the SHA resolution (hashing algorithm)
    }
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Current repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "targetRepoPath": {  // Object containing information about the target repository path for the item
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // Path to where the item will be moved in the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is nested)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "properties": {  // Object containing various properties associated with the item
    "prop1": {  // Custom property name
      "value": [  // Array of values associated with the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
    },
    "size": {  // Property related to the size of the item
      "value": "50Gb"  // Size of the item specified as a string
    },
    "shaResolution": {  // Property related to the hashing algorithm used
      "value": "sha256"  // Value indicating the SHA resolution (hashing algorithm)
    }
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with copying an artifact in storage.
* `ActionStatus.STOP` - The worker does not allow Artifactory to copy an artifact in storage.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with copying an artifact in storage.

### Before Create Property Worker Code Sample

The following section provides a sample code for a Before Create Property worker.

```
export default async (
  context: PlatformContext,
  data: BeforePropertyCreateRequest
): Promise<BeforePropertyCreateResponse> => {
  let status: BeforePropertyCreateStatus =
    BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with create details sent by Artifactory.

**For Artifactory Versions before 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates whether to trust server checksums for validation
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Current repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name",  // Name of the property being set or modified
  "values": [  // Array of values associated with the property
    "value1",  // First value of the property
    "value2"   // Second value of the property
  ]
}
```

**For Artifactory Versions from 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Current repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name",  // Name of the property being set or modified
  "values": [  // Array of values associated with the property
    "value1",  // First value of the property
    "value2"   // Second value of the property
  ]
}
```

###### Response

```
{
  status: BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_PROCEED, // The instruction of how to proceed
  message: 'proceed',  // Message to print to the log. In case of an error, it will be printed as a warning.
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_PROCEED` - The worker allows Artifactory to proceed with creating a property.
* `BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_STOP` - The worker does not allow Artifactory to create a property.
* `BeforePropertyCreateStatus.BEFORE_PROPERTY_CREATE_WARN` - The worker provides a warning before Artifactory can proceed with creating a property.

### Before Create Worker Code Sample

The following section provides a sample code for a Before Create worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block uploads of artifacts using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the upload will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeCreateRequest
): Promise<BeforeCreateResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;

  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with create details sent by Artifactory.

**For Artifactory Versions before 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates whether the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates whether the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates if server checksums should be trusted (false means not)
    "servletContextUrl": "servlet.com",  // URL for accessing the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files (false means indexing will occur)
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (1 typically represents a local repository)
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates whether the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates whether the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be in Unix timestamp format)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates whether the user is authenticated via a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.123**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates whether the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates whether the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "repoType": 1  // Numeric identifier representing the type of repository (1 typically represents a local repository)
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates whether the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates whether the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp of when the item was created (assumed to be in Unix timestamp format)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates whether the user is authenticated via a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with creating an artifact in storage.
* `ActionStatus.STOP` - The worker does not allow Artifactory to create an artifact in storage.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with creating an artifact in storage.

### Before Delete Property Worker Code Sample

The following section provides a sample code for a Before Delete Property worker.

```
export default async (
  context: PlatformContext,
  data: BeforePropertyDeleteRequest
): Promise<BeforePropertyDeleteResponse> => {
  let status: BeforePropertyDeleteStatus =
    BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with delete details sent by Artifactory.

**For Artifactory Versions before 7.123**

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Information about the current path of the artifact in the repository
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates whether to trust server checksums for artifact validation
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context in Artifactory
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files (false means indexing will occur)
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates whether the user is authenticated using a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Information about the current path of the item in the repository
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item in the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact) being referenced
    "created": 1,  // Timestamp indicating when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name"  // Name of the property being referenced or set
}
```

**For Artifactory Versions from 7.123**

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Information about the current path of the artifact in the repository
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "repoType": 1  // Numeric identifier representing the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates whether the user is authenticated using a token (false means they are not)
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Information about the current path of the item in the repository
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item in the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact) being referenced
    "created": 1,  // Timestamp indicating when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  },
  "name": "property-name"  // Name of the property being referenced or set
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_PROCEED` - The worker allows Artifactory to proceed with deleting a property.
* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_STOP` - The worker does not allow Artifactory to delete a property.
* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_Delete_WARN` - The worker provides a warning before Artifactory can proceed with deleting a property.

### Before Delete Replication Worker Code Sample

The following section provides a sample code for a Before Delete Replication worker.

```
export default async (
  context: PlatformContext,
  data: BeforeDeleteReplicationRequest
): Promise<BeforeDeleteReplicationResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with delete replication details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  },
  "targetInfo": {  // Object containing information about the target instance and repository
    "instanceUrl": "artInstance1.jfrog.com",  // URL of the target JFrog Artifactory instance
    "repoKey": "testRepoKey"  // Key identifier for the target repository
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with deleting a replication.
* `ActionStatus.STOP` - The worker does not allow Artifactory to delete a replication.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with deleting a replication.

### Before Delete Worker Code Sample

The following section provides a sample code for a Before Delete worker.

```
export default async (
  context: PlatformContext,
  data: BeforeDeleteRequest
): Promise<BeforeDeleteResponse> => {
  let status: BeforeDeleteStatus = BeforeDeleteStatus.BEFORE_DELETE_UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = BeforeDeleteStatus.BEFORE_DELETE_PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = BeforeDeleteStatus.BEFORE_DELETE_WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = BeforeDeleteStatus.BEFORE_DELETE_STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with delete details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1,  // Numeric identifier representing the type of repository (1 typically denotes a local repository)
    "triggerMetadataCalculation": false,  // Indicates whether metadata calculation should be triggered (false means it does not)
    "allowAsyncDelete": false,  // Indicates if asynchronous deletion of the artifact is allowed (false means it is not)
    "skipTrashcan": false,  // Indicates if the deletion should skip the trashcan (false means it will go to the trashcan)
    "isTriggeredByGc": false,  // Indicates if the deletion was triggered by garbage collection (false means it was not)
    "triggeredByMove": false  // Indicates if the action was triggered by moving the artifact (false means it was not)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates whether the user is authenticated using a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  },
  "itemInfo": {  // Object containing information about the specific item (artifact)
    "repoPath": {  // Repository path information for the item
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific item within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "name": "my-artifact",  // Name of the item (artifact)
    "created": 1,  // Timestamp indicating when the item was created (assumed to be Unix timestamp)
    "lastModified": 0  // Timestamp of the last modification (0 indicates no modification)
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_PROCEED` - The worker allows Artifactory to proceed with deleting a property.
* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_DELETE_STOP` - The worker does not allow Artifactory to delete a property.
* `BeforePropertyDeleteStatus.BEFORE_PROPERTY_Delete_WARN` - The worker provides a warning before Artifactory can proceed with deleting a property.

### Before Directory Replication Worker Code Sample

The following section provides a sample code for a Before Directory Replication worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block directory replication using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the replication will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeDirectoryReplicationRequest
): Promise<BeforeDirectoryReplicationResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with directory replication details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  },
  "targetInfo": {  // Object containing information about the target instance and repository
    "instanceUrl": "artInstance1.jfrog.com",  // URL of the target JFrog Artifactory instance
    "repoKey": "testRepoKey"  // Key identifier for the target repository
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with replicating a directory.
* `ActionStatus.STOP` - The worker does not allow Artifactory to replicate a directory.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with replicating a directory.

### Before Download Worker Code Sample

The following section provides a sample code for a Before Download Worker.

Agent integrations for this event are in [Worker to Agent Integrations](#worker-to-agent-integrations).

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads of artifacts using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeDownloadRequest
): Promise<BeforeDownloadResponse> => {
  let status: DownloadStatus = DownloadStatus.DOWNLOAD_UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = DownloadStatus.DOWNLOAD_PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = DownloadStatus.DOWNLOAD_WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = DownloadStatus.DOWNLOAD_STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "Overwritten by worker-service if an error occurs.",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request?
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to Artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 },
 "repoPath": { // The response repository path
   "key": "key",
   "path": "path",
   "id": "key:path",
   "isRoot": false,
   "isFolder": false
 }
}
```

#### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

##### Possible Statuses

* `DownloadStatus.DOWNLOAD_PROCEED` - The worker allows to proceed with download.
* `DownloadStatus.DOWNLOAD_STOP` - The worker forbids download. Download will be aborted.
* `DownloadStatus.DOWNLOAD_WARN` - The worker allows to proceed with download. A warning log with the provided message will be recorded in Artifactory.

### Before File Replication Worker Code Sample

The following section provides a sample code for a Before File Replication worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block file replication using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the replication will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeFileReplicationRequest
): Promise<BeforeFileReplicationResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with file replication details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  },
  "targetInfo": {  // Object containing information about the target instance and repository
    "instanceUrl": "artInstance1.jfrog.com",  // URL of the target JFrog Artifactory instance
    "repoKey": "testRepoKey"  // Key identifier for the target repository
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* Supported Versions
* Installation Types
* RPM / Debian / Linux Archive Installation

### Before Move Worker Code Sample

The following section provides a sample code for a Before Move worker.

```
export default async (
  context: PlatformContext,
  data: BeforeMoveRequest
): Promise<BeforeMoveResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with move details sent by Artifactory.

**For Artifactory Versions before 7.122**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the current location of the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific artifact within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the artifact's content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates no modifications)
    "trustServerChecksums": false,  // Indicates whether server checksums should be trusted for validation
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context in Artifactory
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files (false means indexing will occur)
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "targetRepoPath": {  // Object containing information about the target repository path
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // New path to the specific artifact within the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is nested)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "properties": {  // Object containing properties associated with the artifact
    "prop1": {  // Custom property name
      "value": [  // Array of values for the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
    },
    "size": {  // Property related to the size of the artifact
      "value": "50Gb"  // Size of the artifact specified as a string
    },
    "shaResolution": {  // Property indicating the hashing algorithm used
      "value": "sha256"  // Value indicating the SHA resolution (hashing algorithm)
    }
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

**For Artifactory Versions from 7.122**

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the current location of the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific artifact within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "lastModified": 0,  // Timestamp of the last modification (0 indicates no modifications)
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "targetRepoPath": {  // Object containing information about the target repository path
    "key": "target-repo",  // Unique key identifier for the target repository
    "path": "new_folder/my-file",  // New path to the specific artifact within the target repository
    "id": "target-repo:new_folder/my-file",  // Unique identifier for the target path
    "isRoot": false,  // Indicates if the target path is a root directory (false means it is nested)
    "isFolder": false  // Indicates if the target path is a folder (false means it is a file)
  },
  "properties": {  // Object containing properties associated with the artifact
    "prop1": {  // Custom property name
      "value": [  // Array of values for the property
        "value1",  // First value of the property
        "value2"   // Second value of the property
      ]
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with moving an artifact.
* `ActionStatus.STOP` - The worker does not allow Artifactory to move an artifact.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with moving an artifact.

### Before Property Replication Worker Code Sample

The following section provides a sample code for a Before Property Replication worker.

```
export default async (
  context: PlatformContext,
  data: BeforePropertyReplicationRequest
): Promise<BeforePropertyReplicationResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with property replication details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  },
  "targetInfo": {  // Object containing information about the target instance and repository
    "instanceUrl": "artInstance1.jfrog.com",  // URL of the target JFrog Artifactory instance
    "repoKey": "testRepoKey"  // Key identifier for the target repository
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with replicating a property.
* `ActionStatus.STOP` - The worker does not allow Artifactory to replicate a property.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with replicating a property.

### Before Build Info Save Worker Code Sample

The following section provides a sample code for a Before Build Info Save worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block publishing of build info using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the publication will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeBuildInfoSaveRequest
): Promise<BeforeBuildInfoSaveResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;

  try {
    // The HTTP client facilitates calls to the JFrog Platform REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "proceed",
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with save details sent by Artifactory.

```
{
  "build": {  // Object containing information about the build
    "name": "buildName",  // Name of the build
    "number": "buildNumber",  // Unique number identifying the build
    "started": "1980-01-01T00:00:00.000+0000",  // Timestamp indicating when the build started (ISO 8601 format)
    "buildAgent": "GENERIC/1.00.0",  // Identifier for the build agent used
    "agent": "jfrog-cli-go/1.00.0",  // Specific CLI agent used for the build
    "durationMillis": 1000,  // Duration of the build in milliseconds
    "principal": "bob",  // User who initiated the build
    "artifactoryPrincipal": "artifactoryPrincipal",  // Principal or user in Artifactory associated with the build
    "url": "url",  // URL to access the build details or information
    "parentName": "parentName",  // Name of the parent build (if applicable)
    "parentNumber": "parentNumber",  // Number of the parent build (if applicable)
    "buildRepo": "buildRepo",  // Repository where the build artifacts are stored
    "modules": [  // Array of modules associated with the build
      {
        "id": "module1",  // Unique identifier for the module
        "artifacts": [  // Array of artifacts produced by the module
          {
            "name": "name",  // Name of the artifact
            "type": "type",  // Type of the artifact (e.g., jar, war, etc.)
            "sha1": "sha1",  // SHA-1 checksum of the artifact
            "sha256": "sha256",  // SHA-256 checksum of the artifact
            "md5": "md5",  // MD5 checksum of the artifact
            "remotePath": "remotePath",  // Path to the remote location of the artifact
            "properties": "properties"  // Additional properties associated with the artifact
          }
        ],
        "dependencies": [  // Array of dependencies for the module
          {
            "id": "id",  // Unique identifier for the dependency
            "scopes": "scopes",  // Scopes in which the dependency is used (e.g., compile, runtime)
            "requestedBy": "requestedBy"  // User or process that requested the dependency
          }
        ]
      }
    ],
    "releaseStatus": "releaseStatus",  // Release status of the build (e.g., released, unreleased)
    "promotionStatuses": [  // Array of promotion statuses for the build
      {
        "status": "status",  // Status of the promotion (e.g., promoted, failed)
        "comment": "comment",  // Comment or note about the promotion status
        "repository": "repository",  // Repository involved in the promotion
        "timestamp": "timestamp",  // Timestamp when the promotion status was recorded
        "user": "user",  // User who performed the promotion
        "ciUser": "ciUser"  // CI user associated with the promotion (if applicable)
      }
    ]
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with build info save events.
* `ActionStatus.STOP` - The worker does not allow Artifactory to save build info save events.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with the build info save events.

### Before Download Request Worker Code Sample

The following section provides a sample code for a Before Download Request worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads of artifacts from download requests using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeDownloadRequestRequest
): Promise<BeforeDownloadRequestResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "Overwritten by worker-service if an error occurs.",
    modifiedRepoPath: data.metadata.repoPath,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download request details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Repository path information for the current location of the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Information about the original path of the artifact before modification
      "key": "local-repo",  // Unique key identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Previous path to the file before modification
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the file being referenced
    "headOnly": false,  // Indicates if only the header of the request should be processed (false means full request)
    "checksum": false,  // Indicates whether a checksum should be computed for the file
    "recursive": false,  // Indicates if the operation should be recursive (false means it will apply to this file only)
    "modificationTime": 0,  // Timestamp of the last modification (0 indicates no modification)
    "directoryRequest": false,  // Indicates if the request is for a directory (false means it relates to a file)
    "metadata": false,  // Indicates if metadata should be included in the request (false means it will not)
    "lastModified": 1,  // Timestamp of the last modification (assumed to be Unix timestamp)
    "ifModifiedSince": 0,  // Timestamp for checking if the file has been modified since a specific time (0 means no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context in Artifactory
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact in the repository
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to a ZIP resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a ZIP resource
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local, remote, virtual)
  },
  "requestHeaders": {  // Object containing HTTP headers associated with the request
    "Content-Type": {  // Content-Type header indicating the type of data being sent
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header indicating the formats the client can accept
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  },
  "userContext": {  // Object containing context information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated using a token (false means not)
    "realm": "realm"  // Realm for user authentication context
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with download request events.
* `ActionStatus.STOP` - The worker does not allow Artifactory to download request events.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with download request events.

### Before Remote Download Worker Code Sample

The following section provides a sample code for a Before Remote Download worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads of artifacts from a remote repository using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeRemoteDownloadRequest
): Promise<BeforeRemoteDownloadResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  let headers: { [key: string]: Header } = {};
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      headers["Content-Type"] = { value: ["text/plain"] };
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
    headers,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Information about the original path of the artifact before any modifications
      "key": "local-repo",  // Unique key identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Previous path to the file before modification
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the file being referenced
    "headOnly": false,  // Indicates if only the headers should be processed (false means full request will be processed)
    "checksum": false,  // Indicates whether a checksum should be calculated for the file
    "recursive": false,  // Indicates if the operation should be recursive (false means it operates only on this file)
    "modificationTime": 0,  // Timestamp of the last modification (0 indicates the file has not been modified)
    "directoryRequest": false,  // Indicates if the request is for a directory (false means it is for a file)
    "metadata": false,  // Indicates if metadata should be included in the request (false means it will not)
    "lastModified": 1,  // Timestamp of the last modification (assuming it is a Unix timestamp)
    "ifModifiedSince": 0,  // Timestamp to check if the file has been modified since this time (0 means no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context in Artifactory
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact in the repository
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to a ZIP resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a ZIP resource
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local = 1)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated using a token (true means they are)
    "realm": "realm"  // Realm for user authentication context
  },
  "headers": {  // Object containing HTTP headers associated with the request
    "Content-Type": {  // Content-Type header indicating the type of data being sent
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header indicating the formats that can be accepted in the response
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with downloading an artifact from the remote.
* `ActionStatus.STOP` - The worker does not allow Artifactory to download an artifact from the remote.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with downloading an artifact from the remote.

### Before Remote Info Worker Code Sample

The following section provides a sample code for a Before Remote Info worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads of remote info using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the download will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeRemoteInfoRequest
): Promise<BeforeRemoteInfoResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  let headers: { [key: string]: Header } = {};

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      headers["Content-Type"] = { value: ["text/plain"] };
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = ActionStatus.STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
    headers,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with info details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Current path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "originalRepoPath": {  // Information about the original path of the artifact before modification
      "key": "local-repo",  // Unique key identifier for the original repository
      "path": "old/folder/subfolder/my-file",  // Previous path to the file before modification
      "id": "local-repo:old/folder/subfolder/my-file",  // Unique identifier for the original path
      "isRoot": false,  // Indicates if the original path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the original path is a folder (false means it is a file)
    },
    "name": "my-file",  // Name of the file being referenced
    "headOnly": false,  // Indicates if only the headers should be processed (false means full request will be processed)
    "checksum": false,  // Indicates whether a checksum should be calculated for the file
    "recursive": false,  // Indicates if the operation should be recursive (false means it operates only on this file)
    "modificationTime": 0,  // Timestamp of the last modification (0 indicates the file has not been modified)
    "directoryRequest": false,  // Indicates if the request is for a directory (false means it relates to a file)
    "metadata": false,  // Indicates if metadata should be included in the request (false means it will not)
    "lastModified": 1,  // Timestamp of the last modification (assumed to be in Unix timestamp format)
    "ifModifiedSince": 0,  // Timestamp to check if the file has been modified since (0 means no check)
    "servletContextUrl": "https://jpd.jfrog.io/artifactory",  // URL for accessing the servlet context in Artifactory
    "uri": "/artifactory/local-repo/folder/subfolder/my-file",  // URI for accessing the artifact in the repository
    "clientAddress": "100.100.100.100",  // IP address of the client making the request
    "zipResourcePath": "",  // Path to a ZIP resource if applicable (empty indicates none)
    "zipResourceRequest": false,  // Indicates if the request involves a ZIP resource (false means it does not)
    "replaceHeadRequestWithGet": false,  // Indicates if HEAD requests should be replaced with GET requests
    "repoType": 1  // Numeric identifier representing the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated using a token (true means they are)
    "realm": "realm"  // Realm for user authentication context
  },
  "headers": {  // Object containing HTTP headers associated with the request
    "Content-Type": {  // Content-Type header indicating the type of data being sent
      "value": [  // Array of values for the Content-Type header
        "text/plain"  // Indicates that the content type is plain text
      ]
    },
    "Accept": {  // Accept header indicating the formats that can be accepted in the response
      "value": [  // Array of values for the Accept header
        "application/json"  // Indicates that the expected response format is JSON
      ]
    }
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with getting info of an artifact from the remote.
* `ActionStatus.STOP` - The worker does not allow Artifactory to get info of an artifact from the remote.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can get an artifact's info from the remote.

### Before Statistics Replication Worker Code Sample

The following section provides a sample code for a Before Statistics Replication worker.

```
export default async (
  context: PlatformContext,
  data: BeforeStatisticsReplicationRequest
): Promise<BeforeStatisticsReplicationResponse> => {
  let status: ActionStatus = ActionStatus.UNSPECIFIED;
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = ActionStatus.PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = ActionStatus.WARN;
      console.warn(
        `Request was successful and returned status code : ${res.status}`
      );
    }
  } catch (error) {
    status = ActionStatus.STOP;
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: "proceed",
    status,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with statistics replication details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata about the artifact
    "repoPath": {  // Current repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfolder/my-file",  // Path to the specific file within the repository
      "id": "local-repo:folder/subfolder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "repoType": 1  // Numeric identifier for the type of repository (1 typically denotes a local repository)
  },
  "userContext": {  // Contextual information about the user making the request
    "id": "id",  // Unique identifier for the user
    "isToken": false,  // Indicates if the user is authenticated via a token (true/false)
    "realm": "realm"  // The realm in which the user is authenticated (used for authorization)
  },
  "targetInfo": {  // Object containing information about the target instance and repository
    "instanceUrl": "artInstance1.jfrog.com",  // URL of the target JFrog Artifactory instance
    "repoKey": "testRepoKey"  // Key identifier for the target repository
  }
}
```

###### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

###### Possible Statuses

* `ActionStatus.PROCEED` - The worker allows Artifactory to proceed with replicating statistics.
* `ActionStatus.STOP` - The worker does not allow Artifactory to replicate statistics.
* `ActionStatus.WARN` - The worker provides a warning before Artifactory can proceed with replicating statistics.

### Before Upload Worker Code Sample

The following section provides a sample code for a Before Upload worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block uploads of artifacts using this Worker's Stop response. Platforms without JAS or Curation can still deploy and run this Worker, but the Stop Action is not enforced: if the Worker returns Stop, the upload will not be blocked and a warning will be logged.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeUploadRequest
): Promise<BeforeUploadResponse> => {
  let status: UploadStatus = UploadStatus.UPLOAD_UNSPECIFIED;

  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      status = UploadStatus.UPLOAD_PROCEED;
      console.log("Artifactory ping success");
    } else {
      status = UploadStatus.UPLOAD_WARN;
      console.warn(
        `Request was successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    status = UploadStatus.UPLOAD_STOP;
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    status,
    message: "Overwritten by worker-service if an error occurs.",
    modifiedRepoPath: data.metadata.repoPath,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with upload details sent by Artifactory.

```
{
  "metadata": {  // Object containing metadata information about the artifact
    "repoPath": {  // Repository path information for the artifact
      "key": "local-repo",  // Unique key identifier for the repository
      "path": "folder/subfoder/my-file",  // Current path to the specific artifact within the repository
      "id": "local-repo:folder/subfoder/my-file",  // Unique identifier combining the repository key and path
      "isRoot": false,  // Indicates if the path is a root directory (false means it is nested)
      "isFolder": false  // Indicates if the path is a folder (false means it is a file)
    },
    "contentLength": 100,  // Length of the content in bytes
    "lastModified": 0,  // Timestamp of the last modification (0 indicates it has not been modified)
    "trustServerChecksums": false,  // Indicates whether server checksums should be trusted for validation
    "servletContextUrl": "servlet.com",  // URL for accessing the servlet context
    "skipJarIndexing": false,  // Indicates whether to skip indexing for JAR files (false means indexing will occur)
    "disableRedirect": false,  // Indicates whether HTTP redirects should be disabled
    "repoType": 1  // Numeric identifier representing the type of repository (e.g., local = 1)
  },
  "headers": {  // Object containing HTTP headers associated with the request
    "key": {  // Example of a custom header
      "key": "bla",  // Name of the custom header
      "value": "bla"  // Value of the custom header
    }
  },
  "userContext": {  // Object containing information about the user making the request
    "id": "jffe@00xxxxxxxxxxxxxxxxxxxxxxxx/users/bob",  // Unique identifier for the user
    "isToken": true,  // Indicates if the user is authenticated using a token (true means they are)
    "realm": "realm"  // Realm for user authentication context
  },
  "artifactProperties": {  // Object containing additional properties associated with the artifact
    "anyProperty": {  // Example of a custom property name
      "value": [  // Array of values for the property
        "anything"  // Example value for the property
      ]
    }
  }
}
```

#### Response

```
{
 "message": "proceed", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": "proceed" // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

##### Possible Statuses

* `UploadStatus.UPLOAD_PROCEED` - The worker allows to proceed with the upload.
* `UploadStatus.UPLOAD_STOP` - The worker forbids upload. Upload will be aborted.
* `UploadStatus.UPLOAD_WARN` - The worker allows to proceed with the upload. A warning log with the provided message will be recorded in Artifactory.

### Before Repository Create Worker Code Sample

The following section provides a sample code for a Before Repository Create worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The Before Repository Create event is blocking. Each Worker must be configured with a repository filter. System-managed repositories are excluded.
</Callout>

#### Example: Enforce Repository Naming Convention

```
export default async (
  context: PlatformContext,
  data: BeforeRepoCreateRequest
): Promise<BeforeRepoCreateResponse> => {
  const REQUIRED_PREFIX = 'prefix-';
  const repoKey = data.metadata.repositoryKey ?? '';
  if (!repoKey.startsWith(REQUIRED_PREFIX)) {
    return {
      status: BeforeRepoCreateStatus.BEFORE_REPO_CREATE_STOP,
      message: `Repository key must start with "${REQUIRED_PREFIX}", got: ${repoKey}`
    };
  }
  return {
    status: BeforeRepoCreateStatus.BEFORE_REPO_CREATE_PROCEED,
    message: ''
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The repository create request sent by Artifactory.

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  },
  "config": {
    "key": "my-docker-repo",
    "packageType": "Docker",
    "baseConfig": {
      "modelVersion": 2,
      "description": "",
      "notes": "",
      "repoLayoutRef": "simple-default",
      "includesPattern": "**/*",
      "excludesPattern": "",
      "federationConfig": {
        "gridTopologyId": null,
        "federationOnGrid": false,
        "members": [],
        "modificationDate": 0,
        "federated": false
      }
    },
    "repoTypeConfig": {
      "archiveBrowsingEnabled": false,
      "blackedOut": false,
      "cdnRedirectRepoConfig": null,
      "downloadRedirectConfig": null,
      "propertySetRefs": [
        "artifactory"
      ],
      "checksumPolicyType": "CLIENT",
      "priorityResolution": false,
      "maxUniqueSnapshots": 0,
      "handleReleases": true,
      "handleSnapshots": true,
      "snapshotVersionBehavior": "UNIQUE"
    },
    "packageTypeConfig": {
      "dockerTagRetention": "1",
      "blockPushingSchema1": "true",
      "dockerApiVersion": "V2",
      "maxUniqueTags": "0"
    },
    "securityConfig": {
      "primaryKeyPairRef": null,
      "secondaryKeyPairRef": null,
      "xrayConfig": null,
      "hideUnauthorizedResources": false,
      "keyPair": null,
      "signedUrlTtl": 90
    },
    "federation": null,
    "repoType": "LOCAL"
  }
}
```

#### Response

```
{
  "status": "BEFORE_REPO_CREATE_PROCEED",
  "message": "proceed"
}
```

* **status** and **message** are mandatory fields.

#### Possible Statuses

* `BeforeRepoCreateStatus.BEFORE_REPO_CREATE_PROCEED`: Allow repository creation to continue.
* `BeforeRepoCreateStatus.BEFORE_REPO_CREATE_STOP`: Block repository creation. In bulk create flows, a STOP aborts the entire batch.
* `BeforeRepoCreateStatus.BEFORE_REPO_CREATE_WARN`: Allow creation; log the Worker message as a warning.

### Before Repository Update Worker Code Sample

The following section provides a sample code for a Before Repository Update worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The Before Repository Update event is blocking. Bulk updates follow all-or-nothing blocking: a STOP on any repository aborts the entire batch.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeRepoUpdateRequest
): Promise<BeforeRepoUpdateResponse> => {
  const packageTypeChanged = data.changeAttributes.some(
    attribute => attribute.attributeName === "packageType"
  );
  if (packageTypeChanged) {
    return {
      status: BeforeRepoUpdateStatus.BEFORE_REPO_UPDATE_STOP,
      message: `Repository ${data.metadata.repositoryKey} cannot change package type`
    };
  }
  return {
    status: BeforeRepoUpdateStatus.BEFORE_REPO_UPDATE_PROCEED,
    message: "proceed"
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The repository update request. Includes `changeAttributes` describing the pending configuration diff instead of the full config.

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  },
  "changeAttributes": [
    {
      "attributeName": "packageTypeConfig»maxUniqueTags",
      "oldValue": "0",
      "newValue": "3"
    }
  ]
}
```

#### Response

```
{
  "status": "BEFORE_REPO_UPDATE_PROCEED",
  "message": "proceed"
}
```

* **status** and **message** are mandatory fields.

#### Possible Statuses

* `BeforeRepoUpdateStatus.BEFORE_REPO_UPDATE_PROCEED`: Allow the repository update to continue.
* `BeforeRepoUpdateStatus.BEFORE_REPO_UPDATE_STOP`: Block the repository update. In bulk update flows, a STOP aborts the entire batch.
* `BeforeRepoUpdateStatus.BEFORE_REPO_UPDATE_WARN`: Allow the update; log the Worker message as a warning.

### Before Repository Delete Worker Code Sample

The following section provides a sample code for a Before Repository Delete worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The Before Repository Delete event is blocking. Bulk deletes follow all-or-nothing blocking: a STOP on any repository aborts the entire batch.
</Callout>

```
export default async (
  context: PlatformContext,
  data: BeforeRepoDeleteRequest
): Promise<BeforeRepoDeleteResponse> => {
  if (data.metadata.hasReplication) {
    return {
      status: BeforeRepoDeleteStatus.BEFORE_REPO_DELETE_STOP,
      message: `Repository ${data.metadata.repositoryKey} has replication configured`
    };
  }
  return {
    status: BeforeRepoDeleteStatus.BEFORE_REPO_DELETE_PROCEED,
    message: "proceed"
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The repository delete request. No `config` or `changeAttributes` fields are present.

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  }
}
```

#### Response

```
{
  "status": "BEFORE_REPO_DELETE_PROCEED",
  "message": "proceed"
}
```

* **status** and **message** are mandatory fields.

#### Possible Statuses

* `BeforeRepoDeleteStatus.BEFORE_REPO_DELETE_PROCEED`: Allow repository deletion to continue.
* `BeforeRepoDeleteStatus.BEFORE_REPO_DELETE_STOP`: Block repository deletion. In bulk delete flows, a STOP aborts the entire batch.
* `BeforeRepoDeleteStatus.BEFORE_REPO_DELETE_WARN`: Allow deletion; log the Worker message as a warning.

### After Repository Create Worker Code Sample

The following section provides a sample code for an After Repository Create worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The After Repository Create event is non-blocking. Worker responses do not affect the repository create operation. Sensitive remote repository fields (for example, password, customHttpHeaders) are masked in the payload.
</Callout>

```
export default async (
  context: PlatformContext,
  data: AfterRepoCreateRequest
): Promise<AfterRepoCreateResponse> => {
  console.log(
    `Repository ${data.metadata.repositoryKey} was created by ${data.context.actor}`
  );
  return {
    message: "processed"
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The post-create repository event. Includes the persisted `config` with sensitive fields masked.

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  },
  "config": {
    "key": "my-docker-repo",
    "packageType": "Docker",
    "baseConfig": {
      "modelVersion": 2,
      "description": "",
      "notes": "",
      "repoLayoutRef": "simple-default",
      "includesPattern": "**/*",
      "excludesPattern": "",
      "federationConfig": {
        "gridTopologyId": null,
        "federationOnGrid": false,
        "members": [],
        "modificationDate": 0,
        "federated": false
      }
    },
    "repoTypeConfig": {
      "archiveBrowsingEnabled": false,
      "blackedOut": false,
      "cdnRedirectRepoConfig": null,
      "downloadRedirectConfig": null,
      "propertySetRefs": [
        "artifactory"
      ],
      "checksumPolicyType": "CLIENT",
      "priorityResolution": false,
      "maxUniqueSnapshots": 0,
      "handleReleases": true,
      "handleSnapshots": true,
      "snapshotVersionBehavior": "UNIQUE"
    },
    "packageTypeConfig": {
      "dockerTagRetention": "1",
      "blockPushingSchema1": "true",
      "dockerApiVersion": "V2",
      "maxUniqueTags": "0"
    },
    "securityConfig": {
      "primaryKeyPairRef": null,
      "secondaryKeyPairRef": null,
      "xrayConfig": null,
      "hideUnauthorizedResources": false,
      "keyPair": null,
      "signedUrlTtl": 90
    },
    "federation": null,
    "repoType": "LOCAL"
  }
}
```

#### Response

```
{
  "message": "processed"
}
```

* **message** is the only response field. The response is informational only and does not gate the repository operation.

### After Repository Update Worker Code Sample

The following section provides a sample code for an After Repository Update worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The After Repository Update event is non-blocking. Worker responses do not affect the repository update operation. Sensitive field changes in `changeAttributes` are masked (for example, password values appear as `***`).
</Callout>

```
export default async (
  context: PlatformContext,
  data: AfterRepoUpdateRequest
): Promise<AfterRepoUpdateResponse> => {
  console.log(
    `Repository ${data.metadata.repositoryKey} was updated by ${data.context.actor}`
  );
  console.log(`Changed attributes: ${data.changeAttributes.length}`);
  return {
    message: "processed"
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The post-update event. Includes `changeAttributes` instead of full config.

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  },
  "changeAttributes": [
    {
      "attributeName": "packageTypeConfig»maxUniqueTags",
      "oldValue": "0",
      "newValue": "3"
    }
  ]
}
```

#### Response

```
{
  "message": "processed"
}
```

* **message** is the only response field. The response is informational only and does not gate the repository operation.

### After Repository Delete Worker Code Sample

The following section provides a sample code for an After Repository Delete worker.

<Callout icon="📘" theme="info">
  ###

  **Note**

  The After Repository Delete event is non-blocking. Worker responses do not affect the repository delete operation.&#x20;
</Callout>

```
export default async (
  context: PlatformContext,
  data: AfterRepoDeleteRequest
): Promise<AfterRepoDeleteResponse> => {
  if (data.partial) {
    console.warn(
      `Repository ${data.metadata.repositoryKey} content deletion partially succeeded`
    );
  } else {
    console.log(
      `Repository ${data.metadata.repositoryKey} was deleted by ${data.context.actor}`
    );
  }
  return {
    message: "processed"
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The post-delete event.&#x20;

```
{
  "context": {
    "actor": "myorg/users/admin"
  },
  "metadata": {
    "repositoryKey": "my-docker-repo",
    "repositoryType": "local",
    "packageType": "docker",
    "isFederated": false,
    "project": null,
    "hasSharedProjects": false,
    "hasReplication": false,
    "environments": []
  },
  "userContext": {
    "id": "myorg/users/admin",
    "isToken": true,
    "realm": "internal",
    "triggerSource": "JFROG_UI"
  },
  "statusCode": 200
}
```

#### Response

```
{
  "message": "processed"
}
```

* **message** is the only response field. The response is informational only and does not gate the repository operation.

## Worker to Agent Integrations

Extend your AI agents with custom, deterministic actions to ensure critical software supply chain operations follow defined logic and policies. Explore ready-to-use integration samples and practical use cases to turn agent decisions into reliable actions across your DevSecOps workflows. For the samples on GitHub, see [AI Agents](https://github.com/jfrog/workers-sample/blob/main/ai-agents.md).

<Callout icon="far fa-circle-info" theme="info">
  **Usage Responsibility Notice**

  When integrating the JFrog Platform with third-party AI clients or agents, you are responsible for the configuration, management, and auditing of those integrations in accordance with your organization's policies. The behavior of third-party AI agents is governed by the terms and practices of their respective providers, not by JFrog.
</Callout>

<Callout icon="📘" theme="info">
  ###

  **Note**

  Platforms entitled to [JFrog Advanced Security (JAS)](/security/docs/advanced-security) or [JFrog Curation](/security/docs/curation-intro) can block downloads using a Before Download Worker's Stop response. Platforms without JAS or Curation can still deploy and run the Worker, but the Stop action is not enforced. If the Worker returns Stop, the download is not blocked and a warning is logged.
</Callout>

Use this table to open a sample.

| Integration     | Event           | Code sample                                                                 |
| :-------------- | :-------------- | :-------------------------------------------------------------------------- |
| NanoClaw        | After Download  | [NanoClaw Agent Vault Audit Log](#nanoclaw-agent-vault-audit-log)           |
| NanoClaw        | After Download  | [NanoClaw Slack Agent Trigger](#nanoclaw-slack-agent-trigger)               |
| NVIDIA NemoClaw | After Download  | [NVIDIA NemoClaw Skill Install Audit](#nvidia-nemoclaw-skill-install-audit) |
| Claude          | After Download  | [Claude Download Risk Advisor](#claude-download-risk-advisor)               |
| OpenAI          | After Download  | [OpenAI Download Risk Advisor](#openai-download-risk-advisor)               |
| GitHub Copilot  | After Download  | [GitHub Copilot Dependency Advisory](#github-copilot-dependency-advisory)   |
| GitHub Copilot  | Before Download | [GitHub Copilot Allowlist Gate](#github-copilot-allowlist-gate)             |
| Claude          | Before Download | [Claude Blocked Download Explainer](#claude-blocked-download-explainer)     |

### NanoClaw Agent Vault Audit Log

This After Download Worker records the artifact path, repository type, and registry identity for a download that NanoClaw's Agent Vault resolved through Artifactory, then posts that record to an audit endpoint. It does not block the download.

Set the `auditSinkBearerToken` secret and the `auditSinkUrl` property. Set `nanoclawIdentities` only when the repository also serves traffic that is not from NanoClaw.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse, RepoType } from './types';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // MODIFY TO FIT YOUR NEEDS
    const AUDIT_SINK_URL_PROPERTY = 'auditSinkUrl';
    // Comma-separated allowlist of the Artifactory token identities registered in the OneCLI Agent
    // Vault for your NanoClaw agent groups (`onecli secrets create --value <token> ...`). Left empty
    // (the default), every download from a filtered repo is audited - set this only if that repo is
    // shared with non-NanoClaw traffic and you want to audit NanoClaw's activity specifically.
    const NANOCLAW_IDENTITIES_PROPERTY = 'nanoclawIdentities';
    const SECRET_NAME = 'auditSinkBearerToken';

    let message = 'NanoClaw registry download successfully audited';
    try {
        const repoPath = data.metadata?.repoPath;
        const repoType = data.metadata?.repoType !== undefined ? RepoType[data.metadata.repoType] : 'UNKNOWN';

        const configuredIdentities = (context.properties.get(NANOCLAW_IDENTITIES_PROPERTY) || '')
            .split(',')
            .map((id) => id.trim())
            .filter(Boolean);
        if (configuredIdentities.length > 0 && !configuredIdentities.includes(data.userContext?.id ?? '')) {
            return {
                message: `Download identity '${data.userContext?.id}' is not a configured NanoClaw identity; skipping audit`,
            };
        }

        const auditSinkUrl = context.properties.get(AUDIT_SINK_URL_PROPERTY);
        if (!auditSinkUrl) {
            return { message: `Worker property '${AUDIT_SINK_URL_PROPERTY}' is not set; skipping audit` };
        }

        // userContext.id is the identity the OneCLI Agent Vault injected into the agent
        // container's outbound request - i.e. the credential shared by a NanoClaw agent
        // group, not a per-session/per-container id. See the README for the full flow.
        const auditRecord = {
            source: 'nanoclaw-agent-vault',
            registryIdentity: data.userContext?.id,
            isToken: data.userContext?.isToken,
            repoKey: repoPath?.key,
            artifactPath: repoPath?.path,
            repoType,
            downloadedAt: new Date().toISOString(),
        };

        const res = await context.clients.axios.post(auditSinkUrl, auditRecord, {
            headers: {
                Authorization: `Bearer ${context.secrets.get(SECRET_NAME)}`,
            },
        });

        if (res.status === 200) {
            console.log(`Audited NanoClaw download of '${repoPath?.id}' by '${auditRecord.registryIdentity}'`);
        } else {
            console.warn(`Failed to audit NanoClaw download. Status code: ${res.status}`);
            message = 'Failed to audit NanoClaw download';
        }
    } catch (error) {
        console.error(`Failed to audit NanoClaw download, caused by: ${(error as Error).message}`);
        message = 'Failed to audit NanoClaw download';
    }

    return {
        message,
    };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "NanoClaw registry download successfully audited" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### NanoClaw Slack Agent Trigger

This After Download Worker posts the download to Slack so a live NanoClaw agent ingests the message and can act on it. The message text starts with the `triggerPrefix` property, which must match the agent's engage pattern. It does not block the download.

Set the `slackBotToken` secret and the `slackChannelId` and `triggerPrefix` properties.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse, RepoType } from './types';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // MODIFY TO FIT YOUR NEEDS
    const SLACK_CHANNEL_PROPERTY = 'slackChannelId';
    // Must exactly match the `--engage-pattern` regex configured on the NanoClaw wiring for this
    // channel (`ncl wirings create --engage-mode pattern --engage-pattern "^<this value>"`), so the
    // wired agent group's router recognizes this message as input instead of ignoring it. See README.
    const TRIGGER_PREFIX_PROPERTY = 'triggerPrefix';
    const SECRET_NAME = 'slackBotToken';

    let message = 'NanoClaw agent notified via Slack';
    try {
        const repoPath = data.metadata?.repoPath;
        const repoType = data.metadata?.repoType !== undefined ? RepoType[data.metadata.repoType] : 'UNKNOWN';

        const channel = context.properties.get(SLACK_CHANNEL_PROPERTY);
        if (!channel) {
            return { message: `Worker property '${SLACK_CHANNEL_PROPERTY}' is not set; skipping Slack notification` };
        }

        const triggerPrefix = context.properties.get(TRIGGER_PREFIX_PROPERTY);
        if (!triggerPrefix) {
            return { message: `Worker property '${TRIGGER_PREFIX_PROPERTY}' is not set; skipping Slack notification` };
        }

        // The text below is the actual trigger: NanoClaw's Slack adapter ingests it like any other
        // channel message, and its router matches it against the wired agent group's pattern -
        // the agent then decides what to do with it (verify the package, reply, escalate, etc.).
        const text =
            `${triggerPrefix} '${repoPath?.path}' was resolved from repo '${repoPath?.key}' (${repoType}) ` +
            `by registry identity '${data.userContext?.id}'. Please verify this package.`;

        const res = await context.clients.axios.post(
            'https://slack.com/api/chat.postMessage',
            { channel, text },
            {
                headers: {
                    Authorization: `Bearer ${context.secrets.get(SECRET_NAME)}`,
                },
            },
        );

        // The Slack Web API returns HTTP 200 even on a logical failure; the real result is in the body.
        if (res.status === 200 && res.data?.ok) {
            console.log(`Notified NanoClaw agent in channel '${channel}' about '${repoPath?.id}'`);
        } else {
            console.warn(`Slack API rejected the notification: ${res.data?.error ?? res.status}`);
            message = 'Failed to notify NanoClaw agent via Slack';
        }
    } catch (error) {
        console.error(`Failed to notify NanoClaw agent via Slack, caused by: ${(error as Error).message}`);
        message = 'Failed to notify NanoClaw agent via Slack';
    }

    return {
        message,
    };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "NanoClaw agent notified via Slack" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### NVIDIA NemoClaw Skill Install Audit

This After Download Worker audits a skill archive downloaded from an Artifactory skills repository for a NemoClaw sandbox. It records the skill slug, version, registry identity, and Xray status, then posts that record to an audit endpoint. It does not block the download.

Set the `auditSinkBearerToken` secret and the `auditSinkUrl` property.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse, RepoType } from './types';
import { AxiosRequestConfig } from 'axios';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // MODIFY TO FIT YOUR NEEDS
    const AUDIT_SINK_URL_PROPERTY = 'auditSinkUrl';
    const SECRET_NAME = 'auditSinkBearerToken';

    let message = 'NemoClaw skill install successfully audited';
    try {
        const auditSinkUrl = context.properties.get(AUDIT_SINK_URL_PROPERTY);
        if (!auditSinkUrl) {
            return { message: `Worker property '${AUDIT_SINK_URL_PROPERTY}' is not set; skipping audit` };
        }

        const repoPath = data.metadata?.repoPath;
        const [slug, version] = parseSkillPath(repoPath?.path);
        const xrayStatus = await fetchXrayStatus(context, repoPath?.key, repoPath?.path);

        const auditRecord = {
            source: 'nemoclaw-skill-install',
            slug,
            version,
            repoKey: repoPath?.key,
            repoType: data.metadata?.repoType !== undefined ? RepoType[data.metadata.repoType] : 'UNKNOWN',
            registryIdentity: data.userContext?.id,
            isToken: data.userContext?.isToken,
            xrayStatus,
            downloadedAt: new Date().toISOString(),
        };

        const res = await context.clients.axios.post(auditSinkUrl, auditRecord, <AxiosRequestConfig>{
            headers: {
                Authorization: `Bearer ${context.secrets.get(SECRET_NAME)}`,
            },
        });

        if (res.status === 200) {
            console.log(`Audited NemoClaw skill install of '${repoPath?.id}' by '${auditRecord.registryIdentity}'`);
        } else {
            console.warn(`Failed to audit NemoClaw skill install. Status code: ${res.status}`);
            message = 'Failed to audit NemoClaw skill install';
        }
    } catch (error) {
        console.error(`Failed to audit NemoClaw skill install, caused by: ${(error as Error).message}`);
        message = 'Failed to audit NemoClaw skill install';
    }

    return {
        message,
    };
};

// Skill archives published via `jf skills publish` are stored as <slug>/<version>/<slug>-<version>.zip.
function parseSkillPath(path: string | undefined): [string | undefined, string | undefined] {
    const parts = path?.split('/');
    if (!parts || parts.length < 2) {
        return [undefined, undefined];
    }
    return [parts[0], parts[1]];
}

async function fetchXrayStatus(
    context: PlatformContext,
    repoKey: string | undefined,
    path: string | undefined,
): Promise<string> {
    if (!repoKey || !path) {
        return 'UNKNOWN';
    }
    try {
        const res = await context.clients.platformHttp.get(
            `/artifactory/api/skills/${repoKey}/xrayStatus?path=${encodeURIComponent(path)}`,
        );
        return res.data?.status ?? 'UNKNOWN';
    } catch (error) {
        console.warn(`Failed to fetch Xray status for '${repoKey}/${path}', caused by: ${(error as Error).message}`);
        return 'UNKNOWN';
    }
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "NemoClaw skill install successfully audited" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### Claude Download Risk Advisor

This After Download Worker looks up the artifact's existing Xray scan. Requires Xray. When the artifact has security issues or policy violations, it asks Claude, through the Anthropic Messages API, for a short risk summary and posts that summary to Slack. A clean artifact does not call Claude. It does not block the download.

Set the `AnthropicApiKey` secret to call Claude. Set the `Slack_URL` secret to post the summary. Without `AnthropicApiKey`, the Worker posts the raw Xray counts instead.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse } from './types';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // Configurable via the worker's "properties" (manifest.json / Platform UI); fall back to these defaults if unset
    // or if the platform errors out on an unknown property key instead of returning undefined.
    const minIssuesForAiSummary = parseInt(getProperty(context, 'minIssuesForAiSummary', '1'), 10);
    const claudeModel = getProperty(context, 'claudeModel', 'claude-sonnet-5'); // e.g. 'claude-haiku-4-5-20251001' to cut cost
    const claudeMaxTokens = parseInt(getProperty(context, 'claudeMaxTokens', '300'), 10); // response is a short summary, keep this small
    const claudeApiUrl = getProperty(context, 'claudeApiUrl', 'https://api.anthropic.com/v1/messages');
    const claudeApiVersion = getProperty(context, 'claudeApiVersion', '2023-06-01');

    if (!data.metadata?.repoPath) {
        return { message: 'Missing repoPath metadata on the download request.' };
    }

    const isXrayAvailable = await checkIfXrayAvailable(context);
    if (!isXrayAvailable) {
        return { message: 'Could not check for Xray scans because Xray is not available.' };
    }

    const repoPath = data.metadata.repoPath.path;
    const repoKey = data.metadata.repoPath.key;
    const artifactName = repoPath.slice(repoPath.lastIndexOf('/') + 1);
    const expectedRepoFullPath = `${repoKey}/${repoPath}`;

    let scanResult;
    try {
        const res = await context.clients.platformHttp.get(`/xray/api/v1/artifacts?repo=${repoKey}&search=${artifactName}&num_of_rows=100`);
        const responseData: XrayArtifactsSearchResponse = res.data;
        scanResult = responseData?.data?.find(artifact => artifact.repo_full_path === expectedRepoFullPath);
    } catch (error: any) {
        console.error(`Xray artifact search failed: ${error.message}`);
    }

    if (!scanResult) {
        return { message: 'Could not find an Xray scan result matching this artifact.' };
    }

    const critical = scanResult.sec_issues?.critical || 0;
    const high = scanResult.sec_issues?.high || 0;
    const medium = scanResult.sec_issues?.medium || 0;
    const low = scanResult.sec_issues?.low || 0;
    const violations = scanResult.violations || 0;

    if (critical + high + medium + low + violations < minIssuesForAiSummary) {
        return { message: 'No security issues or violations found for this artifact; skipped AI risk advisory.' };
    }

    const rawStats = `Artifact: ${artifactName}\nRepository: ${repoKey}\nSecurity issues: ${critical} critical, ${high} high, ${medium} medium, ${low} low\nPolicy violations: ${violations}`;
    const downloadedBy = `${data.userContext?.isToken ? 'token' : 'user'} ${data.userContext?.id}`;

    const anthropicApiKey = context.secrets.get('AnthropicApiKey');
    let advisoryText: string;
    let message: string;
    let aiSummarySucceeded = false;

    if (!anthropicApiKey) {
        advisoryText = rawStats;
        message = 'AnthropicApiKey secret not configured; posted raw Xray stats instead of an AI summary.';
    } else {
        try {
            advisoryText = await askClaudeForRiskSummary(context, anthropicApiKey, claudeModel, claudeMaxTokens, claudeApiUrl, claudeApiVersion, artifactName, repoKey, { critical, high, medium, low }, violations);
            message = 'AI risk summary generated';
            aiSummarySucceeded = true;
        } catch (error: any) {
            console.error(`Claude API call failed: ${error.message}`);
            advisoryText = rawStats;
            message = 'Failed to generate AI risk summary; posted raw Xray stats to Slack instead.';
        }
    }

    const slackWebhookUrl = context.secrets.get('Slack_URL');
    if (!slackWebhookUrl) {
        return { message: aiSummarySucceeded ? `${message}; Slack_URL not configured, logged only.` : message };
    }

    try {
        await context.clients.axios.post(slackWebhookUrl, {
            text: `*Download risk advisory*\nArtifact \`${expectedRepoFullPath}\` downloaded by ${downloadedBy}:\n${advisoryText}`
        });
        return { message: aiSummarySucceeded ? `${message} and posted to Slack.` : message };
    } catch (error: any) {
        console.warn(`Failed to post advisory to Slack: ${error.message}`);
        return { message };
    }
}

// Some platform versions throw instead of returning undefined when a property key isn't set yet
// (server-side bug, fixed but not deployed everywhere) - treat that the same as "unset".
function getProperty(context: PlatformContext, key: string, defaultValue: string): string {
    try {
        return context.properties.get(key) || defaultValue;
    } catch (error: any) {
        console.warn(`Failed to read property '${key}', using default '${defaultValue}': ${error.message}`);
        return defaultValue;
    }
}

async function checkIfXrayAvailable(context: PlatformContext): Promise<boolean> {
    try {
        const response = await context.clients.platformHttp.get('/xray/api/v1/system/ping');
        return response.data?.status === 'pong';
    } catch (error: any) {
        console.log(`Encountered error ${error.message} while checking for Xray readiness.`);
        return false;
    }
}

async function askClaudeForRiskSummary(
    context: PlatformContext,
    anthropicApiKey: string,
    claudeModel: string,
    claudeMaxTokens: number,
    claudeApiUrl: string,
    claudeApiVersion: string,
    artifactName: string,
    repoKey: string,
    secIssues: { critical: number; high: number; medium: number; low: number },
    violations: number
): Promise<string> {
    const prompt = `An artifact was just downloaded from JFrog Artifactory. Summarize the risk for someone who is not a security expert, in 2-3 sentences, then give one line of recommended action.\n\nArtifact: ${artifactName}\nRepository: ${repoKey}\nSecurity issues: ${secIssues.critical} critical, ${secIssues.high} high, ${secIssues.medium} medium, ${secIssues.low} low\nPolicy violations: ${violations}`;

    const res = await context.clients.axios.post(claudeApiUrl, {
        model: claudeModel,
        max_tokens: claudeMaxTokens,
        messages: [{ role: 'user', content: prompt }]
    }, {
        headers: {
            'x-api-key': anthropicApiKey,
            'anthropic-version': claudeApiVersion,
            'content-type': 'application/json'
        }
    });

    const text = res.data?.content?.[0]?.text;
    if (!text) {
        throw new Error('Claude response did not contain any text content.');
    }
    return text;
}

// Declared here rather than in types.ts: 'jf worker deploy' only uploads worker.ts and compiles it
// against the platform's own event types.
interface XrayArtifact {
    name: string;
    repo_path: string;
    repo_full_path: string;
    sec_issues: {
        critical: number;
        high: number;
        medium: number;
        low: number;
        total: number;
    };
    violations: number;
}

interface XrayArtifactsSearchResponse {
    data: XrayArtifact[];
    offset: number;
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "AI risk summary generated" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### OpenAI Download Risk Advisor

This After Download Worker uses the same Xray lookup and Slack advisory as the Claude sample. Requires Xray. It calls the OpenAI Chat Completions API. The default model is `gpt-4o-mini`. It does not block the download.

Set the `OpenAiApiKey` secret to call OpenAI. Set the `Slack_URL` secret to post the summary. Without `OpenAiApiKey`, the Worker posts the raw Xray counts instead.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse } from './types';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // Configurable via the worker's "properties" (manifest.json / Platform UI); fall back to these defaults if unset
    // or if the platform errors out on an unknown property key instead of returning undefined.
    const minIssuesForAiSummary = parseInt(getProperty(context, 'minIssuesForAiSummary', '1'), 10);
    const openAiModel = getProperty(context, 'openAiModel', 'gpt-4o-mini'); // e.g. 'gpt-4.1' for higher quality summaries
    const openAiMaxTokens = parseInt(getProperty(context, 'openAiMaxTokens', '300'), 10); // response is a short summary, keep this small
    const openAiApiUrl = getProperty(context, 'openAiApiUrl', 'https://api.openai.com/v1/chat/completions');

    if (!data.metadata?.repoPath) {
        return { message: 'Missing repoPath metadata on the download request.' };
    }

    const isXrayAvailable = await checkIfXrayAvailable(context);
    if (!isXrayAvailable) {
        return { message: 'Could not check for Xray scans because Xray is not available.' };
    }

    const repoPath = data.metadata.repoPath.path;
    const repoKey = data.metadata.repoPath.key;
    const artifactName = repoPath.slice(repoPath.lastIndexOf('/') + 1);
    const expectedRepoFullPath = `${repoKey}/${repoPath}`;

    let scanResult;
    try {
        const res = await context.clients.platformHttp.get(`/xray/api/v1/artifacts?repo=${repoKey}&search=${artifactName}&num_of_rows=100`);
        const responseData: XrayArtifactsSearchResponse = res.data;
        scanResult = responseData?.data?.find(artifact => artifact.repo_full_path === expectedRepoFullPath);
    } catch (error: any) {
        console.error(`Xray artifact search failed: ${error.message}`);
    }

    if (!scanResult) {
        return { message: 'Could not find an Xray scan result matching this artifact.' };
    }

    const critical = scanResult.sec_issues?.critical || 0;
    const high = scanResult.sec_issues?.high || 0;
    const medium = scanResult.sec_issues?.medium || 0;
    const low = scanResult.sec_issues?.low || 0;
    const violations = scanResult.violations || 0;

    if (critical + high + medium + low + violations < minIssuesForAiSummary) {
        return { message: 'No security issues or violations found for this artifact; skipped AI risk advisory.' };
    }

    const rawStats = `Artifact: ${artifactName}\nRepository: ${repoKey}\nSecurity issues: ${critical} critical, ${high} high, ${medium} medium, ${low} low\nPolicy violations: ${violations}`;
    const downloadedBy = `${data.userContext?.isToken ? 'token' : 'user'} ${data.userContext?.id}`;

    const openAiApiKey = context.secrets.get('OpenAiApiKey');
    let advisoryText: string;
    let message: string;
    let aiSummarySucceeded = false;

    if (!openAiApiKey) {
        advisoryText = rawStats;
        message = 'OpenAiApiKey secret not configured; posted raw Xray stats instead of an AI summary.';
    } else {
        try {
            advisoryText = await askOpenAiForRiskSummary(context, openAiApiKey, openAiModel, openAiMaxTokens, openAiApiUrl, artifactName, repoKey, { critical, high, medium, low }, violations);
            message = 'AI risk summary generated';
            aiSummarySucceeded = true;
        } catch (error: any) {
            console.error(`OpenAI API call failed: ${error.message}`);
            advisoryText = rawStats;
            message = 'Failed to generate AI risk summary; posted raw Xray stats to Slack instead.';
        }
    }

    const slackWebhookUrl = context.secrets.get('Slack_URL');
    if (!slackWebhookUrl) {
        return { message: aiSummarySucceeded ? `${message}; Slack_URL not configured, logged only.` : message };
    }

    try {
        await context.clients.axios.post(slackWebhookUrl, {
            text: `*Download risk advisory*\nArtifact \`${expectedRepoFullPath}\` downloaded by ${downloadedBy}:\n${advisoryText}`
        });
        return { message: aiSummarySucceeded ? `${message} and posted to Slack.` : message };
    } catch (error: any) {
        console.warn(`Failed to post advisory to Slack: ${error.message}`);
        return { message };
    }
}

// Some platform versions throw instead of returning undefined when a property key isn't set yet
// (server-side bug, fixed but not deployed everywhere) - treat that the same as "unset".
function getProperty(context: PlatformContext, key: string, defaultValue: string): string {
    try {
        return context.properties.get(key) || defaultValue;
    } catch (error: any) {
        console.warn(`Failed to read property '${key}', using default '${defaultValue}': ${error.message}`);
        return defaultValue;
    }
}

async function checkIfXrayAvailable(context: PlatformContext): Promise<boolean> {
    try {
        const response = await context.clients.platformHttp.get('/xray/api/v1/system/ping');
        return response.data?.status === 'pong';
    } catch (error: any) {
        console.log(`Encountered error ${error.message} while checking for Xray readiness.`);
        return false;
    }
}

async function askOpenAiForRiskSummary(
    context: PlatformContext,
    openAiApiKey: string,
    openAiModel: string,
    openAiMaxTokens: number,
    openAiApiUrl: string,
    artifactName: string,
    repoKey: string,
    secIssues: { critical: number; high: number; medium: number; low: number },
    violations: number
): Promise<string> {
    const prompt = `An artifact was just downloaded from JFrog Artifactory. Summarize the risk for someone who is not a security expert, in 2-3 sentences, then give one line of recommended action.\n\nArtifact: ${artifactName}\nRepository: ${repoKey}\nSecurity issues: ${secIssues.critical} critical, ${secIssues.high} high, ${secIssues.medium} medium, ${secIssues.low} low\nPolicy violations: ${violations}`;

    const res = await context.clients.axios.post(openAiApiUrl, {
        model: openAiModel,
        max_tokens: openAiMaxTokens,
        messages: [{ role: 'user', content: prompt }]
    }, {
        headers: {
            'Authorization': `Bearer ${openAiApiKey}`,
            'content-type': 'application/json'
        }
    });

    const text = res.data?.choices?.[0]?.message?.content;
    if (!text) {
        throw new Error('OpenAI response did not contain any message content.');
    }
    return text;
}

// Declared here rather than in types.ts: 'jf worker deploy' only uploads worker.ts and compiles it
// against the platform's own event types.
interface XrayArtifact {
    name: string;
    repo_path: string;
    repo_full_path: string;
    sec_issues: {
        critical: number;
        high: number;
        medium: number;
        low: number;
        total: number;
    };
    violations: number;
}

interface XrayArtifactsSearchResponse {
    data: XrayArtifact[];
    offset: number;
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "AI risk summary generated" // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### GitHub Copilot Dependency Advisory

This After Download Worker runs only for an artifact that has the `copilot.advisor.repo` and `copilot.advisor.repoBaseBranch` properties. On the first download of that artifact, it opens a GitHub issue and assigns the issue to the GitHub Copilot coding agent. Later downloads of the same artifact do nothing, because the Worker writes `copilot.advisor.notified` back onto the artifact. It does not block the download.

Set the `GitHubToken` secret to a personal access token. A GitHub App token cannot assign an issue to the Copilot coding agent.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { AfterDownloadRequest, AfterDownloadResponse } from './types';

// Artifact properties (set on the artifact itself in Artifactory, e.g. via `jf rt sp` or the UI)
// that opt an artifact into this advisory. An artifact without both is a NOP - this worker never
// picks a target repo on its own.
const REPO_PROPERTY = 'copilot.advisor.repo'; // e.g. "myorg/dependency-catalog"
const BASE_BRANCH_PROPERTY = 'copilot.advisor.repoBaseBranch'; // e.g. "main"
// Written back onto the artifact once an issue has been opened for it, so dedupe lives on the
// artifact itself rather than in the worker's own state (which is capped at a handful of small
// key-value pairs - not a fit for "remember every artifact ever downloaded").
const NOTIFIED_PROPERTY = 'copilot.advisor.notified';

export default async (context: PlatformContext, data: AfterDownloadRequest): Promise<AfterDownloadResponse> => {
    // Configurable via the worker's "properties" (manifest.json / Platform UI); fall back to this default if unset
    // or if the platform errors out on an unknown property key instead of returning undefined.
    const githubApiUrl = getProperty(context, 'githubApiUrl', 'https://api.github.com');
    const githubApiVersion = getProperty(context, 'githubApiVersion', '2022-11-28');

    const repoPath = data.metadata?.repoPath;
    if (!repoPath) {
        return { message: 'Missing repoPath metadata on the download request.' };
    }

    let artifactProperties: Record<string, string[]>;
    try {
        artifactProperties = await getArtifactProperties(context, repoPath.key, repoPath.path, [REPO_PROPERTY, BASE_BRANCH_PROPERTY, NOTIFIED_PROPERTY]);
    } catch (error: any) {
        console.error(`Failed to read artifact properties: ${error.message}`);
        return { message: `Failed to read artifact properties: ${error.message}` };
    }

    const githubRepo = artifactProperties[REPO_PROPERTY]?.[0];
    const githubBaseBranch = artifactProperties[BASE_BRANCH_PROPERTY]?.[0];
    if (!githubRepo || !githubBaseBranch) {
        return { message: `Artifact is not opted in (missing '${REPO_PROPERTY}' and/or '${BASE_BRANCH_PROPERTY}' property); skipped Copilot advisory.` };
    }

    // ponytail: no locking, so two downloads of the same never-before-notified artifact within the
    // same instant could both pass this check and each open an issue. Narrow, per-artifact race -
    // add a conditional/atomic property write if that duplicate is ever a real problem.
    if (artifactProperties[NOTIFIED_PROPERTY]?.[0] === 'true') {
        return { message: 'Artifact already notified before; skipped Copilot advisory.' };
    }

    const githubToken = context.secrets.get('GitHubToken');
    if (!githubToken) {
        return { message: 'New dependency detected but GitHubToken secret is not configured; skipped Copilot advisory.' };
    }

    const artifactName = repoPath.path.slice(repoPath.path.lastIndexOf('/') + 1);
    const downloadedBy = `${data.userContext?.isToken ? 'token' : 'user'} ${data.userContext?.id}`;

    let issueNumber: number;
    try {
        issueNumber = await createGithubIssue(context, githubApiUrl, githubApiVersion, githubToken, githubRepo, artifactName, repoPath.key, downloadedBy);
    } catch (error: any) {
        console.error(`Failed to open a GitHub issue: ${error.message}`);
        return { message: `New dependency detected but failed to open a GitHub issue: ${error.message}` };
    }

    // The issue exists at this point regardless of what happens next, so record that on the
    // artifact now - a failed Copilot assignment (or a failure here) shouldn't be retried as a
    // brand new issue on the next download of this same artifact.
    try {
        await setNotifiedProperty(context, repoPath.key, repoPath.path);
    } catch (error: any) {
        console.warn(`Failed to record '${NOTIFIED_PROPERTY}' on the artifact: ${error.message}`);
    }

    try {
        await assignToCopilot(context, githubApiUrl, githubApiVersion, githubToken, githubRepo, issueNumber, githubBaseBranch);
        return { message: `New dependency detected: opened issue #${issueNumber} in ${githubRepo} and assigned it to Copilot.` };
    } catch (error: any) {
        console.warn(`Failed to assign issue #${issueNumber} to Copilot: ${error.message}`);
        return { message: `New dependency detected: opened issue #${issueNumber} in ${githubRepo}, but failed to assign it to Copilot.` };
    }
}

// Some platform versions throw instead of returning undefined when a property key isn't set yet
// (server-side bug, fixed but not deployed everywhere) - treat that the same as "unset".
function getProperty(context: PlatformContext, key: string, defaultValue: string): string {
    try {
        return context.properties.get(key) || defaultValue;
    } catch (error: any) {
        console.warn(`Failed to read property '${key}', using default '${defaultValue}': ${error.message}`);
        return defaultValue;
    }
}

// Reads the given properties off the downloaded artifact via Artifactory's Item Properties API:
// https://jfrog.com/help/r/jfrog-rest-apis/item-properties
// Artifactory returns 404 when none of the requested properties are set on this item - that's a
// normal "not opted in" outcome here, not an error.
async function getArtifactProperties(context: PlatformContext, repoKey: string, path: string, keys: string[]): Promise<Record<string, string[]>> {
    try {
        const res = await context.clients.platformHttp.get(`/artifactory/api/storage/${repoKey}/${path}?properties=${keys.join(',')}`);
        return res.data?.properties || {};
    } catch (error: any) {
        if (error.status === 404) {
            return {};
        }
        throw error;
    }
}

// Writes the notified marker back onto the artifact via Artifactory's Set Item Properties API
// (same endpoint family as the read above): https://jfrog.com/help/r/jfrog-rest-apis/item-properties
async function setNotifiedProperty(context: PlatformContext, repoKey: string, path: string): Promise<void> {
    await context.clients.platformHttp.put(`/artifactory/api/storage/${repoKey}/${path}?properties=${NOTIFIED_PROPERTY}=true`);
}

async function createGithubIssue(
    context: PlatformContext,
    githubApiUrl: string,
    githubApiVersion: string,
    githubToken: string,
    githubRepo: string,
    artifactName: string,
    repoKey: string,
    downloadedBy: string
): Promise<number> {
    const res = await context.clients.axios.post(`${githubApiUrl}/repos/${githubRepo}/issues`, {
        title: `New dependency pulled: ${artifactName}`,
        body: `\`${artifactName}\` was downloaded from Artifactory repository \`${repoKey}\` for the first time (by ${downloadedBy}).\n\n` +
              `Could you vet this dependency - confirm it's an approved package, and add or update its usage notes in this repo if needed?`
    }, {
        headers: githubHeaders(githubToken, githubApiVersion)
    });

    const issueNumber = res.data?.number;
    if (!issueNumber) {
        throw new Error('GitHub response did not contain an issue number.');
    }
    return issueNumber;
}

// Assigning an issue to Copilot's coding agent is a dedicated endpoint, not a field on issue
// creation - see https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/use-cloud-agent-via-the-api.
// Requires a personal access token (Copilot usage is billed per-user); a GitHub App token won't work.
async function assignToCopilot(
    context: PlatformContext,
    githubApiUrl: string,
    githubApiVersion: string,
    githubToken: string,
    githubRepo: string,
    issueNumber: number,
    githubBaseBranch: string
): Promise<void> {
    await context.clients.axios.post(`${githubApiUrl}/repos/${githubRepo}/issues/${issueNumber}/assignees`, {
        assignees: ['copilot-swe-agent[bot]'],
        agent_assignment: {
            target_repo: githubRepo,
            base_branch: githubBaseBranch
        }
    }, {
        headers: githubHeaders(githubToken, githubApiVersion)
    });
}

function githubHeaders(githubToken: string, githubApiVersion: string): Record<string, string> {
    return {
        'Authorization': `Bearer ${githubToken}`,
        'Accept': 'application/vnd.github+json',
        'X-GitHub-Api-Version': githubApiVersion
    };
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 }
}
```

#### Response

```
{
 "message": "New dependency detected: opened issue #${issueNumber} in ${githubRepo} and assigned it to Copilot." // Message to print to the log, in case of an error, it will be printed as a warning
}
```

**message** : This is a mandatory field.

### GitHub Copilot Allowlist Gate

This Before Download Worker allows a download only when `<repoKey>/<path>` matches a glob in an allowlist file stored in GitHub. A blocked artifact gets a GitHub issue assigned to the GitHub Copilot coding agent. Copilot can open a pull request that adds a matching glob. The next download proceeds after that pull request is merged. By default (`failMode=WARN`), the download proceeds with a warning if the allowlist can't be read or the Worker is not configured. Set `failMode` to `STOP` to block in that case. A folder request proceeds without an allowlist check.

Set the `GitHubToken` secret and the `githubRepo` property. `allowlistPath`, `githubBranch`, `failMode`, and `issueProperty` have defaults in the code.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { BeforeDownloadRequest, BeforeDownloadResponse, DownloadStatus, RepoPath } from './types';

export default async (context: PlatformContext, data: BeforeDownloadRequest): Promise<BeforeDownloadResponse> => {
    // Configurable via the worker's "properties" (manifest.json / Platform UI); fall back to these defaults if unset.
    const githubRepo = getProperty(context, 'githubRepo', '');
    const githubBranch = getProperty(context, 'githubBranch', 'main');
    const githubApiUrl = getProperty(context, 'githubApiUrl', 'https://api.github.com');
    const githubApiVersion = getProperty(context, 'githubApiVersion', '2022-11-28');
    // Artifact property written onto a blocked artifact once a review issue has been opened for it, so later
    // downloads point at the same issue instead of opening a new one each time.
    const issueProperty = getProperty(context, 'issueProperty', 'copilot.allowlist.issue');
    // What to do when the allowlist can't be read (GitHub down, rate limited, invalid file): WARN lets the
    // download through with a warning, STOP blocks it.
    const failStatus = getProperty(context, 'failMode', 'WARN').toUpperCase() === 'STOP' ? DownloadStatus.DOWNLOAD_STOP : DownloadStatus.DOWNLOAD_WARN;

    const repoPath = data.repoPath ?? data.metadata?.repoPath;
    if (!repoPath) {
        return { status: DownloadStatus.DOWNLOAD_WARN, message: 'Missing repoPath on the download request; allowlist not checked.' };
    }
    if (repoPath.isFolder) {
        return { status: DownloadStatus.DOWNLOAD_PROCEED, message: 'Folder request; allowlist not checked.' };
    }

    const githubToken = context.secrets.get('GitHubToken');
    if (!githubRepo || !githubToken) {
        return { status: DownloadStatus.DOWNLOAD_WARN, message: "Worker is not configured (missing 'githubRepo' property and/or 'GitHubToken' secret); allowlist not checked." };
    }

    const github: GithubTarget = { apiUrl: githubApiUrl, apiVersion: githubApiVersion, token: githubToken, repo: githubRepo, branch: githubBranch };
    const allowlistPath = getProperty(context, 'allowlistPath', 'approved-dependencies.json').replace('{repoKey}', repoPath.key);
    const artifact = `${repoPath.key}/${repoPath.path}`;

    let allowlist: string[];
    try {
        allowlist = await fetchAllowlist(context, github, allowlistPath);
    } catch (error: any) {
        console.error(`Failed to read allowlist ${githubRepo}/${allowlistPath}@${githubBranch}: ${error.message}`);
        return { status: failStatus, message: `Could not read allowlist ${githubRepo}/${allowlistPath}: ${error.message}` };
    }

    if (allowlist.some((pattern) => globToRegExp(pattern).test(artifact))) {
        return { status: DownloadStatus.DOWNLOAD_PROCEED, message: `${artifact} is allowlisted.` };
    }

    // Not allowlisted: the download is blocked whatever happens below; the rest only decides which
    // review issue the message points the user to.
    const blocked = `${artifact} is not in allowlist ${githubRepo}/${allowlistPath}`;

    let existingIssue: string | undefined;
    try {
        existingIssue = await getIssueProperty(context, repoPath, issueProperty);
    } catch (error: any) {
        console.error(`Failed to read '${issueProperty}' on ${artifact}: ${error.message}`);
        return { status: DownloadStatus.DOWNLOAD_STOP, message: `${blocked}.` };
    }
    if (existingIssue) {
        return { status: DownloadStatus.DOWNLOAD_STOP, message: `${blocked}; review pending in ${existingIssue}` };
    }

    let issue: { number: number, url: string };
    try {
        issue = await createReviewIssue(context, github, allowlistPath, artifact);
    } catch (error: any) {
        console.error(`Failed to open a review issue: ${error.message}`);
        return { status: DownloadStatus.DOWNLOAD_STOP, message: `${blocked}; failed to open a review issue: ${error.message}` };
    }

    try {
        await setIssueProperty(context, repoPath, issueProperty, issue.url);
    } catch (error: any) {
        console.warn(`Failed to record '${issueProperty}' on ${artifact}: ${error.message}`);
    }

    try {
        await assignToCopilot(context, github, issue.number);
        return { status: DownloadStatus.DOWNLOAD_STOP, message: `${blocked}; opened ${issue.url} and assigned it to Copilot.` };
    } catch (error: any) {
        console.warn(`Failed to assign issue #${issue.number} to Copilot: ${error.message}`);
        return { status: DownloadStatus.DOWNLOAD_STOP, message: `${blocked}; opened ${issue.url}, but failed to assign it to Copilot.` };
    }
}

type GithubTarget = { apiUrl: string, apiVersion: string, token: string, repo: string, branch: string };

// Some platform versions throw instead of returning undefined when a property key isn't set yet
// (server-side bug, fixed but not deployed everywhere) - treat that the same as "unset".
function getProperty(context: PlatformContext, key: string, defaultValue: string): string {
    try {
        return context.properties.get(key) || defaultValue;
    } catch (error: any) {
        console.warn(`Failed to read property '${key}', using default '${defaultValue}': ${error.message}`);
        return defaultValue;
    }
}

// Reads the allowlist - a JSON array of globs - straight from the repo via the Contents API, using the raw
// media type so the body is the file itself rather than base64: https://docs.github.com/en/rest/repos/contents
// A missing file is an empty allowlist (everything blocked), so the first Copilot PR can create it.
// ponytail: one GitHub call per download, no cache. Mind the 5000 req/h PAT limit on busy repos; cache the
// file in context.state keyed by ETag if that becomes a problem.
async function fetchAllowlist(context: PlatformContext, github: GithubTarget, allowlistPath: string): Promise<string[]> {
    let body: any;
    try {
        const res = await context.clients.axios.get(`${github.apiUrl}/repos/${github.repo}/contents/${allowlistPath}?ref=${encodeURIComponent(github.branch)}`, {
            headers: { ...githubHeaders(github), 'Accept': 'application/vnd.github.raw+json' }
        });
        body = res.data;
    } catch (error: any) {
        if ((error.status ?? error.response?.status) === 404) {
            return [];
        }
        throw error;
    }

    const allowlist = typeof body === 'string' ? JSON.parse(body) : body;
    if (!Array.isArray(allowlist) || !allowlist.every((entry) => typeof entry === 'string')) {
        throw new Error('allowlist must be a JSON array of strings');
    }
    return allowlist;
}

// Matches "<repoKey>/<path>": "**" spans folders, "*" stays within one path segment, "?" is one character.
function globToRegExp(glob: string): RegExp {
    const source = glob
        .split('**')
        .map((part) => part
            .split('*')
            .map((sub) => sub.split('?').map(escapeRegExp).join('[^/]'))
            .join('[^/]*'))
        .join('.*');
    return new RegExp(`^${source}$`);
}

function escapeRegExp(text: string): string {
    return text.replace(/[.+^${}()|[\]\\]/g, '\\$&');
}

// Item Properties API: https://jfrog.com/help/r/jfrog-rest-apis/item-properties
// Artifactory returns 404 when the requested property isn't set - that just means no issue yet.
async function getIssueProperty(context: PlatformContext, repoPath: RepoPath, issueProperty: string): Promise<string | undefined> {
    try {
        const res = await context.clients.platformHttp.get(`/artifactory/api/storage/${repoPath.key}/${repoPath.path}?properties=${issueProperty}`);
        return res.data?.properties?.[issueProperty]?.[0];
    } catch (error: any) {
        if (error.status === 404) {
            return undefined;
        }
        throw error;
    }
}

async function setIssueProperty(context: PlatformContext, repoPath: RepoPath, issueProperty: string, issueUrl: string): Promise<void> {
    await context.clients.platformHttp.put(`/artifactory/api/storage/${repoPath.key}/${repoPath.path}?properties=${issueProperty}=${encodeURIComponent(issueUrl)}`);
}

async function createReviewIssue(context: PlatformContext, github: GithubTarget, allowlistPath: string, artifact: string): Promise<{ number: number, url: string }> {
    const res = await context.clients.axios.post(`${github.apiUrl}/repos/${github.repo}/issues`, {
        title: `Allowlist review: ${artifact}`,
        body: `A download of \`${artifact}\` from Artifactory was blocked because it doesn't match any entry in \`${allowlistPath}\`.\n\n` +
              `Please vet this dependency (license, maintenance, known vulnerabilities). If it is acceptable, open a PR against \`${github.branch}\` ` +
              `that adds a glob matching it to \`${allowlistPath}\` (a JSON array of strings; \`*\` matches within a path segment, \`**\` across segments), ` +
              `and summarize your findings in the PR description. If it is not acceptable, explain why in this issue and don't open a PR.`
    }, {
        headers: githubHeaders(github)
    });

    const { number, html_url } = res.data ?? {};
    if (!number || !html_url) {
        throw new Error('GitHub response did not contain an issue number and URL.');
    }
    return { number, url: html_url };
}

// Assigning an issue to Copilot's coding agent is a dedicated endpoint, not a field on issue
// creation - see https://docs.github.com/en/copilot/how-tos/use-copilot-agents/cloud-agent/use-cloud-agent-via-the-api.
// Requires a personal access token (Copilot usage is billed per-user); a GitHub App token won't work.
async function assignToCopilot(context: PlatformContext, github: GithubTarget, issueNumber: number): Promise<void> {
    await context.clients.axios.post(`${github.apiUrl}/repos/${github.repo}/issues/${issueNumber}/assignees`, {
        assignees: ['copilot-swe-agent[bot]'],
        agent_assignment: {
            target_repo: github.repo,
            base_branch: github.branch
        }
    }, {
        headers: githubHeaders(github)
    });
}

function githubHeaders(github: GithubTarget): Record<string, string> {
    return {
        'Authorization': `Bearer ${github.token}`,
        'Accept': 'application/vnd.github+json',
        'X-GitHub-Api-Version': github.apiVersion
    };
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request?
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to Artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 },
 "repoPath": { // The response repository path
   "key": "key",
   "path": "path",
   "id": "key:path",
   "isRoot": false,
   "isFolder": false
 }
}
```

#### Response

```
{
 "message": "${artifact} is allowlisted.", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": DownloadStatus.DOWNLOAD_PROCEED // The instruction of how to proceed
}
```

* **message** and **status** : These are mandatory fields.

##### Possible Statuses

* `DownloadStatus.DOWNLOAD_PROCEED` - The worker allows to proceed with download.
* `DownloadStatus.DOWNLOAD_STOP` - The worker forbids download. Download will be aborted.
* `DownloadStatus.DOWNLOAD_WARN` - The worker allows to proceed with download. A warning log with the provided message will be recorded in Artifactory.

### Claude Blocked Download Explainer

This Before Download Worker blocks a download when the artifact's existing Xray scan has more critical security issues than `maxCriticalIssues` (default `0`). The count decides the block. Claude, through the Anthropic Messages API, writes the explanation only, and only for a blocked download. If Claude is unavailable, the download stays blocked and the Worker returns the static message. If Xray is unavailable, the artifact has no scan result, or the Xray search fails, the download proceeds with a warning.

Set `AnthropicApiKey` to include the explanation. Set `Slack_URL` to post the block message. Both secrets are optional.

```typescript
import { PlatformContext } from 'jfrog-workers';
import { BeforeDownloadRequest, BeforeDownloadResponse, DownloadStatus } from './types';

export default async (context: PlatformContext, data: BeforeDownloadRequest): Promise<BeforeDownloadResponse> => {
    // Configurable via the worker's "properties" (manifest.json / Platform UI); fall back to these defaults if unset
    // or if the platform errors out on an unknown property key instead of returning undefined.
    const maxCriticalIssues = parseInt(getProperty(context, 'maxCriticalIssues', '0'), 10);
    const claudeModel = getProperty(context, 'claudeModel', 'claude-haiku-4-5-20251001'); // fast model: this call is on the download path
    const claudeMaxTokens = parseInt(getProperty(context, 'claudeMaxTokens', '200'), 10);
    const claudeApiUrl = getProperty(context, 'claudeApiUrl', 'https://api.anthropic.com/v1/messages');
    const claudeApiVersion = getProperty(context, 'claudeApiVersion', '2023-06-01');

    if (!data.metadata?.repoPath) {
        return warn('Missing repoPath metadata on the download request. Download will proceed with warning.');
    }

    const isXrayAvailable = await checkIfXrayAvailable(context);
    if (!isXrayAvailable) {
        return warn('Could not check for Xray scans because Xray is not available. Download will proceed with warning.');
    }

    const repoPath = data.metadata.repoPath.path;
    const repoKey = data.metadata.repoPath.key;
    const artifactName = repoPath.slice(repoPath.lastIndexOf('/') + 1);
    const expectedRepoFullPath = `${repoKey}/${repoPath}`;

    let critical: number;
    try {
        const res = await context.clients.platformHttp.get(`/xray/api/v1/artifacts?repo=${repoKey}&search=${artifactName}&num_of_rows=100`);
        const responseData: XrayArtifactsSearchResponse = res.data;
        const scanResult = responseData?.data?.find(artifact => artifact.repo_full_path === expectedRepoFullPath);
        if (!scanResult) {
            return warn('Could not find an Xray scan result matching this artifact. Download will proceed with warning.');
        }
        critical = scanResult.sec_issues?.critical || 0;
    } catch (error: any) {
        console.error(`Xray artifact search failed: ${error.message}`);
        return warn('Error during scan check. Download will proceed with warning.');
    }

    // The decision is deterministic: Claude never decides whether a download is blocked, it only explains it.
    if (critical <= maxCriticalIssues) {
        return { status: DownloadStatus.DOWNLOAD_PROCEED, message: `Artifact has ${critical} critical security issues (limit ${maxCriticalIssues}): proceed with the download.`, headers: {} };
    }

    const blockedMessage = `DOWNLOAD STOPPED: ${expectedRepoFullPath} has ${critical} critical security issues (limit ${maxCriticalIssues}).`;

    // Clients send HEAD and checksum requests too; only spend a Claude call on the actual download.
    if (data.metadata.headOnly || data.metadata.checksum) {
        return stop(blockedMessage);
    }

    let message = blockedMessage;
    const anthropicApiKey = context.secrets.get('AnthropicApiKey');
    if (!anthropicApiKey) {
        console.warn('AnthropicApiKey secret not configured; returning the static block message.');
    } else {
        try {
            const issues = await getCriticalIssues(context, repoKey, repoPath);
            const explanation = await askClaudeToExplainBlock(context, anthropicApiKey, claudeModel, claudeMaxTokens, claudeApiUrl, claudeApiVersion, artifactName, critical, maxCriticalIssues, issues);
            message = `${blockedMessage} ${explanation}`;
        } catch (error: any) {
            console.error(`Failed to generate AI explanation: ${error.message}`);
        }
    }

    // Many clients only show the HTTP status of a blocked download, so also send the explanation to Slack.
    await notifySlack(context, `${data.userContext?.isToken ? 'Token' : 'User'} ${data.userContext?.id}`, message);
    return stop(message);
}

async function notifySlack(context: PlatformContext, blockedFor: string, message: string): Promise<void> {
    const slackWebhookUrl = context.secrets.get('Slack_URL');
    if (!slackWebhookUrl) {
        return;
    }
    try {
        await context.clients.axios.post(slackWebhookUrl, { text: `*Download blocked* for ${blockedFor}\n${message}` });
    } catch (error: any) {
        console.warn(`Failed to post block notification to Slack: ${error.message}`);
    }
}

function warn(message: string): BeforeDownloadResponse {
    return { status: DownloadStatus.DOWNLOAD_WARN, message, headers: {} };
}

function stop(message: string): BeforeDownloadResponse {
    return { status: DownloadStatus.DOWNLOAD_STOP, message, headers: {} };
}

// Some platform versions throw instead of returning undefined when a property key isn't set yet
// (server-side bug, fixed but not deployed everywhere) - treat that the same as "unset".
function getProperty(context: PlatformContext, key: string, defaultValue: string): string {
    try {
        return context.properties.get(key) || defaultValue;
    } catch (error: any) {
        console.warn(`Failed to read property '${key}', using default '${defaultValue}': ${error.message}`);
        return defaultValue;
    }
}

async function checkIfXrayAvailable(context: PlatformContext): Promise<boolean> {
    try {
        const response = await context.clients.platformHttp.get('/xray/api/v1/system/ping');
        return response.data?.status === 'pong';
    } catch (error: any) {
        console.log(`Encountered error ${error.message} while checking for Xray readiness.`);
        return false;
    }
}

// The artifacts search only returns counts; the summary API gives the CVEs, and each issue summary states the
// affected version range (e.g. "jackson-databind before 2.9.10"), which is what Claude needs to suggest an upgrade.
// Best effort: Claude can still explain from counts alone.
async function getCriticalIssues(context: PlatformContext, repoKey: string, repoPath: string): Promise<string[]> {
    try {
        const res = await context.clients.platformHttp.post('/xray/api/v1/summary/artifact', { paths: [`default/${repoKey}/${repoPath}`] });
        const summary: XrayArtifactSummaryResponse = res.data;
        const artifact = summary?.artifacts?.[0];
        const issues = (artifact?.issues || [])
            .filter(issue => issue.severity === 'Critical')
            // All of them: an upgrade advised from a partial list can still be vulnerable. Capped only to bound the prompt.
            .slice(0, 30)
            .map(issue => {
                const cves = (issue.cves || []).map(c => c.cve).filter(Boolean).join(', ');
                return `${cves || issue.issue_id}: ${(issue.summary || '').slice(0, 300)}`;
            });
        const componentId = artifact?.general?.component_id;
        return componentId && issues.length ? [`Component: ${componentId}`, ...issues] : issues;
    } catch (error: any) {
        console.warn(`Xray artifact summary failed, explaining from counts only: ${error.message}`);
        return [];
    }
}

async function askClaudeToExplainBlock(
    context: PlatformContext,
    anthropicApiKey: string,
    claudeModel: string,
    claudeMaxTokens: number,
    claudeApiUrl: string,
    claudeApiVersion: string,
    artifactName: string,
    critical: number,
    maxCriticalIssues: number,
    issues: string[]
): Promise<string> {
    const prompt = `A developer's download of an artifact from JFrog Artifactory was just blocked by a security policy. Their package manager will print your answer as the error message. In at most 2 short sentences and plain text (no markdown, no line breaks), tell them the main reason and the most useful next step. Only recommend a specific version if it is above every affected version range listed below (a range "through X" includes X); otherwise tell them to upgrade to the latest release. Do not invent CVEs or versions that are not listed below.\n\nArtifact: ${artifactName}\nPolicy: at most ${maxCriticalIssues} critical security issues allowed\nCritical security issues found: ${critical}\n${issues.length ? `Details:\n- ${issues.join('\n- ')}` : 'No further details available.'}`;

    // No client-side timeout: the Workers runtime rejects axios' 'timeout' option and has no clearTimeout,
    // and a pending timer promise left by Promise.race fails the execution. Latency is bounded by the fast
    // model, the small max_tokens, and the platform's execution time limit.
    const res = await context.clients.axios.post(claudeApiUrl, {
        model: claudeModel,
        max_tokens: claudeMaxTokens,
        messages: [{ role: 'user', content: prompt }]
    }, {
        headers: {
            'x-api-key': anthropicApiKey,
            'anthropic-version': claudeApiVersion,
            'content-type': 'application/json'
        }
    });

    const text = res.data?.content?.[0]?.text;
    if (!text) {
        throw new Error('Claude response did not contain any text content.');
    }
    // The message ends up in a client error output: keep it on one line.
    return text.replace(/\s+/g, ' ').trim();
}

// Declared here rather than in types.ts: 'jf worker deploy' only uploads worker.ts and compiles it
// against the platform's own event types.
interface XrayArtifact {
    name: string;
    repo_path: string;
    repo_full_path: string;
    sec_issues: {
        critical: number;
        high: number;
        medium: number;
        low: number;
        total: number;
    };
    violations: number;
}

interface XrayArtifactsSearchResponse {
    data: XrayArtifact[];
    offset: number;
}

/** Subset of POST /xray/api/v1/summary/artifact used by this worker */
interface XrayArtifactSummaryResponse {
    artifacts: Array<{
        general?: { component_id?: string };
        issues: Array<{
            issue_id: string;
            summary: string;
            severity: string;
            cves?: Array<{ cve?: string }>;
        }>;
    }>;
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with download details sent by Artifactory.

```
{
 "metadata": { // Various immutable download metadata
   "repoPath": { // The repository path object of the request
     "key": "key", // The repository key
     "path": "path", // The path itself
     "id": "key:path", // The key:path combination
     "isRoot": false, // Is the path the root?
     "isFolder": false  // Is the path a folder?
   },
   "originalRepoPath": { // The original repository path if a virtual repository is involved
     "key": "key",
     "path": "path",
     "id": "key:path",
     "isRoot": false,
     "isFolder": false
   },
   "name": "name", // The file name from path
   "headOnly": false, // Is it a head request?
   "checksum": false, // Is it a checksum request?
   "recursive": false, // Is it a recursive request?
   "modificationTime": 0, // When a modification has occurred
   "directoryRequest": false, // Is it a directory request?
   "metadata": false, // Is it a metadata request?
   "lastModified": 1, // Last modification time that occurred
   "ifModifiedSince": 0, // If a modification happened since the last modification time
   "servletContextUrl": "base", // The URL that points to Artifactory
   "uri": "jfrog.com", // The request URI
   "clientAddress": "localhost", // The client address
   "zipResourcePath": "", // The resource path of the requested zip
   "zipResourceRequest": false, // Is the request a zip resource request?
   "replaceHeadRequestWithGet": false, // Should the head request be replaced with GET?
   "repoType": 1 // Repository type
 },
 "headers": { // The immutable request headers
   "key": {
     "value": []
   }
 },
 "userContext": { // The user context that sends the request
   "id": "id", // The username or subject
   "isToken": false, // Is the context an accessToken?
   "realm": "realm" // The realm of the user
 },
 "repoPath": { // The response repository path
   "key": "key",
   "path": "path",
   "id": "key:path",
   "isRoot": false,
   "isFolder": false
 }
}
```

#### Response

```
{
 "message": "Artifact has ${critical} critical security issues (limit ${maxCriticalIssues}): proceed with the download.", // Message to print to the log, in case of an error, it will be printed as a warning
 "status": DownloadStatus.DOWNLOAD_PROCEED, // The instruction of how to proceed
 "headers": {} // Response headers to add/override, if any
}
```

* **message** and **status** : These are mandatory fields.
* **headers** : Response headers to add/override, if any.

##### Possible Statuses

* `DownloadStatus.DOWNLOAD_PROCEED` - The worker allows to proceed with download.
* `DownloadStatus.DOWNLOAD_STOP` - The worker forbids download. Download will be aborted.
* `DownloadStatus.DOWNLOAD_WARN` - The worker allows to proceed with download. A warning log with the provided message will be recorded in Artifactory.

## Access Workers Code Samples

The following sections provide code samples for workers. For event descriptions, see [Worker Event Types](https://docs.jfrog.com/administration/docs/worker-event-types).

| Worker                     | Code Sample                                                                       |
| :------------------------- | :-------------------------------------------------------------------------------- |
| Before Create Token Worker | [Before Create Token Worker Code Sample](#before-create-token-worker-code-sample) |
| Before Revoke Token Worker | [Before Revoke Token Worker Code Sample](#before-revoke-token-worker-code-sample) |
| Before Token Expiry Worker | [Before Token Expiry Worker Code Sample](#before-token-expiry-worker-code-sample) |

### Before Create Token Worker Code Sample

The following section provides a sample code for a Before Create Token worker.

```
export default async (context: PlatformContext, data: BeforeCreateTokenRequest): Promise<BeforeCreateTokenResponse> => {

    let status: CreateTokenStatus = CreateTokenStatus.CREATE_TOKEN_UNSPECIFIED;
    let message = 'Overwritten by worker-service if an error occurs.';

    try {
        // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
        //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
        const res = await context.clients.platformHttp.get('/access/api/v1/config/token/default_expiry');

        // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
        if (res.status === 200) {
            const defaultExpiry = res.data.default_token_expiration;
            const tokenExpiry = data.tokenSpec.expiresIn;
            console.log(`Got default token expiry ${defaultExpiry}`);
            if (data.tokenSpec.scope.includes('applied-permissions/admin')
                    && defaultExpiry > 0
                    && (!tokenExpiry || (tokenExpiry > defaultExpiry))) {
                status = CreateTokenStatus.CREATE_TOKEN_STOP;
                message = 'Admin token generation with expiry greater that default expiry is not allowed';
            } else {
                status = CreateTokenStatus.CREATE_TOKEN_PROCEED;
            }
        } else {
            status = CreateTokenStatus.CREATE_TOKEN_WARN;
            console.warn(`Request is successful but returned status other than 200. Status code : ${ res.status }`);
        }
    } catch(error) {
        // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
        status = CreateTokenStatus.CREATE_TOKEN_STOP;
        console.error(`Request failed with status code ${ error.status || '<none>' } caused by : ${ error.message }`);
    }

    return {
        status,
        message,
    }
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with delete details sent by Artifactory.

```
{
  "tokenSpec": {
    "subject": "user",
    "owner": "jfwks@000",
    "scope": [
      "applied-permissions/user"
    ],
    "audience": [
      "*@*"
    ],
    "expiresIn": 3600,
    "refreshable": false,
    "extension": "extension",
    "description": "description",
    "includeReferenceToken": true
  },
  "userContext": {
    "id": "id",
    "isToken": false,
    "realm": "realm"
  }
}
```

###### Response

```
{
  "status": CreateTokenStatus.CREATE_TOKEN_PROCEED,
  "message": "Overwritten by worker-service if an error occurs.",
}
```

###### Possible Statuses

* `CreateTokenStatus.CREATE_TOKEN_PROCEED` - The worker allows Artifactory to proceed with creating a token.
* `CreateTokenStatus.CREATE_TOKEN_STOP` - The worker does not allow Artifactory to create a token.
* `CreateTokenStatus.CREATE_TOKEN_WARN` - The worker provides a warning before Artifactory can proceed with creating a token.

### Before Revoke Token Worker Code Sample

The following section provides a sample code for a Before Revoke Token worker.

```
export default async (context: PlatformContext, data: BeforeRevokeTokenRequest): Promise<BeforeRevokeTokenResponse> => {

    let status: RevokeTokenStatus = RevokeTokenStatus.REVOKE_TOKEN_PROCEED;
    let message = 'Overwritten by worker-service if an error occurs.';

    if (data.token.description?.startsWith('protected')) {
        console.log(`Token description starts with 'protected'. Checking if it is the last protected token.`);
        try {
            // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
            //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
            const res = await context.clients.platformHttp.get('/access/api/v1/tokens?description=protected*');

            // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
            if (res.status === 200) {
                const protectedTokensCount = res.data.tokens?.length;
                console.log(`Number of protected tokens: ${protectedTokensCount}`);
                // If request includes multiple tokens to revoke, worker code will be executed for each token
                // In such case the last protected token may be revoked
                if (protectedTokensCount <= 1) {
                    status = RevokeTokenStatus.REVOKE_TOKEN_STOP;
                    message = 'Revocation of the last protected token is not allowed';
                    console.warn(message);
                }
            } else {
                status = RevokeTokenStatus.REVOKE_TOKEN_WARN;
                console.warn(`Request is successful but returned status other than 200. Status code : ${ res.status }`);
            }
        } catch(error) {
            // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
            status = RevokeTokenStatus.REVOKE_TOKEN_STOP;
            console.error(`Request failed with status code ${ error.status || '<none>' } caused by : ${ error.message }`);
        }
    }

    return {
        status,
        message,
    }
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with details sent by Access.

```
{
    token: {
        id: 'id',
        subject: 'user',
        owner: 'jfwks@000',
        scope: 'applied-permissions/user',
        audience: '*@*',
        expirationTime: 1717171717,
        created: 1717161717,
        type: 'generic',
        username: 'username',
        description: 'description',
        projectKey: 'projectKey',
    },
    userContext: { id: 'id', isToken: false, realm: 'realm' },
}
```

###### Response

```
{
  "status": RevokeTokenStatus.REVOKE_TOKEN_PROCEED,
  "message": "Overwritten by worker-service if an error occurs.",
  "executionStatus": "STATUS_SUCCESS"
}
```

###### Possible Statuses

* `RevokeTokenStatus.REVOKE_TOKEN_PROCEED` - The worker allows Artifactory to proceed with revoking a token.
* `RevokeTokenStatus.REVOKE_TOKEN_STOP` - The worker does not allow Artifactory to revoke a token.
* `RevokeTokenStatus.REVOKE_TOKEN_WARN` - The worker provides a warning before Artifactory can proceed with revoking a token.

### Before Token Expiry Worker Code Sample

The following section provides a sample code for a Before Token Expiry worker.

```
export default async (
  context: PlatformContext,
  data: BeforeTokenExpiryRequest
): Promise<BeforeTokenExpiryResponse> => {
  try {
    // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
    //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
    const res = await context.clients.platformHttp.get(
      "/artifactory/api/v1/system/readiness"
    );

    // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
    if (res.status === 200) {
      console.log("Artifactory ping success");
    } else {
      console.warn(
        `Request is successful but returned status other than 200. Status code : ${res.status}`
      );
    }
  } catch (error) {
    // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
    console.error(
      `Request failed with status code ${
        error.status || "<none>"
      } caused by : ${error.message}`
    );
  }

  return {
    message: `Acknowledged tokens that are about to expire: ${data.tokens.length}`,
  };
};
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with details sent by Access.

```
export interface BeforeTokenExpiryRequest {
    /** The tokens that will expire */
    tokens:
            | Array<Token>
            | undefined;
    /** Contextual information about the user who triggered the event */
    userContext: {
        /** The username or token subject */
        id: string;
        /** Indicates if the user is authenticated via an access token */
        isToken: boolean;
        /** The realm in which the user is authenticated */
        realm: string;
    };
}

export interface Token {
    /** The token id to revoke */
    id: string
    /** The subject the token belongs to */
    subject: string;
    /** The owner of the token */
    owner: string;
    /** The scope of the token*/
    scope: string;
    /** The audience (i.e. services) this token is aimed for. These services are expected to accept this token */
    audience: string;
    /** The time (epoch) this token expires (optional if it has no expiration time) */
    expirationTime: number;
    /** The time (epoch) this token was created */
    created: number;
    /** Token type. Could be session or generic */
    type: string;
    /** Optional username derived from the token subject */
    username: string;
    /** Optional free text describing the token */
    description: string;
    /** The project key associated with the token */
    projectKey: string;
}
```

###### Response

```
export interface BeforeTokenExpiryResponse {
    /** Message to print to the log, in case of an error it will be printed as a warning */
    message: string;
}
{
  "status": CreateTokenStatus.CREATE_TOKEN_PROCEED,
  "message": "Overwritten by worker-service if an error occurs.",
}
```

<br />

```json
{
  "continue": true
}

```

<br />

## Runtime Workers Code Samples

### After Runtime Workload State Change Worker Code Sample

Use the following code sample for an After Runtime Workload State Change worker.

```typescript
export default async (context: PlatformContext, data: AfterWorkloadStateChangeRequest): Promise<AfterWorkloadStateChangeResponse> => {

    try {
        // The HTTP client facilitates calls to the JFrog Platform REST APIs
        // To call an external endpoint, use 'await context.clients.axios.get("[https://foo.com](https://foo.com)")'
        const res = await context.clients.platformHttp.get('/runtime/api/v1/system/readiness');

        // You'll reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
        if (res.status === 200) {
            console.log("Runtime ping success");
        } else {
            console.warn(`Request was successful and returned status code : ${res.status}`);
        }
    } catch (error) {
        // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
        console.error(`Request failed with status code ${error.status || '<none>'} caused by : ${error.message}`)
    }

    return {
        'continue': true,
    }
}
```

#### Input Parameters

##### Context

Use the `context` parameter to access the `baseUrl`, `token`, and `clients` needed to communicate with the JFrog Platform. For more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext).

##### Data

The request details sent by JFrog Runtime:

```json
{
  "change_type": "workload",
  "workload_changed_object": {
    "name": "frontend-service",
    "namespace": "production",
    "cluster": "production-euc1",
    "nodes": ["node-1", "node-2"],
    "risks": ["untrusted_registry_images", "critical_and_applicable_cves"],
    "vulnerabilities_count": 5
  },
  "image_tags_object": [
    {
      "name": "frontend-image",
      "registry": "docker.io",
      "repository_path": "company/frontend",
      "architecture": "amd64",
      "tag": "v1.2.3",
      "sha256": "bcek9g0025d450f7865cnl97jebea13108166f81fe414620696klnb4d96c00f",
      "risks": ["critical_and_applicable_cves"],
      "vulnerabilities": [
        {
          "package_type": "npm",
          "xray_id": "XRAY-2024-001",
          "cve_id": "CVE-2024-1234",
          "severity": "Critical",
          "cvss_v2": "6.5",
          "cvss_v3": "8.2",
          "last_fetched": "2025-02-15T12:00:00Z",
          "issue_kind": 1,
          "applicability": "applicable",
          "components": [
            {
              "component_id": "npm:lodash",
              "name": "lodash",
              "version": "4.17.21"
            }
          ]
        }
      ],
      "malicious_packages": null,
      "deployed_by": "jenkins-user",
      "build_info": {
        "build_owner": "devops-team",
        "build_name": "frontend-service",
        "build_number": "456",
        "build_repository": "jfrog-artifactory"
      }
    }
  ]
}
```

#### Response

```json
{
  "continue": true
}
```

### Scheduled Worker Code Sample

The following section provides a sample code for a scheduled worker.

```
export default async (
 context: PlatformContext,
 data: ScheduledEventRequest
): Promise<ScheduledEventResponse> => {
 try {
   // The in-browser HTTP client facilitates making calls to the JFrog REST APIs
   //To call an external endpoint, use 'await context.clients.axios.get("https://foo.com")'
   const res = await context.clients.platformHttp.get(
     "/artifactory/api/v1/system/readiness"
   );


   // You should reach this part if the HTTP request status is successful (HTTP Status 399 or lower)
   if (res.status === 200) {
     console.log("Artifactory ping success");
   } else {
     console.warn(
       `Request is successful but returned status other than 200. Status code : ${res.status}`
     );
   }
 } catch (error) {
   // The platformHttp client throws PlatformHttpClientError if the HTTP request status is 400 or higher
   console.error(
     `Request failed with status code ${
       error.status || "<none>"
     } caused by : ${error.message}`
   );
 }


 return {
   message: "Overwritten by worker-service if an error occurs.",
 };
};
```

#### Input Parameters

###### Context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### Data

The trigger ID of the scheduled execution

```
{
   "triggerID": "triggerID"
}
```

###### Response

```
{
   message: 'custom message', // Message to print to the log. If an error occurs, it will be printed as a warning.
}
```

## HTTP-Triggered and Scheduled Workers Code Samples

### HTTP-Trigged Worker Code Sample

The following section provides a sample code for a Execute Worker for Generic Event worker.

This sample code calls an API and fetches its data into a response object. The worker could potentially be used to enable non-Platform Admin users to run an API which requires Platform Admin permissions.

```
export default async (context: PlatformContext, data: { repoKey: string }): Promise<{ error: string | undefined, repository: any }> => {
    const response = {
        error: undefined,
        repository: {},
    };

    try {
        // Ref: https://docs.jfrog.com/artifactory/reference/getrepositoryconfiguration
        const res = await context.clients.platformHttp.get(`/artifactory/api/repositories/${data.repoKey}`);
        if (res.status === 200) {
            response.repository = res.data;
            console.log("Repository fetch success");
        } else {
            response.error = `Request is successful but returned an unexpected status : ${ res.status }`;
            console.warn(response.error);
        }
    } catch(error) {
        response.error = `Request failed with status code ${ error.status || '<none>' }`;
        console.error(response.error);
    }

    return response;
}
```

#### Input Parameters

###### context

Provides baseUrl, token, and clients to communicate with the JFrog Platform (for more information, see [PlatformContext](https://docs.jfrog.com/administration/docs/typescript-code-for-workers#platformcontext)).

###### data

The request with upload details sent by Artifactory.

```
{
  "foo": "one"
}
```

###### Response

```
{
  "data": {
    "repository": {
      "key": "type",
      "packageType": "type",
      "description": "",
      "notes": "",
      "includesPattern": "**/*",
      "excludesPattern": "",
      "repoLayoutRef": "simple-default",
      "signedUrlTtl": 90,
      "enableComposerSupport": false,
      "enableNuGetSupport": false,
      "enableGemsSupport": false,
      "enableNpmSupport": false,
      "enableBowerSupport": false,
      "enableChefSupport": false,
      "enableCocoaPodsSupport": false,
      "enableConanSupport": false,
      "enableDebianSupport": true,
      "debianTrivialLayout": false,
      "ddebSupported": false,
      "enablePypiSupport": false,
      "enablePuppetSupport": false,
      "enableDockerSupport": false,
      "dockerApiVersion": "V2",
      "blockPushingSchema1": true,
      "forceNugetAuthentication": false,
      "forceP2Authentication": false,
      "forceConanAuthentication": false,
      "enableVagrantSupport": false,
      "enableGitLfsSupport": false,
      "enableDistRepoSupport": false,
      "dockerProjectId": "",
      "priorityResolution": false,
      "environments": [],
      "checksumPolicyType": "client-checksums",
      "handleReleases": true,
      "handleSnapshots": true,
      "maxUniqueSnapshots": 0,
      "maxUniqueTags": 0,
      "snapshotVersionBehavior": "unique",
      "suppressPomConsistencyChecks": false,
      "blackedOut": false,
      "propertySets": [
        "artifactory"
      ],
      "optionalIndexCompressionFormats": [
        "bz2"
      ],
      "archiveBrowsingEnabled": false,
      "calculateYumMetadata": false,
      "enableFileListsIndexing": false,
      "yumRootDepth": 0,
      "dockerTagRetention": 1,
      "enableComposerV1Indexing": false,
      "terraformType": "MODULE",
      "encryptStates": true,
      "cargoInternalIndex": false,
      "cargoAnonymousAccess": false,
      "xrayDataTtl": 90,
      "downloadRedirect": false,
      "cdnRedirect": false,
      "xrayIndex": true,
      "rclass": "local"
    }
  },
  "executionStatus": "STATUS_SUCCESS"
}
```

###### Example

```
curl --location '<JDP_BASE_URL>/worker/api/v1/execute/<WORKER_KEY>' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <BEARER>' \
--data '{
    "repoKey": "my-repository"
}'
```