@harperfast/skills 1.4.2 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ export const ruleNames = [
|
|
|
13
13
|
"deploying-to-harper-fabric",
|
|
14
14
|
"extending-tables",
|
|
15
15
|
"handling-binary-data",
|
|
16
|
+
"logging",
|
|
16
17
|
"programmatic-table-requests",
|
|
17
18
|
"querying-rest-apis",
|
|
18
19
|
"real-time-apps",
|
|
@@ -38,6 +39,7 @@ export const rules = {
|
|
|
38
39
|
"deploying-to-harper-fabric": "---\nname: deploying-to-harper-fabric\ndescription: How to deploy a Harper application to the Harper Fabric cloud.\n---\n\n# Deploying to Harper Fabric\n\nInstructions for the agent to follow when deploying to Harper Fabric.\n\n## When to Use\n\nUse this skill when you are ready to move your Harper application from local development to a cloud-hosted environment.\n\n## How It Works\n\n1. **Sign up**: Follow the [creating-a-fabric-account-and-cluster](creating-a-fabric-account-and-cluster.md) rule to create a Harper Fabric account, organization, and cluster.\n2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:\n ```bash\n CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'\n CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'\n CLI_TARGET='YOUR_CLUSTER_URL'\n ```\n3. **Deploy From Local Environment**: Run `npm run deploy`.\n4. **Set up CI/CD**: Configure `.github/workflows/deploy.yaml` and set repository secrets for automated deployments.\n\n## Manual Setup for Existing Apps\n\nIf your application was not created with `npm create harper`, you'll need to manually configure the deployment scripts and CI/CD workflow.\n\n### 1. Update `package.json`\n\nAdd the following scripts and dependencies to your `package.json`:\n\n```json\n{\n\t\"scripts\": {\n\t\t\"deploy\": \"dotenv -- npm run deploy:component\",\n\t\t\"deploy:component\": \"harperdb deploy_component . restart=rolling replicated=true\"\n\t},\n\t\"devDependencies\": {\n\t\t\"dotenv-cli\": \"^11.0.0\",\n\t\t\"harperdb\": \"^4.7.20\"\n\t}\n}\n```\n\n#### Why split the scripts?\n\nThe `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.\n\n- `deploy`: Uses `dotenv-cli` to load environment variables (like `CLI_TARGET`, `CLI_TARGET_USERNAME`, and `CLI_TARGET_PASSWORD`) before executing the next command.\n- `deploy:component`: The actual command that performs the deployment.\n\nBy using `dotenv -- npm run deploy:component`, the environment variables are correctly set in the shell session before `harperdb deploy_component` is called, allowing it to authenticate with your cluster.\n\n### 2. Configure GitHub Actions\n\nCreate a `.github/workflows/deploy.yaml` file with the following content:\n\n```yaml\nname: Deploy to Harper Fabric\non:\n workflow_dispatch:\n# push:\n# branches:\n# - main\nconcurrency:\n group: main\n cancel-in-progress: false\njobs:\n deploy:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout code\n uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1\n with:\n fetch-depth: 0\n fetch-tags: true\n - name: Set up Node.js\n uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0\n with:\n cache: 'npm'\n node-version-file: '.nvmrc'\n - name: Install dependencies\n run: npm ci\n - name: Run unit tests\n run: npm test\n - name: Run lint\n run: npm run lint\n - name: Deploy\n run: npm run deploy\n env:\n CLI_TARGET: ${{ secrets.CLI_TARGET }}\n CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}\n CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}\n```\n\nBe sure to set the following repository secrets in your GitHub repository's /settings/secrets/actions:\n\n- `CLI_TARGET`\n- `CLI_TARGET_USERNAME`\n- `CLI_TARGET_PASSWORD`\n",
|
|
39
40
|
"extending-tables": "---\nname: extending-tables\ndescription: How to add custom logic to automatically generated table resources in Harper.\n---\n\n# Extending Tables\n\nInstructions for the agent to follow when extending table resources in Harper.\n\n## When to Use\n\nUse this skill when you need to add custom validation, side effects (like webhooks), data transformation, or custom access control to the standard CRUD operations of a Harper table.\n\n## How It Works\n\n1. **Define the Table in GraphQL**: In your `.graphql` schema, define the table using the `@table` directive. **Do not** use `@export` if you plan to extend it.\n ```graphql\n type MyTable @table {\n \tid: ID @primaryKey\n \tname: String\n }\n ```\n2. **Create the Extension File**: Create a `.ts` file in your `resources/` directory.\n3. **Extend the Table Resource**: Export a class that extends `tables.YourTableName`:\n\n ```typescript\n import { type RequestTargetOrId, tables } from 'harperdb';\n\n export class MyTable extends tables.MyTable {\n \tasync post(target: RequestTargetOrId, record: any) {\n \t\t// Custom logic here\n \t\tif (!record.name) {\n \t\t\tthrow new Error('Name required');\n \t\t}\n \t\treturn super.post(target, record);\n \t}\n }\n ```\n\n4. **Override Methods**: Override `get`, `post`, `put`, `patch`, or `delete` as needed. Always call `super[method]` to maintain default Harper functionality unless you intend to replace it entirely.\n5. **Implement Logic**: Use overrides for validation, side effects, or transforming data before/after database operations.\n",
|
|
40
41
|
"handling-binary-data": "---\nname: handling-binary-data\ndescription: How to store and serve binary data like images or audio in Harper.\n---\n\n# Handling Binary Data\n\nInstructions for the agent to follow when handling binary data in Harper.\n\n## When to Use\n\nUse this skill when you need to store binary files (images, audio, etc.) in the database or serve them back to clients via REST endpoints.\n\n## How It Works\n\n1. **Store Binary Data**: In your resource's `post` or `put` method, convert incoming data to Buffers and then to Blobs using `createBlob` from Harper's globals. Include the MIME type if available:\n\n ```typescript\n async post(target, record) {\n if (record.data) {\n record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {\n type: record.contentType || 'application/octet-stream',\n });\n }\n return super.post(target, record);\n }\n ```\n\n2. **Serve Binary Data**: In your resource's `get` method, return a response object with the appropriate `Content-Type` and the binary data in the `body`:\n ```typescript\n async get(target) {\n const record = await super.get(target);\n if (record?.data) {\n return {\n status: 200,\n headers: { 'Content-Type': record.data.type || 'application/octet-stream' },\n body: record.data,\n };\n }\n return record;\n }\n ```\n3. **Use the Blob Type**: Ensure your GraphQL schema uses the `Blob` scalar for binary fields.\n",
|
|
42
|
+
"logging": "---\nname: logging\ndescription: Best practices for logging in Harper, including console capture, the granular logger interface, and programmatic log retrieval.\n---\n\n# Logging Best Practices\n\nHarper provides a robust logging system that captures standard output and offers a granular, tagged logging interface for both local and deployed environments.\n\n## Standard Console Logging\n\nThe simplest way to log in Harper is using standard JavaScript console methods. `console.log()`, `console.warn()`, `console.error()`, and `console.trace()` are automatically captured by Harper and can be viewed in the logs.\n\n- `console.log(...)`: Captured as `stdout` level in Harper logs.\n- `console.warn(...)`: Captured as `stderr` level in Harper logs.\n- `console.error(...)`: Captured as `stderr` level in Harper logs.\n- `console.trace(...)`: Captured as `stdout` level in Harper logs (includes stack trace).\n\n## Harper Logger\n\nFor more granularity and better organization, use Harper's built-in `logger`. You can use the global `logger` object or import it from the `harper` package.\n\n### Log Levels\n\nThe Harper `logger` supports the following levels (ordered by increasing severity):\n\n- `trace`\n- `debug`\n- `info`\n- `warn`\n- `error`\n- `fatal`\n- `notify`\n\n### Usage\n\n```typescript\nimport { logger, loggerWithTag } from 'harper';\n\n// Basic logging\nlogger.info('Application started');\nlogger.error('An error occurred', error);\n\n// Tagged logging for better filtering (Namespacing)\nconst authLogger = loggerWithTag('auth');\nauthLogger.debug('User login attempt', { userId: '123' });\n```\n\nUsing `loggerWithTag` is highly recommended for grouping related logs, making them much easier to filter and analyze in the Harper Studio or via the API.\n\n## Programmatic Log Retrieval\n\nYou can programmatically read logs from a deployed Harper instance using the `read_log` operation. This is useful for building custom monitoring tools or debugging dashboards.\n\n### `read_log` Operation\n\nThe `read_log` operation is a POST request to the Harper instance.\n\n**Example Request:**\n\n```json\n{\n\t\"operation\": \"read_log\",\n\t\"limit\": 100,\n\t\"start\": 0,\n\t\"level\": \"error\",\n\t\"order\": \"desc\",\n\t\"from\": \"2024-01-01T00:00:00.000Z\",\n\t\"until\": \"2024-01-02T00:00:00.000Z\"\n}\n```\n\n### Parameters\n\n- `limit`: Number of log entries to return.\n- `start`: Offset for pagination.\n- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).\n- `from`: ISO 8601 timestamp to start reading from.\n- `until`: ISO 8601 timestamp to stop reading at.\n- `order`: Sort order, either `asc` or `desc`.\n- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.\n\n### Log Entry Structure\n\nEach log entry returned by `read_log` typically includes:\n\n- `level`: The severity level of the log.\n- `timestamp`: When the log was recorded.\n- `thread`: The execution thread.\n- `tags`: An array of tags (e.g., from `loggerWithTag`).\n- `node`: The node name in a Harper cluster.\n- `message`: The logged content.\n",
|
|
41
43
|
"programmatic-table-requests": "---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to follow when interacting with Harper tables via code.\n\n## When to Use\n\nUse this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.\n\n## How It Works\n\n1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).\n2. **Perform CRUD Operations**:\n - **Get**: `await tables.MyTable.get(id)` for a single record or `await tables.MyTable.get({ conditions: [...] })` for multiple.\n - **Create**: `await tables.MyTable.post(record)` (auto-generates ID) or `await tables.MyTable.put(id, record)`.\n - **Update**: `await tables.MyTable.patch(id, partialRecord)` for partial updates.\n - **Delete**: `await tables.MyTable.delete(id)`.\n3. **Use Updatable Records for Atomic Ops**: Call `update(id)` to get a reference, then use `addTo` or `subtractFrom` for atomic increments/decrements:\n ```typescript\n const stats = await tables.Stats.update('daily');\n stats.addTo('viewCount', 1);\n ```\n4. **Search and Stream**: Use `search(query)` for efficient streaming of large result sets:\n ```typescript\n for await (const record of tables.MyTable.search({ conditions: [...] })) {\n // process record\n }\n ```\n5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:\n ```typescript\n for await (const event of tables.MyTable.subscribe(query)) {\n \t// handle event\n }\n ```\n6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.\n\n## Cautions\n\nBe very careful when performing updates and deletions! You may be dealing with live production data. The wrong request to delete, without approval from a human, could be devastating to a business. Always use the proper approval process.\n",
|
|
42
44
|
"querying-rest-apis": "---\nname: querying-rest-apis\ndescription: How to use query parameters to filter, sort, and paginate Harper REST APIs.\n---\n\n# Querying REST APIs\n\nInstructions for the agent to follow when querying Harper's REST APIs.\n\n## When to Use\n\nUse this skill when you need to perform advanced data retrieval (filtering, sorting, pagination, joins) using Harper's automatic REST endpoints.\n\n## How It Works\n\n1. **Basic Filtering**: Use attribute names as query parameters: `GET /Table/?key=value`.\n2. **Use Comparison Operators**: Append operators like `gt`, `ge`, `lt`, `le`, `ne` using FIQL-style syntax: `GET /Table/?price=gt=100`.\n3. **Apply Logic and Grouping**: Use `&` for AND, `|` for OR, and `()` for grouping: `GET /Table/?(rating=5|featured=true)&price=lt=50`.\n4. **Select Specific Fields**: Use `select()` to limit returned attributes: `GET /Table/?select(name,price)`.\n5. **Paginate Results**: Use `limit(count)` or `limit(offset, count)` to set the number of records to return and skip.\n - Example (first 10): `GET /Table/?limit(10)`\n - Example (skip 20, return 10): `GET /Table/?limit(20, 10)`\n6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc) before the field name. Avoid `sort=field` format.\n - Example (asc): `GET /Table/?sort(+name)`\n - Example (desc): `GET /Table/?sort(-price)`\n - Example (combined): `GET /Table/?sort(-price,+name)`\n7. **Query Relationships**: Use dot syntax for tables linked with `@relationship`: `GET /Book/?author.name=Harper`.\n",
|
|
43
45
|
"real-time-apps": "---\nname: real-time-apps\ndescription: How to build real-time features in Harper using WebSockets and Pub/Sub.\n---\n\n# Real-time Applications\n\nInstructions for the agent to follow when building real-time applications in Harper.\n\n## When to Use\n\nUse this skill when you need to stream live updates to clients, implement chat features, or provide real-time data synchronization between the database and a frontend.\n\n## How It Works\n\n1. **Check Automatic WebSockets**: If you only need to stream table changes, use [Automatic APIs](automatic-apis.md) which provide a WebSocket endpoint for every `@export`ed table.\n2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method.\n3. **Use Pub/Sub**: Use `tables.TableName.subscribe(query)` to listen for specific data changes and stream them to the client.\n4. **Handle SSE**: Ensure your `connect` method gracefully handles cases where `incomingMessages` is null (Server-Sent Events).\n5. **Connect from Client**: Use standard WebSockets (`new WebSocket('wss://...')`) to connect to your resource endpoint. Ensure you use the appropriate scheme (`ws://` for HTTP, `wss://` for HTTPS).\n\n## Examples\n\n### Bi-directional WebSocket Resource\n\n```typescript\nimport { Resource, tables } from 'harperdb';\n\nexport class MySocket extends Resource {\n\tasync *connect(target, incomingMessages) {\n\t\t// Subscribe to table changes\n\t\tconst subscription = await tables.MyTable.subscribe(target);\n\t\tif (!incomingMessages) {\n\t\t\treturn subscription; // SSE mode\n\t\t}\n\n\t\t// Handle incoming client messages\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield { received: message };\n\t\t}\n\t}\n}\n```\n",
|
|
@@ -51,4 +53,4 @@ export const rules = {
|
|
|
51
53
|
/**
|
|
52
54
|
* The content of the Harper Best Practices SKILL.md.
|
|
53
55
|
*/
|
|
54
|
-
export const skillSummary = "---\nname: harper-best-practices\ndescription: Best practices for building Harper applications, covering schema definition,\n automatic APIs, authentication, custom resources, and data handling.\n Triggers on tasks involving Harper database design, API implementation,\n and deployment.\nlicense: Apache-2.0\nmetadata:\n author: harper\n version: '1.0.0'\n---\n\n# Harper Best Practices\n\nGuidelines for building scalable, secure, and performant applications on Harper. These practices cover everything from initial schema design to advanced deployment strategies.\n\n## When to Use\n\nReference these guidelines when:\n\n- Defining or modifying database schemas\n- Implementing or extending REST/WebSocket APIs\n- Handling authentication and session management\n- Working with custom resources and extensions\n- Optimizing data storage and retrieval (Blobs, Vector Indexing)\n- Deploying applications to Harper Fabric\n\n## How It Works\n\n1. Review the requirements for the task (schema design, API needs, or infrastructure setup).\n2. Consult the relevant category under \"Rule Categories by Priority\" to understand the impact of your decisions.\n3. Apply specific rules from the \"Quick Reference\" section below by reading their detailed rule files.\n4. If you're building a new table, prioritize the `schema-` rules.\n5. If you're extending functionality, consult the `logic-` and `api-` rules.\n6. Validate your implementation against the `ops-` rules before deployment.\n\n## Examples\n\nSee the concrete examples embedded in each rule subsection below (GraphQL schemas, REST query patterns, and deployment workflow snippets).\n\n## Rule Categories by Priority\n\n| Priority | Category | Impact | Prefix |\n| -------- | -------------------- | ------ | --------- |\n| 1 | Schema & Data Design | HIGH | `schema-` |\n| 2 | API & Communication | HIGH | `api-` |\n| 3 | Logic & Extension | MEDIUM | `logic-` |\n| 4 | Infrastructure & Ops | MEDIUM | `ops-` |\n\n## Quick Reference\n\n### 1. Schema & Data Design (HIGH)\n\n- `adding-tables-with-schemas` - Define tables using GraphQL schemas and directives\n- `schema-design-tooling` - Core directives and GraphQL IDE/agent configuration\n- `defining-relationships` - Link tables using the `@relationship` directive\n- `vector-indexing` - Efficient similarity search with vector indexes\n- `using-blob-datatype` - Store and retrieve large data (Blobs)\n- `handling-binary-data` - Manage binary data like images or MP3s\n\n### 2. API & Communication (HIGH)\n\n- `automatic-apis` - Leverage automatically generated CRUD endpoints\n- `querying-rest-apis` - Filters, sorting, and pagination in REST requests\n- `real-time-apps` - WebSockets and Pub/Sub for Real-Time Apps\n- `checking-authentication` - Secure apps with session-based identity verification\n\n### 3. Logic & Extension (MEDIUM)\n\n- `custom-resources` - Define custom REST endpoints using JS/TS\n- `extending-tables` - Add custom logic to generated table resources\n- `programmatic-table-requests` - Advanced filtering and sorting in code\n- `typescript-type-stripping` - Use TypeScript without build tools\n- `caching` - Implement and define caching for performance\n\n### 4. Infrastructure & Ops (MEDIUM)\n\n- `deploying-to-harper-fabric` - Scale globally with Harper Fabric\n- `creating-a-fabric-account-and-cluster` - Setting up your Harper Fabric cloud infrastructure\n- `creating-harper-apps` - Quickstart with `npm create harper@latest`\n- `serving-web-content` - Ways to serve web content from Harper\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/adding-tables-with-schemas.md\nrules/schema-design-tooling.md\nrules/automatic-apis.md\nrules/creating-harper-apps.md\n```\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded: `AGENTS.md`\n";
|
|
56
|
+
export const skillSummary = "---\nname: harper-best-practices\ndescription: Best practices for building Harper applications, covering schema definition,\n automatic APIs, authentication, custom resources, and data handling.\n Triggers on tasks involving Harper database design, API implementation,\n and deployment.\nlicense: Apache-2.0\nmetadata:\n author: harper\n version: '1.0.0'\n---\n\n# Harper Best Practices\n\nGuidelines for building scalable, secure, and performant applications on Harper. These practices cover everything from initial schema design to advanced deployment strategies.\n\n## When to Use\n\nReference these guidelines when:\n\n- Defining or modifying database schemas\n- Implementing or extending REST/WebSocket APIs\n- Handling authentication and session management\n- Working with custom resources and extensions\n- Optimizing data storage and retrieval (Blobs, Vector Indexing)\n- Deploying applications to Harper Fabric\n\n## How It Works\n\n1. Review the requirements for the task (schema design, API needs, or infrastructure setup).\n2. Consult the relevant category under \"Rule Categories by Priority\" to understand the impact of your decisions.\n3. Apply specific rules from the \"Quick Reference\" section below by reading their detailed rule files.\n4. If you're building a new table, prioritize the `schema-` rules.\n5. If you're extending functionality, consult the `logic-` and `api-` rules.\n6. Validate your implementation against the `ops-` rules before deployment.\n\n## Examples\n\nSee the concrete examples embedded in each rule subsection below (GraphQL schemas, REST query patterns, and deployment workflow snippets).\n\n## Rule Categories by Priority\n\n| Priority | Category | Impact | Prefix |\n| -------- | -------------------- | ------ | --------- |\n| 1 | Schema & Data Design | HIGH | `schema-` |\n| 2 | API & Communication | HIGH | `api-` |\n| 3 | Logic & Extension | MEDIUM | `logic-` |\n| 4 | Infrastructure & Ops | MEDIUM | `ops-` |\n\n## Quick Reference\n\n### 1. Schema & Data Design (HIGH)\n\n- `adding-tables-with-schemas` - Define tables using GraphQL schemas and directives\n- `schema-design-tooling` - Core directives and GraphQL IDE/agent configuration\n- `defining-relationships` - Link tables using the `@relationship` directive\n- `vector-indexing` - Efficient similarity search with vector indexes\n- `using-blob-datatype` - Store and retrieve large data (Blobs)\n- `handling-binary-data` - Manage binary data like images or MP3s\n\n### 2. API & Communication (HIGH)\n\n- `automatic-apis` - Leverage automatically generated CRUD endpoints\n- `querying-rest-apis` - Filters, sorting, and pagination in REST requests\n- `real-time-apps` - WebSockets and Pub/Sub for Real-Time Apps\n- `checking-authentication` - Secure apps with session-based identity verification\n\n### 3. Logic & Extension (MEDIUM)\n\n- `custom-resources` - Define custom REST endpoints using JS/TS\n- `extending-tables` - Add custom logic to generated table resources\n- `programmatic-table-requests` - Advanced filtering and sorting in code\n- `typescript-type-stripping` - Use TypeScript without build tools\n- `caching` - Implement and define caching for performance\n\n### 4. Infrastructure & Ops (MEDIUM)\n\n- `deploying-to-harper-fabric` - Scale globally with Harper Fabric\n- `creating-a-fabric-account-and-cluster` - Setting up your Harper Fabric cloud infrastructure\n- `creating-harper-apps` - Quickstart with `npm create harper@latest`\n- `serving-web-content` - Ways to serve web content from Harper\n- `logging` - Use standard console and Harper's granular logger\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/adding-tables-with-schemas.md\nrules/schema-design-tooling.md\nrules/automatic-apis.md\nrules/creating-harper-apps.md\nrules/logging.md\n```\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded: `AGENTS.md`\n";
|
|
@@ -29,6 +29,7 @@ Guidelines for building scalable, secure, and performant applications on Harper.
|
|
|
29
29
|
- 4.2 [Creating a Fabric Account and Cluster](#42-creating-a-fabric-account-and-cluster)
|
|
30
30
|
- 4.3 [Deploying to Harper Fabric](#43-deploying-to-harper-fabric)
|
|
31
31
|
- 4.4 [Serving Web Content](#44-serving-web-content)
|
|
32
|
+
- 4.5 [Logging Best Practices](#45-logging-best-practices)
|
|
32
33
|
|
|
33
34
|
---
|
|
34
35
|
|
|
@@ -500,3 +501,91 @@ Two ways to serve web content from a Harper application.
|
|
|
500
501
|
|
|
501
502
|
1. **Static Serving**: Serve HTML, CSS, and JS files directly. If using the Vite plugin for development, ensure Harper is running (e.g., `harperdb run .`) to allow for Hot Module Replacement (HMR).
|
|
502
503
|
2. **Dynamic Rendering**: Use custom resources to render content on the fly.
|
|
504
|
+
|
|
505
|
+
### 4.5 Logging Best Practices
|
|
506
|
+
|
|
507
|
+
Harper provides a robust logging system that captures standard output and offers a granular, tagged logging interface for both local and deployed environments.
|
|
508
|
+
|
|
509
|
+
#### Standard Console Logging
|
|
510
|
+
|
|
511
|
+
The simplest way to log in Harper is using standard JavaScript console methods. `console.log()`, `console.warn()`, `console.error()`, and `console.trace()` are automatically captured by Harper and can be viewed in the logs.
|
|
512
|
+
|
|
513
|
+
- `console.log(...)`: Captured as `stdout` level in Harper logs.
|
|
514
|
+
- `console.warn(...)`: Captured as `stderr` level in Harper logs.
|
|
515
|
+
- `console.error(...)`: Captured as `stderr` level in Harper logs.
|
|
516
|
+
- `console.trace(...)`: Captured as `stdout` level in Harper logs (includes stack trace).
|
|
517
|
+
|
|
518
|
+
#### Harper Logger
|
|
519
|
+
|
|
520
|
+
For more granularity and better organization, use Harper's built-in `logger`. You can use the global `logger` object or import it from the `harper` package.
|
|
521
|
+
|
|
522
|
+
##### Log Levels
|
|
523
|
+
|
|
524
|
+
The Harper `logger` supports the following levels (ordered by increasing severity):
|
|
525
|
+
|
|
526
|
+
- `trace`
|
|
527
|
+
- `debug`
|
|
528
|
+
- `info`
|
|
529
|
+
- `warn`
|
|
530
|
+
- `error`
|
|
531
|
+
- `fatal`
|
|
532
|
+
- `notify`
|
|
533
|
+
|
|
534
|
+
##### Usage
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
import { logger, loggerWithTag } from 'harper';
|
|
538
|
+
|
|
539
|
+
// Basic logging
|
|
540
|
+
logger.info('Application started');
|
|
541
|
+
logger.error('An error occurred', error);
|
|
542
|
+
|
|
543
|
+
// Tagged logging for better filtering (Namespacing)
|
|
544
|
+
const authLogger = loggerWithTag('auth');
|
|
545
|
+
authLogger.debug('User login attempt', { userId: '123' });
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
Using `loggerWithTag` is highly recommended for grouping related logs, making them much easier to filter and analyze in the Harper Studio or via the API.
|
|
549
|
+
|
|
550
|
+
#### Programmatic Log Retrieval
|
|
551
|
+
|
|
552
|
+
You can programmatically read logs from a deployed Harper instance using the `read_log` operation. This is useful for building custom monitoring tools or debugging dashboards.
|
|
553
|
+
|
|
554
|
+
##### `read_log` Operation
|
|
555
|
+
|
|
556
|
+
The `read_log` operation is a POST request to the Harper instance.
|
|
557
|
+
|
|
558
|
+
**Example Request:**
|
|
559
|
+
|
|
560
|
+
```json
|
|
561
|
+
{
|
|
562
|
+
"operation": "read_log",
|
|
563
|
+
"limit": 100,
|
|
564
|
+
"start": 0,
|
|
565
|
+
"level": "error",
|
|
566
|
+
"order": "desc",
|
|
567
|
+
"from": "2024-01-01T00:00:00.000Z",
|
|
568
|
+
"until": "2024-01-02T00:00:00.000Z"
|
|
569
|
+
}
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
##### Parameters
|
|
573
|
+
|
|
574
|
+
- `limit`: Number of log entries to return.
|
|
575
|
+
- `start`: Offset for pagination.
|
|
576
|
+
- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).
|
|
577
|
+
- `from`: ISO 8601 timestamp to start reading from.
|
|
578
|
+
- `until`: ISO 8601 timestamp to stop reading at.
|
|
579
|
+
- `order`: Sort order, either `asc` or `desc`.
|
|
580
|
+
- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.
|
|
581
|
+
|
|
582
|
+
##### Log Entry Structure
|
|
583
|
+
|
|
584
|
+
Each log entry returned by `read_log` typically includes:
|
|
585
|
+
|
|
586
|
+
- `level`: The severity level of the log.
|
|
587
|
+
- `timestamp`: When the log was recorded.
|
|
588
|
+
- `thread`: The execution thread.
|
|
589
|
+
- `tags`: An array of tags (e.g., from `loggerWithTag`).
|
|
590
|
+
- `node`: The node name in a Harper cluster.
|
|
591
|
+
- `message`: The logged content.
|
|
@@ -79,6 +79,7 @@ See the concrete examples embedded in each rule subsection below (GraphQL schema
|
|
|
79
79
|
- `creating-a-fabric-account-and-cluster` - Setting up your Harper Fabric cloud infrastructure
|
|
80
80
|
- `creating-harper-apps` - Quickstart with `npm create harper@latest`
|
|
81
81
|
- `serving-web-content` - Ways to serve web content from Harper
|
|
82
|
+
- `logging` - Use standard console and Harper's granular logger
|
|
82
83
|
|
|
83
84
|
## How to Use
|
|
84
85
|
|
|
@@ -89,6 +90,7 @@ rules/adding-tables-with-schemas.md
|
|
|
89
90
|
rules/schema-design-tooling.md
|
|
90
91
|
rules/automatic-apis.md
|
|
91
92
|
rules/creating-harper-apps.md
|
|
93
|
+
rules/logging.md
|
|
92
94
|
```
|
|
93
95
|
|
|
94
96
|
## Full Compiled Document
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: logging
|
|
3
|
+
description: Best practices for logging in Harper, including console capture, the granular logger interface, and programmatic log retrieval.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Logging Best Practices
|
|
7
|
+
|
|
8
|
+
Harper provides a robust logging system that captures standard output and offers a granular, tagged logging interface for both local and deployed environments.
|
|
9
|
+
|
|
10
|
+
## Standard Console Logging
|
|
11
|
+
|
|
12
|
+
The simplest way to log in Harper is using standard JavaScript console methods. `console.log()`, `console.warn()`, `console.error()`, and `console.trace()` are automatically captured by Harper and can be viewed in the logs.
|
|
13
|
+
|
|
14
|
+
- `console.log(...)`: Captured as `stdout` level in Harper logs.
|
|
15
|
+
- `console.warn(...)`: Captured as `stderr` level in Harper logs.
|
|
16
|
+
- `console.error(...)`: Captured as `stderr` level in Harper logs.
|
|
17
|
+
- `console.trace(...)`: Captured as `stdout` level in Harper logs (includes stack trace).
|
|
18
|
+
|
|
19
|
+
## Harper Logger
|
|
20
|
+
|
|
21
|
+
For more granularity and better organization, use Harper's built-in `logger`. You can use the global `logger` object or import it from the `harper` package.
|
|
22
|
+
|
|
23
|
+
### Log Levels
|
|
24
|
+
|
|
25
|
+
The Harper `logger` supports the following levels (ordered by increasing severity):
|
|
26
|
+
|
|
27
|
+
- `trace`
|
|
28
|
+
- `debug`
|
|
29
|
+
- `info`
|
|
30
|
+
- `warn`
|
|
31
|
+
- `error`
|
|
32
|
+
- `fatal`
|
|
33
|
+
- `notify`
|
|
34
|
+
|
|
35
|
+
### Usage
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { logger, loggerWithTag } from 'harper';
|
|
39
|
+
|
|
40
|
+
// Basic logging
|
|
41
|
+
logger.info('Application started');
|
|
42
|
+
logger.error('An error occurred', error);
|
|
43
|
+
|
|
44
|
+
// Tagged logging for better filtering (Namespacing)
|
|
45
|
+
const authLogger = loggerWithTag('auth');
|
|
46
|
+
authLogger.debug('User login attempt', { userId: '123' });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Using `loggerWithTag` is highly recommended for grouping related logs, making them much easier to filter and analyze in the Harper Studio or via the API.
|
|
50
|
+
|
|
51
|
+
## Programmatic Log Retrieval
|
|
52
|
+
|
|
53
|
+
You can programmatically read logs from a deployed Harper instance using the `read_log` operation. This is useful for building custom monitoring tools or debugging dashboards.
|
|
54
|
+
|
|
55
|
+
### `read_log` Operation
|
|
56
|
+
|
|
57
|
+
The `read_log` operation is a POST request to the Harper instance.
|
|
58
|
+
|
|
59
|
+
**Example Request:**
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{
|
|
63
|
+
"operation": "read_log",
|
|
64
|
+
"limit": 100,
|
|
65
|
+
"start": 0,
|
|
66
|
+
"level": "error",
|
|
67
|
+
"order": "desc",
|
|
68
|
+
"from": "2024-01-01T00:00:00.000Z",
|
|
69
|
+
"until": "2024-01-02T00:00:00.000Z"
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Parameters
|
|
74
|
+
|
|
75
|
+
- `limit`: Number of log entries to return.
|
|
76
|
+
- `start`: Offset for pagination.
|
|
77
|
+
- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).
|
|
78
|
+
- `from`: ISO 8601 timestamp to start reading from.
|
|
79
|
+
- `until`: ISO 8601 timestamp to stop reading at.
|
|
80
|
+
- `order`: Sort order, either `asc` or `desc`.
|
|
81
|
+
- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.
|
|
82
|
+
|
|
83
|
+
### Log Entry Structure
|
|
84
|
+
|
|
85
|
+
Each log entry returned by `read_log` typically includes:
|
|
86
|
+
|
|
87
|
+
- `level`: The severity level of the log.
|
|
88
|
+
- `timestamp`: When the log was recorded.
|
|
89
|
+
- `thread`: The execution thread.
|
|
90
|
+
- `tags`: An array of tags (e.g., from `loggerWithTag`).
|
|
91
|
+
- `node`: The node name in a Harper cluster.
|
|
92
|
+
- `message`: The logged content.
|