diff --git a/src/content/docs/en/pages/devtools/azion-lib/usage/client.mdx b/src/content/docs/en/pages/devtools/azion-lib/usage/client.mdx
index d16b96440a..b8cb657f32 100644
--- a/src/content/docs/en/pages/devtools/azion-lib/usage/client.mdx
+++ b/src/content/docs/en/pages/devtools/azion-lib/usage/client.mdx
@@ -11,7 +11,7 @@ menu_namespace: libMenu
import LinkButton from 'azion-webkit/linkbutton'
-The Azion **Client** interface provides a unified interface to interact with all products and services. You can use the `client` to access and manage all products and functionalities across Storage, SQL, Purge, and more.
+The Azion **Client** interface provides a unified interface to interact with all products and services. You can use the `client` to access and manage all products and functionalities across Storage, SQL, Purge, KV, Domains, and more.
When instantiating a client, you can define configurations such as `token` and `debug` explicitly as parameters. You can then interact with Azion functionalities directly through the `client`, in a simplified and centralized way.
@@ -103,3 +103,50 @@ if (data) {
```
This flexibility allows you to either manage everything through the client for simplicity or call specific functions from each package with more control over environment configurations.
+
+---
+
+## Available modules
+
+The Azion Client provides access to the following modules:
+
+| Module | Description |
+|--------|-------------|
+| `storage` | Manage buckets and objects in Object Storage. |
+| `sql` | Create and query SQL databases. |
+| `purge` | Purge cache by URL, cache key, or wildcard. |
+| `domains` | Manage domains and their configurations. |
+| `kv` | Interact with KV Store using a Redis-like API. |
+
+### Using the KV module
+
+The `kv` module provides a Redis-like interface for key-value operations:
+
+```typescript
+import { createClient } from 'azion';
+
+const client = createClient({ token: 'your-api-token', debug: true });
+
+// Access the KV module
+const kvClient = await client.kv
+ .on('error', (err) => console.error('KV Error:', err))
+ .connect();
+
+// Store a value
+await kvClient.set('user:123', JSON.stringify({ name: 'John' }), {
+ expiration: { type: 'EX', value: 3600 }, // 1 hour TTL
+});
+
+// Retrieve a value
+const userData = await kvClient.get('user:123');
+console.log('User data:', userData);
+
+// Hash operations
+await kvClient.hSet('config', 'theme', 'dark');
+const config = await kvClient.hGetAll('config');
+
+// Disconnect when done
+await kvClient.disconnect();
+```
+
+For more details on KV operations, see the [KV library documentation](/en/documentation/products/azion-lib/kv/).
diff --git a/src/content/docs/en/pages/devtools/azion-lib/usage/config.mdx b/src/content/docs/en/pages/devtools/azion-lib/usage/config.mdx
index 935b1c90d0..2058719c24 100644
--- a/src/content/docs/en/pages/devtools/azion-lib/usage/config.mdx
+++ b/src/content/docs/en/pages/devtools/azion-lib/usage/config.mdx
@@ -11,86 +11,350 @@ menu_namespace: libMenu
import LinkButton from 'azion-webkit/linkbutton'
-The **Config** module provides a function to configure and validate options for **Applications**. It supports various configurations, including domain settings, origin settings, cache settings, rules, network lists, and purge operations.
+The **Config** module provides comprehensive configuration and validation for the Azion Platform. It supports applications, workloads, connectors, functions, storage, firewall rules, WAF settings, network lists, custom pages, and purge operations.
---
+## Usage
+
+You can configure your Azion application in two ways:
+
+**1. Using JSDoc for type information:**
+
+```javascript
+/** @type {import('azion').AzionConfig} */
+const config = {...}
+
+export default config;
+```
+
+**2. Using the `defineConfig` function:**
+
+```javascript
+import { defineConfig } from 'azion/config';
+
+const config = defineConfig({
+ build: {
+ entry: './src/index.js',
+ preset: 'javascript',
+ },
+ // ... other configurations
+});
+
+export default config;
+```
+
+---
+
## Functions
### `defineConfig`
-This function configures and validates the options for Azion Applications. It receives a configuration object that contains the settings for domains, cache, rules, and more.
+Configures and validates the options for Azion Applications.
-:::note
-The code examples in this page show a partial implementation of the configuration object. Check the [full list of properties](/en/documentation/devtools/cli/configs/azion-config-js/) for more details.
-:::
+**Parameters**:
-Example:
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `config` | `AzionConfig` | The configuration object for the Azion Application. |
-```js
-import { defineConfig } from 'azion';
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `AzionConfig` | The validated configuration object. |
+
+**Example**:
+
+```javascript
+import { defineConfig } from 'azion/config';
const config = defineConfig({
- origin: [
+ build: {
+ entry: './src/index.js',
+ preset: 'javascript',
+ bundler: 'esbuild',
+ },
+ applications: [
{
- name: 'My Origin',
- type: 'single_origin',
- addresses: [
+ name: 'my-app',
+ active: true,
+ cache: [
{
- address: 'origin.example.com',
- weight: 100,
+ name: 'my-cache',
+ browser: { maxAgeSeconds: 3600 },
+ edge: { maxAgeSeconds: 7200 },
},
],
- protocolPolicy: 'https',
+ },
+ ],
+ storage: [
+ {
+ name: 'my-storage',
+ workloadsAccess: 'read_write',
+ dir: './storage',
+ prefix: 'app-data',
},
],
});
+
+export default config;
```
### `processConfig`
-This function processes the configuration object and returns a manifest.
+Processes the configuration object and returns a manifest.
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `config` | `AzionConfig` | The configuration object. |
+
+**Returns**:
-Example:
+| Return Type | Description |
+|-------------|-------------|
+| `object` | The processed manifest. |
-```ts
+**Example**:
+
+```typescript
import { AzionConfig, processConfig } from 'azion';
const config: AzionConfig = {...};
const manifest = processConfig(config);
-
console.log(manifest);
```
### `convertJsonConfigToObject`
-This function converts a JSON configuration object into an `AzionConfig` object.
+Converts a JSON configuration string to an `AzionConfig` object.
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `config` | `string` | The JSON configuration string. |
+
+**Returns**:
-Example:
+| Return Type | Description |
+|-------------|-------------|
+| `AzionConfig` | The configuration object. |
+
+**Example**:
```javascript
import { convertJsonConfigToObject } from 'azion';
const manifestJson = {
- origin: [
+ workloads: [
{
- name: 'My Origin',
- origin_type: 'single_origin',
- addresses: [
- {
- address: 'origin.example.com',
- weight: 100,
- },
- ],
- origin_protocol_policy: 'https',
+ name: 'my-workload',
+ active: true,
+ domains: ['example.com'],
},
],
};
-const manifest = convertJsonConfigToObject(JSON.stringify(manifestJson));
-
-console.log(manifest);
+const config = convertJsonConfigToObject(JSON.stringify(manifestJson));
+console.log(config);
```
+
+---
+
+## Configuration sections
+
+The `AzionConfig` object supports the following sections:
+
+| Section | Description |
+|---------|-------------|
+| `build` | Build configuration (entry, preset, bundler). |
+| `applications` | List of applications with cache, rules, and function instances. |
+| `workloads` | Workload configurations for domain management. |
+| `connectors` | HTTP, storage, or live ingest connectors. |
+| `functions` | Functions configurations. |
+| `storage` | Storage bucket configurations. |
+| `firewall` | Firewall rules and configurations. |
+| `waf` | Web Application Firewall settings. |
+| `networkList` | Network lists (IP, ASN, countries). |
+| `customPages` | Custom error page configurations. |
+| `purge` | URLs or cache keys to purge. |
+| `kv` | Key-Value storage configurations. |
+
+---
+
+## Types
+
+### `AzionConfig`
+
+The main configuration object.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `build` | `AzionBuild` (optional) | Build configuration. |
+| `applications` | `AzionApplication[]` (optional) | List of applications. |
+| `workloads` | `AzionWorkload[]` (optional) | List of workloads. |
+| `connectors` | `AzionConnector[]` (optional) | List of connectors. |
+| `functions` | `AzionFunction[]` (optional) | List of functions. |
+| `storage` | `AzionStorage[]` (optional) | List of storage configurations. |
+| `firewall` | `AzionFirewall[]` (optional) | List of firewall configurations. |
+| `waf` | `AzionWaf[]` (optional) | List of WAF configurations. |
+| `networkList` | `AzionNetworkList[]` (optional) | List of network lists. |
+| `customPages` | `AzionCustomPages[]` (optional) | List of custom pages. |
+| `purge` | `AzionPurge[]` (optional) | List of purge operations. |
+| `kv` | `AzionKV[]` (optional) | List of KV configurations. |
+
+### `AzionBuild`
+
+Build configuration options.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `entry` | `string \| string[] \| Record` (optional) | Entry file(s). |
+| `preset` | `string \| AzionBuildPreset` (optional) | Build preset. |
+| `bundler` | `'esbuild' \| 'webpack'` (optional) | Bundler to use. Default: `'esbuild'`. |
+| `polyfills` | `boolean` (optional) | Include polyfills. |
+| `extend` | `(context: T) => T` (optional) | Extend bundler configuration. |
+| `memoryFS` | `object` (optional) | In-memory file system configuration. |
+
+### `AzionApplication`
+
+Application configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Application name (1-250 characters). |
+| `active` | `boolean` (optional) | Whether active. Default: `true`. |
+| `debug` | `boolean` (optional) | Enable debug mode. Default: `false`. |
+| `edgeCacheEnabled` | `boolean` (optional) | Enable edge cache. Default: `true`. |
+| `functionsEnabled` | `boolean` (optional) | Enable functions. Default: `false`. |
+| `applicationAcceleratorEnabled` | `boolean` (optional) | Enable accelerator. Default: `false`. |
+| `imageProcessorEnabled` | `boolean` (optional) | Enable image processor. Default: `false`. |
+| `cache` | `AzionCache[]` (optional) | Cache configurations. |
+| `rules` | `AzionRules` (optional) | Request/response rules. |
+| `functionsInstances` | `FunctionInstance[]` (optional) | Function instances. |
+
+### `AzionWorkload`
+
+Workload configuration for domain management.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Workload name (1-100 characters). |
+| `active` | `boolean` (optional) | Whether active. Default: `true`. |
+| `infrastructure` | `1 \| 2` (optional) | Infrastructure type. |
+| `domains` | `string[]` | List of domains. |
+| `workloadDomainAllowAccess` | `boolean` (optional) | Allow domain access. Default: `true`. |
+| `tls` | `TLSConfig` (optional) | TLS configuration. |
+| `protocols` | `ProtocolConfig` (optional) | Protocol configuration. |
+| `mtls` | `MTLSConfig` (optional) | Mutual TLS configuration. |
+| `deployments` | `Deployment[]` | List of deployments. |
+
+### `AzionConnector`
+
+Connector configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Connector name (1-255 characters). |
+| `active` | `boolean` (optional) | Whether active. Default: `true`. |
+| `type` | `'http' \| 'storage' \| 'live_ingest'` | Connector type. |
+| `attributes` | `ConnectorAttributes` | Connector-specific attributes. |
+
+### `AzionFunction`
+
+Function configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Function name (1-250 characters). |
+| `path` | `string` | Path to function file. |
+| `runtime` | `'azion_js'` (optional) | Runtime. Default: `'azion_js'`. |
+| `defaultArgs` | `object` (optional) | Default arguments. |
+| `executionEnvironment` | `'application' \| 'firewall'` (optional) | Execution environment. |
+| `active` | `boolean` (optional) | Whether active. Default: `true`. |
+| `bindings` | `FunctionBindings` (optional) | Function bindings. |
+
+### `AzionStorage`
+
+Storage configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Storage name (6-63 characters). |
+| `dir` | `string` | Local directory path. |
+| `workloadsAccess` | `'read_only' \| 'read_write' \| 'restricted'` (optional) | Access permissions. |
+| `prefix` | `string` | Storage prefix. |
+
+### `AzionCache`
+
+Cache configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Cache name (1-250 characters). |
+| `stale` | `boolean` (optional) | Allow stale content. |
+| `queryStringSort` | `boolean` (optional) | Sort query string parameters. |
+| `methods` | `{ post?: boolean; options?: boolean }` (optional) | HTTP methods to cache. |
+| `browser` | `{ maxAgeSeconds: number \| string }` (optional) | Browser cache settings. |
+| `edge` | `{ maxAgeSeconds: number \| string }` (optional) | Edge cache settings. |
+| `cacheByCookie` | `object` (optional) | Cache by cookie settings. |
+| `cacheByQueryString` | `object` (optional) | Cache by query string settings. |
+| `tieredCache` | `object` (optional) | Tiered cache settings. |
+
+### `AzionFirewall`
+
+Firewall configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Firewall name. |
+| `active` | `boolean` (optional) | Whether active. |
+| `functions` | `boolean` (optional) | Enable functions. |
+| `networkProtection` | `boolean` (optional) | Enable network protection. |
+| `waf` | `boolean` (optional) | Enable WAF. |
+| `rules` | `AzionFirewallRule[]` (optional) | Firewall rules. |
+
+### `AzionWaf`
+
+WAF configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | WAF name (1-250 characters). |
+| `productVersion` | `string` (optional) | Product version. Default: `'1.0'`. |
+| `engineSettings` | `WafEngineSettings` | WAF engine configuration. |
+
+### `AzionNetworkList`
+
+Network list configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | Network list name (1-250 characters). |
+| `type` | `'ip_cidr' \| 'asn' \| 'countries'` | List type. |
+| `items` | `string[]` | List items (1-20000). |
+| `active` | `boolean` (optional) | Whether active. Default: `true`. |
+
+### `AzionPurge`
+
+Purge configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `type` | `'url' \| 'cachekey' \| 'wildcard'` | Purge type. |
+| `items` | `string[]` | URLs or patterns to purge. |
+| `layer` | `'cache' \| 'tiered_cache'` (optional) | Cache layer. |
+
+### `AzionKV`
+
+KV storage configuration.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | `string` | KV storage name (1-255 characters). |
diff --git a/src/content/docs/en/pages/devtools/azion-lib/usage/kv.mdx b/src/content/docs/en/pages/devtools/azion-lib/usage/kv.mdx
new file mode 100644
index 0000000000..f2aa75996d
--- /dev/null
+++ b/src/content/docs/en/pages/devtools/azion-lib/usage/kv.mdx
@@ -0,0 +1,441 @@
+---
+title: Azion KV library
+description: >-
+ Learn how to use the KV library to interact with the KV Store using a Redis-like API.
+permalink: /documentation/products/azion-lib/kv/
+meta_tags: >-
+ Azion Lib, edge computing, applications, Azion products, KV Store, Redis
+namespace: documentation_azion_lib_kv
+menu_namespace: libMenu
+---
+
+import LinkButton from 'azion-webkit/linkbutton'
+
+The **KV** library provides a Redis-like interface to interact with Azion's **KV Store**. This library offers familiar Redis patterns including event-based error handling, connection management, and hash operations.
+
+
+
+You can interact with the API using a `client` with Redis-like chaining patterns. The client supports both native runtime and API-based providers with automatic detection.
+
+This is an example of how a `.env` file with your environment variables may look like:
+
+```sh
+AZION_TOKEN=
+AZION_DEBUG=true
+```
+
+| Variable | Description |
+|----------|-------------|
+| `AZION_TOKEN` | Your Azion API token. |
+| `AZION_DEBUG` | Enable debug mode (true/false). |
+
+---
+
+## Usage
+
+### Creating a client
+
+Create a KV client using the Redis-like chaining pattern:
+
+```typescript
+import { createClient } from 'azion/kv';
+import type { KVClient } from 'azion/kv';
+
+// Create a client with Redis-like chaining pattern
+const client: KVClient = await createClient()
+ .on('error', (err) => console.log('KV Client Error', err))
+ .connect();
+```
+
+You can also create a client with custom options:
+
+```typescript
+import { createClient } from 'azion/kv';
+
+const client = await createClient({
+ namespace: 'my-namespace',
+ apiToken: 'my-token',
+})
+ .on('error', (err) => console.error('KV Error:', err))
+ .connect();
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `options` | `KVClientOptions` (optional) | Configuration options for the client. |
+| `options.namespace` | `string` (optional) | The namespace to use for KV operations. |
+| `options.apiToken` | `string` (optional) | The API token for authentication. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `KVClient` | A client object with methods to interact with KV Store. |
+
+---
+
+### `get`
+
+Retrieves a value by key.
+
+```typescript
+const value = await client.get('my-key');
+console.log(value);
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The key to retrieve. |
+| `options` | `KVGetOptions` (optional) | Options for the get operation. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | The value or null if not found. |
+
+---
+
+### `getWithMetadata`
+
+Retrieves a value along with its metadata.
+
+```typescript
+const result = await client.getWithMetadata('my-key');
+console.log(result.value, result.metadata);
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The key to retrieve. |
+| `options` | `KVGetOptions` (optional) | Options for the get operation. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | An object containing the value and metadata. |
+
+---
+
+### `set`
+
+Stores a value with an optional expiration and metadata.
+
+```typescript
+// Simple set
+await client.set('my-key', 'my-value');
+
+// Set with options
+await client.set('my-key', 'my-value', {
+ expiration: {
+ type: 'EX',
+ value: 10, // 10 seconds
+ },
+ metadata: { userId: '123' },
+});
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The key to store. |
+| `value` | `KVValue` | The value to store. |
+| `options` | `KVSetOptions` (optional) | Options for the set operation. |
+
+The `KVSetOptions` object supports the following properties:
+
+| Option | Type | Description |
+|--------|------|-------------|
+| `expiration` | `object` (optional) | Expiration configuration. |
+| `expiration.type` | `'EX' \| 'PX' \| 'EXAT' \| 'PXAT'` | Expiration type. |
+| `expiration.value` | `number` | Expiration value. |
+| `metadata` | `object` (optional) | Metadata to associate with the key. |
+
+**Expiration types**:
+
+| Type | Description |
+|------|-------------|
+| `EX` | Expire in seconds from now. |
+| `PX` | Expire in milliseconds from now. |
+| `EXAT` | Expire at a specific Unix timestamp (seconds). |
+| `PXAT` | Expire at a specific Unix timestamp (milliseconds). |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | Resolves when the operation is complete. |
+
+---
+
+### `delete` / `del`
+
+Deletes a key from the store.
+
+```typescript
+await client.delete('my-key');
+// or
+await client.del('my-key');
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The key to delete. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | Resolves when the operation is complete. |
+
+---
+
+### Hash operations
+
+The KV library supports Redis-like hash operations for storing field-value pairs.
+
+#### `hSet` / `HSET`
+
+Sets a field in a hash.
+
+```typescript
+await client.hSet('my-key', 'field', 'value');
+await client.HSET('my-key', 'field', 'value');
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The hash key. |
+| `field` | `string` | The field name. |
+| `value` | `KVValue` | The value to store. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | Resolves when the operation is complete. |
+
+#### `hGetAll` / `HGETALL`
+
+Gets all fields and values from a hash.
+
+```typescript
+const result = await client.hGetAll('my-key');
+const result = await client.HGETALL('my-key');
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The hash key. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | The hash data or null if not found. |
+
+#### `hVals` / `HVALS`
+
+Gets all values from a hash.
+
+```typescript
+const result = await client.hVals('my-key');
+const result = await client.HVALS('my-key');
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `key` | `string` | The hash key. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | An array of values or null if not found. |
+
+---
+
+### Connection management
+
+#### `disconnect` / `quit`
+
+Disconnects from the KV store.
+
+```typescript
+await client.disconnect();
+// or
+await client.quit();
+```
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise` | Resolves when disconnected. |
+
+---
+
+### Provider detection
+
+#### `getProviderType`
+
+Returns the current provider type being used.
+
+```typescript
+const providerType = client.getProviderType();
+console.log(providerType); // 'native' or 'api'
+```
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `'native' \| 'api'` | The provider type. |
+
+The client automatically detects the environment:
+- **native**: Used when running in Azion Runtime (Functions).
+- **api**: Used when running outside of Azion Runtime (local development, external servers).
+
+---
+
+## Error handling
+
+The KV client uses an event-based error handling pattern similar to Redis:
+
+```typescript
+const client = await createClient()
+ .on('error', (err) => {
+ console.error('KV Client Error:', err);
+ // Handle error appropriately
+ })
+ .connect();
+```
+
+You can also use try-catch for individual operations:
+
+```typescript
+try {
+ const value = await client.get('my-key');
+} catch (error) {
+ console.error('Failed to get value:', error);
+}
+```
+
+---
+
+## Complete example
+
+```typescript
+import { createClient } from 'azion/kv';
+
+async function main() {
+ // Create and connect client
+ const client = await createClient({
+ namespace: 'my-namespace',
+ })
+ .on('error', (err) => console.error('KV Error:', err))
+ .connect();
+
+ // Store a value with expiration
+ await client.set('user:123', JSON.stringify({ name: 'John', role: 'admin' }), {
+ expiration: { type: 'EX', value: 3600 }, // 1 hour
+ metadata: { createdBy: 'system' },
+ });
+
+ // Retrieve the value
+ const userData = await client.get('user:123');
+ console.log('User data:', userData);
+
+ // Get with metadata
+ const result = await client.getWithMetadata('user:123');
+ console.log('Value:', result.value);
+ console.log('Metadata:', result.metadata);
+
+ // Hash operations
+ await client.hSet('config', 'theme', 'dark');
+ await client.hSet('config', 'language', 'en');
+ const config = await client.hGetAll('config');
+ console.log('Config:', config);
+
+ // Check provider type
+ console.log('Provider:', client.getProviderType());
+
+ // Delete and disconnect
+ await client.delete('user:123');
+ await client.disconnect();
+}
+
+main();
+```
+
+---
+
+## Types
+
+These are the types used by the **KV** library:
+
+### `KVClient`
+
+The main client interface for KV operations.
+
+| Method | Parameters | Return Type | Description |
+|--------|------------|-------------|-------------|
+| `on` | `event: 'error', handler: (error: Error) => void` | `this` | Register error event handler (chainable). |
+| `connect` | - | `Promise` | Connect to KV store (chainable). |
+| `get` | `key: string, options?: KVGetOptions` | `Promise` | Get a value. |
+| `getWithMetadata` | `key: string, options?: KVGetOptions` | `Promise` | Get value with metadata. |
+| `set` | `key: string, value: KVValue, options?: KVSetOptions` | `Promise` | Set a value. |
+| `delete` | `key: string` | `Promise` | Delete a key. |
+| `del` | `key: string` | `Promise` | Alias for delete. |
+| `disconnect` | - | `Promise` | Disconnect from store. |
+| `quit` | - | `Promise` | Alias for disconnect. |
+| `hSet` | `key: string, field: string, value: KVValue` | `Promise` | Set hash field. |
+| `HSET` | `key: string, field: string, value: KVValue` | `Promise` | Alias for hSet. |
+| `hGetAll` | `key: string` | `Promise` | Get all hash fields. |
+| `HGETALL` | `key: string` | `Promise` | Alias for hGetAll. |
+| `hVals` | `key: string` | `Promise` | Get all hash values. |
+| `HVALS` | `key: string` | `Promise` | Alias for hVals. |
+| `getProviderType` | - | `'native' \| 'api'` | Get current provider type. |
+
+### `KVClientOptions`
+
+Configuration options for the KV client.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `namespace` | `string` (optional) | The namespace for KV operations. |
+| `apiToken` | `string` (optional) | The API token for authentication. |
+
+### `KVSetOptions`
+
+Options for set operations.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `expiration` | `{ type: 'EX' \| 'PX' \| 'EXAT' \| 'PXAT', value: number }` (optional) | Expiration configuration. |
+| `metadata` | `object` (optional) | Metadata to associate with the key. |
+
+### `KVGetResult`
+
+Result from getWithMetadata operation.
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `value` | `KVGetValue \| null` | The retrieved value. |
+| `metadata` | `object \| null` | The associated metadata. |
diff --git a/src/content/docs/en/pages/devtools/azion-lib/usage/sql.mdx b/src/content/docs/en/pages/devtools/azion-lib/usage/sql.mdx
index 2c00b895bd..bea2d67759 100644
--- a/src/content/docs/en/pages/devtools/azion-lib/usage/sql.mdx
+++ b/src/content/docs/en/pages/devtools/azion-lib/usage/sql.mdx
@@ -274,6 +274,43 @@ if (result?.state === 'executed') {
}
```
+### `getTables`
+
+Retrieves a list of tables in a specific database.
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `name` | `string` | Name of the database to retrieve tables from. |
+| `options` | `AzionClientOptions` (optional) | Optional parameters for the retrieval. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise>` | Query result containing table information or error. |
+
+**Example**:
+
+```typescript
+import { getDatabase } from 'azion/sql';
+import type { AzionDatabaseResponse, AzionDatabase, AzionDatabaseQueryResponse } from 'azion/sql';
+
+// First get the database
+const { data: database, error }: AzionDatabaseResponse = await getDatabase('my-db', { debug: true });
+
+if (database) {
+ // Then get the tables using the database object method
+ const { data: tables, error: tablesError }: AzionDatabaseResponse = await database.getTables();
+ if (tables) {
+ console.log('Tables:', tables.data);
+ } else {
+ console.error('Failed to get tables', tablesError);
+ }
+}
+```
+
---
## Types
diff --git a/src/content/docs/en/pages/devtools/azion-lib/usage/storage.mdx b/src/content/docs/en/pages/devtools/azion-lib/usage/storage.mdx
index b980d7357b..af65fe7b77 100644
--- a/src/content/docs/en/pages/devtools/azion-lib/usage/storage.mdx
+++ b/src/content/docs/en/pages/devtools/azion-lib/usage/storage.mdx
@@ -13,6 +13,8 @@ import LinkButton from 'azion-webkit/linkbutton'
The **Object Storage** library provides methods to interact with the **Object Storage** API, allowing you to manage buckets and objects. This client is configurable and supports both debug mode and environment variable-based configuration.
+The library also includes a convenient `setupStorage` utility that ensures a bucket exists before performing operations.
+
You can interact with the API using a `client` or calling the methods directly from the library. When making direct calls, you can use the environment variables to configure the `client` without passing the token and debug parameters directly.
@@ -71,6 +73,49 @@ In the following examples, the methods are called directly without the creation
## Usage
+### `setupStorage`
+
+Ensures a bucket exists by first trying to get an existing bucket, and if it doesn't exist, creates it automatically. This is useful for initialization scripts or ensuring your storage is ready to use.
+
+Example:
+
+```typescript
+import { setupStorage } from 'azion/storage';
+import type { AzionStorageResponse, AzionBucket } from 'azion/storage';
+
+const { data: bucket, error }: AzionStorageResponse = await setupStorage({
+ name: 'my-app-bucket',
+ workloads_access: 'read_write',
+});
+if (bucket) {
+ console.log(`Storage ready: ${bucket.name}`);
+ // Now you can safely use the bucket for operations
+ await bucket.createObject({
+ key: 'config.json',
+ content: '{}',
+ params: { content_type: 'application/json' },
+ });
+} else {
+ console.error('Failed to setup storage', error);
+}
+```
+
+**Parameters**:
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `name` | `string` | The name of the bucket to get or create. |
+| `workloads_access` | `string` | The workloads access configuration for the bucket if it needs to be created. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
+| `options?` | `AzionClientOptions` | Optional parameters for the request. |
+
+**Returns**:
+
+| Return Type | Description |
+|-------------|-------------|
+| `Promise>` | The existing or newly created bucket object, or error. |
+
+---
+
### `createBucket`
Creates a new bucket.
@@ -82,7 +127,7 @@ import { createBucket } from 'azion/storage';
import type { AzionStorageResponse, AzionBucket } from 'azion/storage';
const { data, error }: AzionStorageResponse = await createBucket({
name: 'my-new-bucket',
- edge_access: 'public',
+ workloads_access: 'read_only',
});
if (data) {
console.log(`Bucket created with name: ${data.name}`);
@@ -96,7 +141,7 @@ if (data) {
| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the new bucket. |
-| `edge_access` | `string` | The `edge access` configuration for the bucket. |
+| `workloads_access` | `string` | The workloads access configuration for the bucket. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
| `options?` | `AzionClientOptions` | Optional parameters for the request. |
**Returns**:
@@ -210,7 +255,7 @@ import { updateBucket, AzionBucket, AzionStorageResponse } from 'azion/storage';
const { data: updatedBucket, error }: AzionStorageResponse | null = await updateBucket({
name: 'my-bucket',
- edge_access: 'private',
+ workloads_access: 'read_write',
});
if (updatedBucket) {
console.log(`Bucket updated: ${updatedBucket.name}`);
@@ -224,7 +269,7 @@ if (updatedBucket) {
| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the bucket to be updated. |
-| `edge_access` | `string` | The new `edge access` configuration for the bucket. |
+| `workloads_access` | `string` | The new workloads access configuration for the bucket. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
| `debug?` | `boolean` | Enables debug mode for detailed logging. |
**Returns**:
@@ -450,8 +495,11 @@ The bucket object.
| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | The name of the bucket. |
-| `edge_access` | `string` (optional) | The `edge access` of the bucket. |
+| `workloads_access` | `string` (optional) | The workloads access configuration of the bucket. |
| `state` | `'executed' \| 'pending'` (optional) | The state of the bucket. |
+| `last_editor` | `string` (optional) | The last editor of the bucket. |
+| `last_modified` | `string` (optional) | The last modified timestamp. |
+| `product_version` | `string` (optional) | The product version. |
| `getObjects` | `() => Promise>` (optional) | A method to get all objects in the bucket. |
| `getObjectByKey` | `(objectKey: string) => Promise>` (optional) | A method to get an object by its key. |
| `createObject` | `(objectKey: string, file: string) => Promise>` (optional) | A method to create a new object in the bucket. |
diff --git a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/client.mdx b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/client.mdx
index 7f90e8dc2c..497659f548 100644
--- a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/client.mdx
+++ b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/client.mdx
@@ -11,7 +11,7 @@ menu_namespace: libMenu
import LinkButton from 'azion-webkit/linkbutton'
-A interface **Client** da Azion fornece um meio unificado para interagir com todos os produtos e serviços. Você pode usar o `client` para acessar e gerenciar todos os produtos e funcionalidades no Object Storage, SQL Database, Purge, e mais.
+A interface **Client** da Azion fornece um meio unificado para interagir com todos os produtos e serviços. Você pode usar o `client` para acessar e gerenciar todos os produtos e funcionalidades no Object Storage, SQL Database, Purge, KV, Domains, e mais.
Ao instanciar um cliente, você pode definir explicitamente configurações como `token` e `debug` como parâmetros. Você pode então interagir com as funcionalidades da Azion diretamente através do `client`, de maneira simplificada e centralizada.
@@ -101,3 +101,50 @@ if (data) {
```
Essa flexibilidade permite que você gerencie tudo através do `client` para simplificar ou chame funções específicas de cada pacote com mais controle sobre as configurações do ambiente.
+
+---
+
+## Módulos disponíveis
+
+O Client da Azion fornece acesso aos seguintes módulos:
+
+| Módulo | Descrição |
+|--------|-----------|
+| `storage` | Gerenciar buckets e objetos no Object Storage. |
+| `sql` | Criar e consultar bancos de dados SQL. |
+| `purge` | Limpar cache por URL, cache key ou wildcard. |
+| `domains` | Gerenciar domínios e suas configurações. |
+| `kv` | Interagir com o KV Store usando uma API similar ao Redis. |
+
+### Usando o módulo KV
+
+O módulo `kv` fornece uma interface similar ao Redis para operações de chave-valor:
+
+```typescript
+import { createClient } from 'azion';
+
+const client = createClient({ token: 'seu-token-api', debug: true });
+
+// Acessar o módulo KV
+const kvClient = await client.kv
+ .on('error', (err) => console.error('Erro KV:', err))
+ .connect();
+
+// Armazenar um valor
+await kvClient.set('user:123', JSON.stringify({ name: 'John' }), {
+ expiration: { type: 'EX', value: 3600 }, // TTL de 1 hora
+});
+
+// Recuperar um valor
+const userData = await kvClient.get('user:123');
+console.log('Dados do usuário:', userData);
+
+// Operações de hash
+await kvClient.hSet('config', 'theme', 'dark');
+const config = await kvClient.hGetAll('config');
+
+// Desconectar quando terminar
+await kvClient.disconnect();
+```
+
+Para mais detalhes sobre operações KV, veja a [documentação da biblioteca KV](/pt-br/documentacao/produtos/azion-lib/kv/).
diff --git a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/config.mdx b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/config.mdx
index 984a31f9f9..3412c81db2 100644
--- a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/config.mdx
+++ b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/config.mdx
@@ -11,9 +11,40 @@ menu_namespace: libMenu
import LinkButton from 'azion-webkit/linkbutton'
-O módulo **Config** fornece funções para configurar e validar opções para **Applications**. Ele suporta várias configurações, incluindo domínio, origem, cache, regras, listas de rede e operações de purge.
+O módulo **Config** fornece configuração e validação abrangentes para a Plataforma Azion. Ele suporta applications, workloads, connectors, functions, storage, regras de firewall, configurações WAF, listas de rede, páginas personalizadas e operações de purge.
-
+
+
+---
+
+## Uso
+
+Você pode configurar sua aplicação Azion de duas formas:
+
+**1. Usando JSDoc para informações de tipo:**
+
+```javascript
+/** @type {import('azion').AzionConfig} */
+const config = {...}
+
+export default config;
+```
+
+**2. Usando a função `defineConfig`:**
+
+```javascript
+import { defineConfig } from 'azion/config';
+
+const config = defineConfig({
+ build: {
+ entry: './src/index.js',
+ preset: 'javascript',
+ },
+ // ... outras configurações
+});
+
+export default config;
+```
---
@@ -21,76 +52,309 @@ O módulo **Config** fornece funções para configurar e validar opções para *
### `defineConfig`
-Esta função configura e valida as opções para a application. Ela recebe um objeto de configuração que contém as defninições para domínios, cache, regras e muito mais.
+Configura e valida as opções para Applications Azion.
-:::note
-Os exemplos de código nesta página mostram uma implementação parcial do objeto de configuração. Verifique a [lista completa de propriedades](/pt-br/documentacao/devtools/cli/configs/azion-config-js/) para mais detalhes.
-:::
+**Parâmetros**:
-Exemplo:
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `config` | `AzionConfig` | O objeto de configuração para a Application Azion. |
-```js
-import { defineConfig } from 'azion';
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `AzionConfig` | O objeto de configuração validado. |
+
+**Exemplo**:
+
+```javascript
+import { defineConfig } from 'azion/config';
const config = defineConfig({
- origin: [
+ build: {
+ entry: './src/index.js',
+ preset: 'javascript',
+ bundler: 'esbuild',
+ },
+ applications: [
{
- name: 'My Origin',
- type: 'single_origin',
- addresses: [
+ name: 'my-app',
+ active: true,
+ cache: [
{
- address: 'origin.example.com',
- weight: 100,
+ name: 'my-cache',
+ browser: { maxAgeSeconds: 3600 },
+ edge: { maxAgeSeconds: 7200 },
},
],
- protocolPolicy: 'https',
+ },
+ ],
+ storage: [
+ {
+ name: 'my-storage',
+ workloadsAccess: 'read_write',
+ dir: './storage',
+ prefix: 'app-data',
},
],
});
+
+export default config;
```
### `processConfig`
-Esta função processa o objeto de configuração e retorna um manifesto.
+Processa o objeto de configuração e retorna um manifesto.
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `config` | `AzionConfig` | O objeto de configuração. |
+
+**Retorno**:
-Exemplo:
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `object` | O manifesto processado. |
-```ts
+**Exemplo**:
+
+```typescript
import { AzionConfig, processConfig } from 'azion';
const config: AzionConfig = {...};
const manifest = processConfig(config);
-
console.log(manifest);
```
### `convertJsonConfigToObject`
-Esta função converte um objeto de configuração JSON em um objeto `AzionConfig`.
+Converte uma string de configuração JSON para um objeto `AzionConfig`.
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `config` | `string` | A string de configuração JSON. |
+
+**Retorno**:
-Exemplo:
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `AzionConfig` | O objeto de configuração. |
+
+**Exemplo**:
```javascript
import { convertJsonConfigToObject } from 'azion';
const manifestJson = {
- origin: [
+ workloads: [
{
- name: 'My Origin',
- origin_type: 'single_origin',
- addresses: [
- {
- address: 'origin.example.com',
- weight: 100,
- },
- ],
- origin_protocol_policy: 'https',
+ name: 'my-workload',
+ active: true,
+ domains: ['example.com'],
},
],
};
-const manifest = convertJsonConfigToObject(JSON.stringify(manifestJson));
-
-console.log(manifest);
+const config = convertJsonConfigToObject(JSON.stringify(manifestJson));
+console.log(config);
```
+
+---
+
+## Seções de configuração
+
+O objeto `AzionConfig` suporta as seguintes seções:
+
+| Seção | Descrição |
+|-------|-----------|
+| `build` | Configuração de build (entry, preset, bundler). |
+| `applications` | Lista de applications com cache, regras e instâncias de function. |
+| `workloads` | Configurações de workload para gerenciamento de domínios. |
+| `connectors` | Connectors HTTP, storage ou live ingest. |
+| `functions` | Configurações de functions. |
+| `storage` | Configurações de buckets de storage. |
+| `firewall` | Regras e configurações de firewall. |
+| `waf` | Configurações de Web Application Firewall. |
+| `networkList` | Listas de rede (IP, ASN, países). |
+| `customPages` | Configurações de páginas de erro personalizadas. |
+| `purge` | URLs ou cache keys para purge. |
+| `kv` | Configurações de armazenamento Key-Value. |
+
+---
+
+## Tipos
+
+### `AzionConfig`
+
+O objeto de configuração principal.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `build` | `AzionBuild` (opcional) | Configuração de build. |
+| `applications` | `AzionApplication[]` (opcional) | Lista de applications. |
+| `workloads` | `AzionWorkload[]` (opcional) | Lista de workloads. |
+| `connectors` | `AzionConnector[]` (opcional) | Lista de connectors. |
+| `functions` | `AzionFunction[]` (opcional) | Lista de functions. |
+| `storage` | `AzionStorage[]` (opcional) | Lista de configurações de storage. |
+| `firewall` | `AzionFirewall[]` (opcional) | Lista de configurações de firewall. |
+| `waf` | `AzionWaf[]` (opcional) | Lista de configurações WAF. |
+| `networkList` | `AzionNetworkList[]` (opcional) | Lista de listas de rede. |
+| `customPages` | `AzionCustomPages[]` (opcional) | Lista de páginas personalizadas. |
+| `purge` | `AzionPurge[]` (opcional) | Lista de operações de purge. |
+| `kv` | `AzionKV[]` (opcional) | Lista de configurações KV. |
+
+### `AzionBuild`
+
+Opções de configuração de build.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `entry` | `string \| string[] \| Record` (opcional) | Arquivo(s) de entrada. |
+| `preset` | `string \| AzionBuildPreset` (opcional) | Preset de build. |
+| `bundler` | `'esbuild' \| 'webpack'` (opcional) | Bundler a usar. Padrão: `'esbuild'`. |
+| `polyfills` | `boolean` (opcional) | Incluir polyfills. |
+| `extend` | `(context: T) => T` (opcional) | Estender configuração do bundler. |
+| `memoryFS` | `object` (opcional) | Configuração de sistema de arquivos em memória. |
+
+### `AzionApplication`
+
+Configuração de application.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome da application (1-250 caracteres). |
+| `active` | `boolean` (opcional) | Se está ativa. Padrão: `true`. |
+| `debug` | `boolean` (opcional) | Habilitar modo debug. Padrão: `false`. |
+| `edgeCacheEnabled` | `boolean` (opcional) | Habilitar edge cache. Padrão: `true`. |
+| `functionsEnabled` | `boolean` (opcional) | Habilitar functions. Padrão: `false`. |
+| `applicationAcceleratorEnabled` | `boolean` (opcional) | Habilitar acelerador. Padrão: `false`. |
+| `imageProcessorEnabled` | `boolean` (opcional) | Habilitar processador de imagem. Padrão: `false`. |
+| `cache` | `AzionCache[]` (opcional) | Configurações de cache. |
+| `rules` | `AzionRules` (opcional) | Regras de request/response. |
+| `functionsInstances` | `FunctionInstance[]` (opcional) | Instâncias de function. |
+
+### `AzionWorkload`
+
+Configuração de workload para gerenciamento de domínios.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do workload (1-100 caracteres). |
+| `active` | `boolean` (opcional) | Se está ativo. Padrão: `true`. |
+| `infrastructure` | `1 \| 2` (opcional) | Tipo de infraestrutura. |
+| `domains` | `string[]` | Lista de domínios. |
+| `workloadDomainAllowAccess` | `boolean` (opcional) | Permitir acesso ao domínio. Padrão: `true`. |
+| `tls` | `TLSConfig` (opcional) | Configuração TLS. |
+| `protocols` | `ProtocolConfig` (opcional) | Configuração de protocolo. |
+| `mtls` | `MTLSConfig` (opcional) | Configuração de TLS mútuo. |
+| `deployments` | `Deployment[]` | Lista de deployments. |
+
+### `AzionConnector`
+
+Configuração de connector.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do connector (1-255 caracteres). |
+| `active` | `boolean` (opcional) | Se está ativo. Padrão: `true`. |
+| `type` | `'http' \| 'storage' \| 'live_ingest'` | Tipo de connector. |
+| `attributes` | `ConnectorAttributes` | Atributos específicos do connector. |
+
+### `AzionFunction`
+
+Configuração de function.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome da function (1-250 caracteres). |
+| `path` | `string` | Caminho para o arquivo da function. |
+| `runtime` | `'azion_js'` (opcional) | Runtime. Padrão: `'azion_js'`. |
+| `defaultArgs` | `object` (opcional) | Argumentos padrão. |
+| `executionEnvironment` | `'application' \| 'firewall'` (opcional) | Ambiente de execução. |
+| `active` | `boolean` (opcional) | Se está ativa. Padrão: `true`. |
+| `bindings` | `FunctionBindings` (opcional) | Bindings da function. |
+
+### `AzionStorage`
+
+Configuração de storage.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do storage (6-63 caracteres). |
+| `dir` | `string` | Caminho do diretório local. |
+| `workloadsAccess` | `'read_only' \| 'read_write' \| 'restricted'` (opcional) | Permissões de acesso. |
+| `prefix` | `string` | Prefixo do storage. |
+
+### `AzionCache`
+
+Configuração de cache.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do cache (1-250 caracteres). |
+| `stale` | `boolean` (opcional) | Permitir conteúdo stale. |
+| `queryStringSort` | `boolean` (opcional) | Ordenar parâmetros de query string. |
+| `methods` | `{ post?: boolean; options?: boolean }` (opcional) | Métodos HTTP para cache. |
+| `browser` | `{ maxAgeSeconds: number \| string }` (opcional) | Configurações de cache do browser. |
+| `edge` | `{ maxAgeSeconds: number \| string }` (opcional) | Configurações de cache edge. |
+| `cacheByCookie` | `object` (opcional) | Configurações de cache por cookie. |
+| `cacheByQueryString` | `object` (opcional) | Configurações de cache por query string. |
+| `tieredCache` | `object` (opcional) | Configurações de tiered cache. |
+
+### `AzionFirewall`
+
+Configuração de firewall.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do firewall. |
+| `active` | `boolean` (opcional) | Se está ativo. |
+| `functions` | `boolean` (opcional) | Habilitar functions. |
+| `networkProtection` | `boolean` (opcional) | Habilitar proteção de rede. |
+| `waf` | `boolean` (opcional) | Habilitar WAF. |
+| `rules` | `AzionFirewallRule[]` (opcional) | Regras de firewall. |
+
+### `AzionWaf`
+
+Configuração WAF.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do WAF (1-250 caracteres). |
+| `productVersion` | `string` (opcional) | Versão do produto. Padrão: `'1.0'`. |
+| `engineSettings` | `WafEngineSettings` | Configuração do engine WAF. |
+
+### `AzionNetworkList`
+
+Configuração de lista de rede.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome da lista de rede (1-250 caracteres). |
+| `type` | `'ip_cidr' \| 'asn' \| 'countries'` | Tipo da lista. |
+| `items` | `string[]` | Itens da lista (1-20000). |
+| `active` | `boolean` (opcional) | Se está ativa. Padrão: `true`. |
+
+### `AzionPurge`
+
+Configuração de purge.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `type` | `'url' \| 'cachekey' \| 'wildcard'` | Tipo de purge. |
+| `items` | `string[]` | URLs ou padrões para purge. |
+| `layer` | `'cache' \| 'tiered_cache'` (opcional) | Camada de cache. |
+
+### `AzionKV`
+
+Configuração de armazenamento KV.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `name` | `string` | Nome do armazenamento KV (1-255 caracteres). |
diff --git a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/kv.mdx b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/kv.mdx
new file mode 100644
index 0000000000..20f3be5438
--- /dev/null
+++ b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/kv.mdx
@@ -0,0 +1,441 @@
+---
+title: Biblioteca Azion KV
+description: >-
+ Aprenda a usar a biblioteca KV para interagir com o KV Store usando uma API similar ao Redis.
+permalink: /documentacao/produtos/azion-lib/kv/
+meta_tags: >-
+ Azion Lib, edge computing, aplicações, produtos Azion, KV Store, Redis
+namespace: documentation_azion_lib_kv
+menu_namespace: libMenu
+---
+
+import LinkButton from 'azion-webkit/linkbutton'
+
+A biblioteca **KV** fornece uma interface similar ao Redis para interagir com o **KV Store** da Azion. Esta biblioteca oferece padrões familiares do Redis, incluindo tratamento de erros baseado em eventos, gerenciamento de conexão e operações de hash.
+
+
+
+Você pode interagir com a API usando um `client` com padrões de encadeamento similares ao Redis. O cliente suporta tanto provedores nativos do runtime quanto baseados em API com detecção automática.
+
+Este é um exemplo de como um arquivo `.env` com suas variáveis de ambiente pode parecer:
+
+```sh
+AZION_TOKEN=
+AZION_DEBUG=true
+```
+
+| Variável | Descrição |
+|----------|-----------|
+| `AZION_TOKEN` | Seu token de API da Azion. |
+| `AZION_DEBUG` | Habilitar modo de depuração (true/false). |
+
+---
+
+## Uso
+
+### Criando um cliente
+
+Crie um cliente KV usando o padrão de encadeamento similar ao Redis:
+
+```typescript
+import { createClient } from 'azion/kv';
+import type { KVClient } from 'azion/kv';
+
+// Criar um cliente com padrão de encadeamento similar ao Redis
+const client: KVClient = await createClient()
+ .on('error', (err) => console.log('Erro do Cliente KV', err))
+ .connect();
+```
+
+Você também pode criar um cliente com opções personalizadas:
+
+```typescript
+import { createClient } from 'azion/kv';
+
+const client = await createClient({
+ namespace: 'meu-namespace',
+ apiToken: 'meu-token',
+})
+ .on('error', (err) => console.error('Erro KV:', err))
+ .connect();
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `options` | `KVClientOptions` (opcional) | Opções de configuração para o cliente. |
+| `options.namespace` | `string` (opcional) | O namespace a ser usado para operações KV. |
+| `options.apiToken` | `string` (opcional) | O token de API para autenticação. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `KVClient` | Um objeto cliente com métodos para interagir com o KV Store. |
+
+---
+
+### `get`
+
+Recupera um valor pela chave.
+
+```typescript
+const value = await client.get('minha-chave');
+console.log(value);
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave a ser recuperada. |
+| `options` | `KVGetOptions` (opcional) | Opções para a operação de get. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | O valor ou null se não encontrado. |
+
+---
+
+### `getWithMetadata`
+
+Recupera um valor junto com seus metadados.
+
+```typescript
+const result = await client.getWithMetadata('minha-chave');
+console.log(result.value, result.metadata);
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave a ser recuperada. |
+| `options` | `KVGetOptions` (opcional) | Opções para a operação de get. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Um objeto contendo o valor e os metadados. |
+
+---
+
+### `set`
+
+Armazena um valor com expiração e metadados opcionais.
+
+```typescript
+// Set simples
+await client.set('minha-chave', 'meu-valor');
+
+// Set com opções
+await client.set('minha-chave', 'meu-valor', {
+ expiration: {
+ type: 'EX',
+ value: 10, // 10 segundos
+ },
+ metadata: { userId: '123' },
+});
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave a ser armazenada. |
+| `value` | `KVValue` | O valor a ser armazenado. |
+| `options` | `KVSetOptions` (opcional) | Opções para a operação de set. |
+
+O objeto `KVSetOptions` suporta as seguintes propriedades:
+
+| Opção | Tipo | Descrição |
+|-------|------|-----------|
+| `expiration` | `object` (opcional) | Configuração de expiração. |
+| `expiration.type` | `'EX' \| 'PX' \| 'EXAT' \| 'PXAT'` | Tipo de expiração. |
+| `expiration.value` | `number` | Valor de expiração. |
+| `metadata` | `object` (opcional) | Metadados a serem associados à chave. |
+
+**Tipos de expiração**:
+
+| Tipo | Descrição |
+|------|-----------|
+| `EX` | Expira em segundos a partir de agora. |
+| `PX` | Expira em milissegundos a partir de agora. |
+| `EXAT` | Expira em um timestamp Unix específico (segundos). |
+| `PXAT` | Expira em um timestamp Unix específico (milissegundos). |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Resolve quando a operação é concluída. |
+
+---
+
+### `delete` / `del`
+
+Exclui uma chave do armazenamento.
+
+```typescript
+await client.delete('minha-chave');
+// ou
+await client.del('minha-chave');
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave a ser excluída. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Resolve quando a operação é concluída. |
+
+---
+
+### Operações de hash
+
+A biblioteca KV suporta operações de hash similares ao Redis para armazenar pares campo-valor.
+
+#### `hSet` / `HSET`
+
+Define um campo em um hash.
+
+```typescript
+await client.hSet('minha-chave', 'campo', 'valor');
+await client.HSET('minha-chave', 'campo', 'valor');
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave do hash. |
+| `field` | `string` | O nome do campo. |
+| `value` | `KVValue` | O valor a ser armazenado. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Resolve quando a operação é concluída. |
+
+#### `hGetAll` / `HGETALL`
+
+Obtém todos os campos e valores de um hash.
+
+```typescript
+const result = await client.hGetAll('minha-chave');
+const result = await client.HGETALL('minha-chave');
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave do hash. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Os dados do hash ou null se não encontrado. |
+
+#### `hVals` / `HVALS`
+
+Obtém todos os valores de um hash.
+
+```typescript
+const result = await client.hVals('minha-chave');
+const result = await client.HVALS('minha-chave');
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-----------|
+| `key` | `string` | A chave do hash. |
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Um array de valores ou null se não encontrado. |
+
+---
+
+### Gerenciamento de conexão
+
+#### `disconnect` / `quit`
+
+Desconecta do KV store.
+
+```typescript
+await client.disconnect();
+// ou
+await client.quit();
+```
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `Promise` | Resolve quando desconectado. |
+
+---
+
+### Detecção de provedor
+
+#### `getProviderType`
+
+Retorna o tipo de provedor atual sendo usado.
+
+```typescript
+const providerType = client.getProviderType();
+console.log(providerType); // 'native' ou 'api'
+```
+
+**Retorno**:
+
+| Tipo de Retorno | Descrição |
+|-----------------|-----------|
+| `'native' \| 'api'` | O tipo de provedor. |
+
+O cliente detecta automaticamente o ambiente:
+- **native**: Usado quando executando no Azion Runtime (Functions).
+- **api**: Usado quando executando fora do Azion Runtime (desenvolvimento local, servidores externos).
+
+---
+
+## Tratamento de erros
+
+O cliente KV usa um padrão de tratamento de erros baseado em eventos similar ao Redis:
+
+```typescript
+const client = await createClient()
+ .on('error', (err) => {
+ console.error('Erro do Cliente KV:', err);
+ // Trate o erro apropriadamente
+ })
+ .connect();
+```
+
+Você também pode usar try-catch para operações individuais:
+
+```typescript
+try {
+ const value = await client.get('minha-chave');
+} catch (error) {
+ console.error('Falha ao obter valor:', error);
+}
+```
+
+---
+
+## Exemplo completo
+
+```typescript
+import { createClient } from 'azion/kv';
+
+async function main() {
+ // Criar e conectar cliente
+ const client = await createClient({
+ namespace: 'meu-namespace',
+ })
+ .on('error', (err) => console.error('Erro KV:', err))
+ .connect();
+
+ // Armazenar um valor com expiração
+ await client.set('user:123', JSON.stringify({ name: 'John', role: 'admin' }), {
+ expiration: { type: 'EX', value: 3600 }, // 1 hora
+ metadata: { createdBy: 'system' },
+ });
+
+ // Recuperar o valor
+ const userData = await client.get('user:123');
+ console.log('Dados do usuário:', userData);
+
+ // Obter com metadados
+ const result = await client.getWithMetadata('user:123');
+ console.log('Valor:', result.value);
+ console.log('Metadados:', result.metadata);
+
+ // Operações de hash
+ await client.hSet('config', 'theme', 'dark');
+ await client.hSet('config', 'language', 'pt');
+ const config = await client.hGetAll('config');
+ console.log('Configuração:', config);
+
+ // Verificar tipo de provedor
+ console.log('Provedor:', client.getProviderType());
+
+ // Excluir e desconectar
+ await client.delete('user:123');
+ await client.disconnect();
+}
+
+main();
+```
+
+---
+
+## Tipos
+
+Estes são os tipos usados pela biblioteca **KV**:
+
+### `KVClient`
+
+A interface principal do cliente para operações KV.
+
+| Método | Parâmetros | Tipo de Retorno | Descrição |
+|--------|------------|-----------------|-----------|
+| `on` | `event: 'error', handler: (error: Error) => void` | `this` | Registra manipulador de evento de erro (encadeável). |
+| `connect` | - | `Promise` | Conecta ao KV store (encadeável). |
+| `get` | `key: string, options?: KVGetOptions` | `Promise` | Obtém um valor. |
+| `getWithMetadata` | `key: string, options?: KVGetOptions` | `Promise` | Obtém valor com metadados. |
+| `set` | `key: string, value: KVValue, options?: KVSetOptions` | `Promise` | Define um valor. |
+| `delete` | `key: string` | `Promise` | Exclui uma chave. |
+| `del` | `key: string` | `Promise` | Alias para delete. |
+| `disconnect` | - | `Promise` | Desconecta do store. |
+| `quit` | - | `Promise` | Alias para disconnect. |
+| `hSet` | `key: string, field: string, value: KVValue` | `Promise` | Define campo de hash. |
+| `HSET` | `key: string, field: string, value: KVValue` | `Promise` | Alias para hSet. |
+| `hGetAll` | `key: string` | `Promise` | Obtém todos os campos do hash. |
+| `HGETALL` | `key: string` | `Promise` | Alias para hGetAll. |
+| `hVals` | `key: string` | `Promise` | Obtém todos os valores do hash. |
+| `HVALS` | `key: string` | `Promise` | Alias para hVals. |
+| `getProviderType` | - | `'native' \| 'api'` | Obtém o tipo de provedor atual. |
+
+### `KVClientOptions`
+
+Opções de configuração para o cliente KV.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `namespace` | `string` (opcional) | O namespace para operações KV. |
+| `apiToken` | `string` (opcional) | O token de API para autenticação. |
+
+### `KVSetOptions`
+
+Opções para operações de set.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `expiration` | `{ type: 'EX' \| 'PX' \| 'EXAT' \| 'PXAT', value: number }` (opcional) | Configuração de expiração. |
+| `metadata` | `object` (opcional) | Metadados a serem associados à chave. |
+
+### `KVGetResult`
+
+Resultado da operação getWithMetadata.
+
+| Propriedade | Tipo | Descrição |
+|-------------|------|-----------|
+| `value` | `KVGetValue \| null` | O valor recuperado. |
+| `metadata` | `object \| null` | Os metadados associados. |
diff --git a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/sql.mdx b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/sql.mdx
index e42571b15f..bec293a7d9 100644
--- a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/sql.mdx
+++ b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/sql.mdx
@@ -274,6 +274,43 @@ if (result?.state === 'executed') {
}
```
+### `getTables`
+
+Recupera uma lista de tabelas em um banco de dados específico.
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-------------|
+| `name` | `string` | Nome do banco de dados do qual recuperar as tabelas. |
+| `options` | `AzionClientOptions` (opcional) | Parâmetros opcionais para a recuperação. |
+
+**Retorno**:
+
+| Tipo de retorno | Descrição |
+|-------------|-------------|
+| `Promise>` | Resultado da consulta contendo informações das tabelas ou erro. |
+
+**Exemplo**:
+
+```typescript
+import { getDatabase } from 'azion/sql';
+import type { AzionDatabaseResponse, AzionDatabase, AzionDatabaseQueryResponse } from 'azion/sql';
+
+// Primeiro obtenha o banco de dados
+const { data: database, error }: AzionDatabaseResponse = await getDatabase('my-db', { debug: true });
+
+if (database) {
+ // Então obtenha as tabelas usando o método do objeto database
+ const { data: tables, error: tablesError }: AzionDatabaseResponse = await database.getTables();
+ if (tables) {
+ console.log('Tabelas:', tables.data);
+ } else {
+ console.error('Falha ao obter tabelas', tablesError);
+ }
+}
+```
+
---
## Tipos
diff --git a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/storage.mdx b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/storage.mdx
index 811fa3e5e1..02f12ab049 100644
--- a/src/content/docs/pt-br/pages/devtools/azion-lib/usage/storage.mdx
+++ b/src/content/docs/pt-br/pages/devtools/azion-lib/usage/storage.mdx
@@ -13,6 +13,8 @@ import LinkButton from 'azion-webkit/linkbutton'
A biblioteca **Object Storage** fornece métodos para interagir com a API do **Object Storage**, permitindo que você gerencie buckets e objetos. Este cliente é configurável e suporta tanto o modo de debug quanto a configuração baseada em variáveis de ambiente.
+A biblioteca também inclui um utilitário conveniente `setupStorage` que garante que um bucket exista antes de realizar operações.
+
Você pode interagir com a API usando um `client` ou chamando os métodos diretamente da biblioteca. Quando fizer chamadas diretas, você pode usar as variáveis de ambiente para configurar o `client` sem passar os parâmetros de token e debug diretamente.
@@ -70,6 +72,49 @@ Nos exemplos a seguir, os métodos são chamados diretamente sem a criação de
## Uso
+### `setupStorage`
+
+Garante que um bucket exista, primeiro tentando obter um bucket existente e, se não existir, criando-o automaticamente. Isso é útil para scripts de inicialização ou para garantir que seu armazenamento esteja pronto para uso.
+
+Exemplo:
+
+```typescript
+import { setupStorage } from 'azion/storage';
+import type { AzionStorageResponse, AzionBucket } from 'azion/storage';
+
+const { data: bucket, error }: AzionStorageResponse = await setupStorage({
+ name: 'meu-bucket-app',
+ workloads_access: 'read_write',
+});
+if (bucket) {
+ console.log(`Storage pronto: ${bucket.name}`);
+ // Agora você pode usar o bucket com segurança para operações
+ await bucket.createObject({
+ key: 'config.json',
+ content: '{}',
+ params: { content_type: 'application/json' },
+ });
+} else {
+ console.error('Falha ao configurar storage', error);
+}
+```
+
+**Parâmetros**:
+
+| Parâmetro | Tipo | Descrição |
+|-----------|------|-------------|
+| `name` | `string` | O nome do bucket a ser obtido ou criado. |
+| `workloads_access` | `string` | A configuração de acesso de workloads para o bucket se precisar ser criado. Valores possíveis: `'read_only'`, `'read_write'`, `'restricted'`. |
+| `options?` | `AzionClientOptions` | Parâmetros opcionais para a requisição. |
+
+**Retorno**:
+
+| Tipo de retorno | Descrição |
+|-------------|-------------|
+| `Promise>` | O bucket existente ou recém-criado, ou erro. |
+
+---
+
### `createBucket`
Cria um novo bucket.
@@ -81,7 +126,7 @@ import { createBucket } from 'azion/storage';
import type { AzionStorageResponse, AzionBucket } from 'azion/storage';
const { data, error }: AzionStorageResponse = await createBucket({
name: 'my-new-bucket',
- edge_access: 'public',
+ workloads_access: 'read_only',
});
if (data) {
console.log(`Bucket created with name: ${data.name}`);
@@ -94,7 +139,7 @@ if (data) {
| Parâmetro | Tipo | Descrição |
|-----------|------|-------------|
| `name` | `string` | O nome do novo bucket. |
-| `edge_access` | `string` | A configuração de `edge access` do bucket. |
+| `workloads_access` | `string` | A configuração de acesso de workloads do bucket. Valores possíveis: `'read_only'`, `'read_write'`, `'restricted'`. |
| `options?` | `AzionClientOptions` | Parâmetros opcionais para a requisição. |
**Retorno**:
@@ -208,7 +253,7 @@ import { updateBucket, AzionBucket, AzionStorageResponse } from 'azion/storage';
const { data: updatedBucket, error }: AzionStorageResponse | null = await updateBucket({
name: 'my-bucket',
- edge_access: 'private',
+ workloads_access: 'read_write',
});
if (updatedBucket) {
console.log(`Bucket updated: ${updatedBucket.name}`);
@@ -222,7 +267,7 @@ if (updatedBucket) {
| Parâmetro | Tipo | Descrição |
|-----------|------|-------------|
| `name` | `string` | O nome do bucket a ser atualizado. |
-| `edge_access` | `string` | A nova configuração de `edge access` para o bucket. |
+| `workloads_access` | `string` | A nova configuração de acesso de workloads para o bucket. Valores possíveis: `'read_only'`, `'read_write'`, `'restricted'`. |
| `debug?` | `boolean` | Ativa o modo de debug para logs detalhados. |
**Retorno**:
@@ -425,8 +470,8 @@ Um objeto com métodos para interagir com o Storage.
| Método | Parâmetros | Tipo de retorno |
|--------|------------|-----------------|
| `getBuckets` | `options?: BucketCollectionOptions` | `Promise>` |
-| `createBucket` | `name: string, edge_access: string` | `Promise>` |
-| `updateBucket` | `name: string, edge_access: string` | `Promise>` |
+| `createBucket` | `name: string, workloads_access: string` | `Promise>` |
+| `updateBucket` | `name: string, workloads_access: string` | `Promise>` |
| `deleteBucket` | `name: string` | `Promise>` |
| `getBucket` | `name: string` | `Promise>` |
@@ -446,8 +491,11 @@ O objeto bucket.
| Propriedade | Tipo | Descrição |
|-------------|------|-------------|
| `name` | `string` | O nome do bucket. |
-| `edge_access` | `string` (opcional) | A configuração `edge access` do bucket. |
+| `workloads_access` | `string` (opcional) | A configuração de acesso de workloads do bucket. |
| `state` | `'executed' \| 'pending'` (opcional) | O estado do bucket. |
+| `last_editor` | `string` (opcional) | O último editor do bucket. |
+| `last_modified` | `string` (opcional) | O timestamp da última modificação. |
+| `product_version` | `string` (opcional) | A versão do produto. |
| `getObjects` | `() => Promise>` (opcional) | Um método para obter todos os objetos no bucket. |
| `getObjectByKey` | `(objectKey: string) => Promise>` (opcional) | Um método para obter um objeto pela sua chave. |
| `createObject` | `(objectKey: string, file: string) => Promise>` (opcional) | Um método para criar um novo objeto no bucket. |