@harperfast/template-vue-studio 1.6.2 → 1.6.4
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/.agents/skills/harper-best-practices/AGENTS.md +1428 -303
- package/.agents/skills/harper-best-practices/SKILL.md +24 -20
- package/.agents/skills/harper-best-practices/rules/adding-tables-with-schemas.md +4 -2
- package/.agents/skills/harper-best-practices/rules/automatic-apis.md +144 -16
- package/.agents/skills/harper-best-practices/rules/caching.md +134 -21
- package/.agents/skills/harper-best-practices/rules/checking-authentication.md +139 -148
- package/.agents/skills/harper-best-practices/rules/creating-a-fabric-account-and-cluster.md +2 -0
- package/.agents/skills/harper-best-practices/rules/creating-harper-apps.md +2 -0
- package/.agents/skills/harper-best-practices/rules/custom-resources.md +5 -3
- package/.agents/skills/harper-best-practices/rules/defining-relationships.md +2 -0
- package/.agents/skills/harper-best-practices/rules/deploying-to-harper-fabric.md +97 -77
- package/.agents/skills/harper-best-practices/rules/extending-tables.md +3 -1
- package/.agents/skills/harper-best-practices/rules/handling-binary-data.md +2 -0
- package/.agents/skills/harper-best-practices/rules/logging.md +154 -77
- package/.agents/skills/harper-best-practices/rules/programmatic-table-requests.md +91 -0
- package/.agents/skills/harper-best-practices/rules/querying-rest-apis.md +190 -15
- package/.agents/skills/harper-best-practices/rules/real-time-apps.md +80 -21
- package/.agents/skills/harper-best-practices/rules/schema-design-tooling.md +4 -2
- package/.agents/skills/harper-best-practices/rules/serving-web-content.md +3 -2
- package/.agents/skills/harper-best-practices/rules/typescript-type-stripping.md +3 -1
- package/.agents/skills/harper-best-practices/rules/using-blob-datatype.md +3 -1
- package/.agents/skills/harper-best-practices/rules/vector-indexing.md +85 -120
- package/.agents/skills/harper-best-practices/rules.manifest.yaml +258 -0
- package/package.json +1 -1
- package/skills-lock.json +1 -1
|
@@ -2,41 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Guidelines for building scalable, secure, and performant applications on Harper. These practices cover everything from initial schema design to advanced deployment strategies.
|
|
4
4
|
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## Table of Contents
|
|
8
|
-
|
|
9
|
-
1. [Schema & Data Design](#1-schema--data-design) — **HIGH**
|
|
10
|
-
- 1.1 [Adding Tables with Schemas](#11-adding-tables-with-schemas)
|
|
11
|
-
- 1.2 [Schema Design & Tooling](#12-schema-design--tooling)
|
|
12
|
-
- 1.3 [Defining Relationships](#13-defining-relationships)
|
|
13
|
-
- 1.4 [Vector Indexing](#14-vector-indexing)
|
|
14
|
-
- 1.5 [Using Blobs](#15-using-blobs)
|
|
15
|
-
- 1.6 [Handling Binary Data](#16-handling-binary-data)
|
|
16
|
-
2. [API & Communication](#2-api--communication) — **HIGH**
|
|
17
|
-
- 2.1 [Automatic REST APIs](#21-automatic-rest-apis)
|
|
18
|
-
- 2.2 [Querying REST APIs](#22-querying-rest-apis)
|
|
19
|
-
- 2.3 [Real-time Applications](#23-real-time-applications)
|
|
20
|
-
- 2.4 [Checking Authentication](#24-checking-authentication)
|
|
21
|
-
3. [Logic & Extension](#3-logic--extension) — **MEDIUM**
|
|
22
|
-
- 3.1 [Custom Resources](#31-custom-resources)
|
|
23
|
-
- 3.2 [Extending Table Resources](#32-extending-table-resources)
|
|
24
|
-
- 3.3 [Programmatic Table Requests](#33-programmatic-table-requests)
|
|
25
|
-
- 3.4 [TypeScript Type Stripping](#34-typescript-type-stripping)
|
|
26
|
-
- 3.5 [Caching](#35-caching)
|
|
27
|
-
4. [Infrastructure & Ops](#4-infrastructure--ops) — **MEDIUM**
|
|
28
|
-
- 4.1 [Creating Harper Applications](#41-creating-harper-applications)
|
|
29
|
-
- 4.2 [Creating a Fabric Account and Cluster](#42-creating-a-fabric-account-and-cluster)
|
|
30
|
-
- 4.3 [Deploying to Harper Fabric](#43-deploying-to-harper-fabric)
|
|
31
|
-
- 4.4 [Serving Web Content](#44-serving-web-content)
|
|
32
|
-
- 4.5 [Logging Best Practices](#45-logging-best-practices)
|
|
33
|
-
|
|
34
|
-
---
|
|
35
|
-
|
|
36
5
|
## 1. Schema & Data Design
|
|
37
6
|
|
|
38
|
-
**Impact: HIGH**
|
|
39
|
-
|
|
40
7
|
### 1.1 Adding Tables with Schemas
|
|
41
8
|
|
|
42
9
|
Instructions for the agent to follow when adding tables to a Harper database.
|
|
@@ -48,12 +15,22 @@ Use this skill when you need to define new data structures or modify existing on
|
|
|
48
15
|
#### How It Works
|
|
49
16
|
|
|
50
17
|
1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.
|
|
51
|
-
2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/
|
|
52
|
-
3. **Define Relationships**: Link tables together using the `@relationship` directive.
|
|
53
|
-
4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
18
|
+
2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.
|
|
19
|
+
3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.
|
|
20
|
+
4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.
|
|
21
|
+
- `GET /{TableName}`: Describes the schema itself.
|
|
22
|
+
- `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.
|
|
23
|
+
- `GET /{TableName}/{id}`: Retrieves a single record by its ID.
|
|
24
|
+
- `POST /{TableName}/`: Creates a new record.
|
|
25
|
+
- `PUT /{TableName}/{id}`: Updates an existing record.
|
|
26
|
+
- `PATCH /{TableName}/{id}`: Performs a partial update on a record.
|
|
27
|
+
- `DELETE /{TableName}/`: Deletes all records or filtered records.
|
|
28
|
+
- `DELETE /{TableName}/{id}`: Deletes a single record by its ID.
|
|
29
|
+
5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.
|
|
30
|
+
|
|
31
|
+
#### Examples
|
|
32
|
+
|
|
33
|
+
In a hypothetical `schemas/ExamplePerson.graphql`:
|
|
57
34
|
|
|
58
35
|
```graphql
|
|
59
36
|
type ExamplePerson @table @export {
|
|
@@ -69,7 +46,7 @@ Harper uses GraphQL schemas to define database tables, relationships, and APIs.
|
|
|
69
46
|
|
|
70
47
|
#### Core Harper Directives
|
|
71
48
|
|
|
72
|
-
Harper extends GraphQL with custom directives that define database behavior. These are typically defined in `node_modules/
|
|
49
|
+
Harper extends GraphQL with custom directives that define database behavior. These are typically defined in `node_modules/harper/schema.graphql`. If you don't have access to that file, here is a reference of the most important ones:
|
|
73
50
|
|
|
74
51
|
##### Table Definition
|
|
75
52
|
|
|
@@ -103,7 +80,7 @@ Create a file named `graphql.config.yml` in your project root with the following
|
|
|
103
80
|
|
|
104
81
|
```yaml
|
|
105
82
|
schema:
|
|
106
|
-
- 'node_modules/
|
|
83
|
+
- 'node_modules/harper/schema.graphql'
|
|
107
84
|
- 'schema.graphql'
|
|
108
85
|
- 'schemas/*.graphql'
|
|
109
86
|
```
|
|
@@ -129,16 +106,16 @@ my-harper-app/
|
|
|
129
106
|
|
|
130
107
|
### 1.3 Defining Relationships
|
|
131
108
|
|
|
132
|
-
|
|
109
|
+
Instructions for the agent to follow when defining relationships between Harper tables.
|
|
133
110
|
|
|
134
111
|
#### When to Use
|
|
135
112
|
|
|
136
|
-
Use this when you
|
|
113
|
+
Use this skill when you need to link data across different tables, enabling automatic joins and efficient related-data fetching via REST APIs.
|
|
137
114
|
|
|
138
115
|
#### How It Works
|
|
139
116
|
|
|
140
117
|
1. **Identify the Relationship Type**: Determine if it's one-to-one, many-to-one, or one-to-many.
|
|
141
|
-
2. **
|
|
118
|
+
2. **Use the `@relationship` Directive**: Apply it to a field in your GraphQL schema.
|
|
142
119
|
- **Many-to-One (Current table holds FK)**: Use `from`.
|
|
143
120
|
```graphql
|
|
144
121
|
type Book @table @export {
|
|
@@ -153,232 +130,1307 @@ Use this when you have two or more tables that need to be logically linked (e.g.
|
|
|
153
130
|
}
|
|
154
131
|
```
|
|
155
132
|
3. **Query with Relationships**: Use dot syntax in REST API calls for filtering or the `select()` operator for including related data.
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
```graphql
|
|
160
|
-
type Product @table @export {
|
|
161
|
-
id: ID @primaryKey
|
|
162
|
-
name: String
|
|
163
|
-
categoryId: ID
|
|
164
|
-
category: Category @relationship(from: "categoryId")
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
type Category @table @export {
|
|
168
|
-
id: ID @primaryKey
|
|
169
|
-
name: String
|
|
170
|
-
products: [Product] @relationship(to: "categoryId")
|
|
171
|
-
}
|
|
172
|
-
```
|
|
133
|
+
- Example Filter: `GET /Book/?author.name=Harper`
|
|
134
|
+
- Example Select: `GET /Author/?select(name,books(title))`
|
|
173
135
|
|
|
174
136
|
### 1.4 Vector Indexing
|
|
175
137
|
|
|
176
|
-
|
|
138
|
+
Instructions for the agent to follow when enabling and querying vector indexes for similarity search in Harper using the HNSW algorithm.
|
|
177
139
|
|
|
178
140
|
#### When to Use
|
|
179
141
|
|
|
180
|
-
|
|
142
|
+
Apply this rule when adding a vector index to a Harper table schema or writing similarity search queries against high-dimensional vector fields. Use it whenever you need approximate nearest-neighbor search, distance-threshold filtering, or distance-scored results.
|
|
181
143
|
|
|
182
144
|
#### How It Works
|
|
183
145
|
|
|
184
|
-
1. **
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
146
|
+
1. **Declare the vector index on a `[Float]` field**: Add `@indexed(type: "HNSW")` to any `[Float]` attribute in a `@table` type. See [adding-tables-with-schemas.md](adding-tables-with-schemas.md) for general schema setup.
|
|
147
|
+
|
|
148
|
+
```graphql
|
|
149
|
+
type Document @table {
|
|
150
|
+
id: Long @primaryKey
|
|
151
|
+
textEmbeddings: [Float] @indexed(type: "HNSW")
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
2. **Query by nearest neighbors using `sort`**: Call `Document.search()` with a `sort` object containing `attribute` (the indexed field name) and `target` (the query vector). Include `limit` to cap results.
|
|
156
|
+
|
|
157
|
+
```javascript
|
|
158
|
+
let results = Document.search({
|
|
159
|
+
sort: { attribute: 'textEmbeddings', target: searchVector },
|
|
160
|
+
limit: 5,
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.
|
|
165
|
+
|
|
166
|
+
```javascript
|
|
167
|
+
let results = Document.search({
|
|
168
|
+
conditions: [{ attribute: 'price', comparator: 'lt', value: 50 }],
|
|
169
|
+
sort: { attribute: 'textEmbeddings', target: searchVector },
|
|
170
|
+
limit: 5,
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. Omit `sort`.
|
|
175
|
+
|
|
176
|
+
```javascript
|
|
177
|
+
let results = Document.search({
|
|
178
|
+
conditions: {
|
|
179
|
+
attribute: 'textEmbeddings',
|
|
180
|
+
comparator: 'lt',
|
|
181
|
+
value: 0.1,
|
|
182
|
+
target: searchVector,
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Works with both `sort`-based and `conditions`-based queries.
|
|
188
|
+
|
|
189
|
+
```javascript
|
|
190
|
+
let results = Document.search({
|
|
191
|
+
select: ['name', '$distance'],
|
|
192
|
+
sort: { attribute: 'textEmbeddings', target: searchVector },
|
|
193
|
+
limit: 5,
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
6. **Tune HNSW parameters**: Pass additional parameters to `@indexed(type: "HNSW", ...)` to control index quality and performance.
|
|
188
198
|
|
|
189
|
-
|
|
199
|
+
| Parameter | Default | Description |
|
|
200
|
+
| ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |
|
|
201
|
+
| `distance` | `"cosine"` | Distance function: `"euclidean"` or `"cosine"` (negative cosine similarity) |
|
|
202
|
+
| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |
|
|
203
|
+
| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |
|
|
204
|
+
| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |
|
|
205
|
+
| `mL` | computed from `M` | Normalization factor for level generation |
|
|
206
|
+
| `efSearchConstruction` | `50` | Max nodes explored during search |
|
|
207
|
+
|
|
208
|
+
#### Examples
|
|
209
|
+
|
|
210
|
+
**Schema with custom HNSW parameters:**
|
|
190
211
|
|
|
191
212
|
```graphql
|
|
192
|
-
type Document @table
|
|
193
|
-
id:
|
|
194
|
-
|
|
195
|
-
|
|
213
|
+
type Document @table {
|
|
214
|
+
id: Long @primaryKey
|
|
215
|
+
textEmbeddings: [Float]
|
|
216
|
+
@indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efSearchConstruction: 100)
|
|
196
217
|
}
|
|
197
218
|
```
|
|
198
219
|
|
|
199
|
-
|
|
220
|
+
**Nearest-neighbor search with distance score:**
|
|
221
|
+
|
|
222
|
+
```javascript
|
|
223
|
+
let results = Document.search({
|
|
224
|
+
select: ['name', '$distance'],
|
|
225
|
+
sort: { attribute: 'textEmbeddings', target: searchVector },
|
|
226
|
+
limit: 5,
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Distance-threshold filter (no ranking):**
|
|
231
|
+
|
|
232
|
+
```javascript
|
|
233
|
+
let results = Document.search({
|
|
234
|
+
conditions: {
|
|
235
|
+
attribute: 'textEmbeddings',
|
|
236
|
+
comparator: 'lt',
|
|
237
|
+
value: 0.1,
|
|
238
|
+
target: searchVector,
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
#### Notes
|
|
244
|
+
|
|
245
|
+
- The default `distance` function is `cosine`. Pass `distance: "euclidean"` to switch.
|
|
246
|
+
- `efConstruction` controls index build quality; raising it improves recall at the cost of build time.
|
|
247
|
+
- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.
|
|
248
|
+
- Use the threshold (`conditions` + `target`) form when you want to bound result quality by a similarity cutoff rather than ranking by similarity.
|
|
200
249
|
|
|
201
|
-
|
|
250
|
+
### 1.5 Using Blob Datatype
|
|
251
|
+
|
|
252
|
+
Instructions for the agent to follow when working with the Blob data type in Harper.
|
|
202
253
|
|
|
203
254
|
#### When to Use
|
|
204
255
|
|
|
205
|
-
Use this when you need to store large
|
|
256
|
+
Use this skill when you need to store unstructured or large binary data (media, documents) that is too large for standard JSON fields. Blobs provide efficient storage and integrated streaming support.
|
|
206
257
|
|
|
207
258
|
#### How It Works
|
|
208
259
|
|
|
209
|
-
1. **Define
|
|
210
|
-
|
|
211
|
-
|
|
260
|
+
1. **Define Blob Fields**: In your GraphQL schema, use the `Blob` type:
|
|
261
|
+
```graphql
|
|
262
|
+
type MyTable @table {
|
|
263
|
+
id: ID @primaryKey
|
|
264
|
+
data: Blob
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
2. **Create and Store Blobs**: Use `createBlob()` from Harper's globals to wrap Buffers or Streams:
|
|
268
|
+
```javascript
|
|
269
|
+
import { tables } from 'harper';
|
|
270
|
+
const blob = createBlob(largeBuffer);
|
|
271
|
+
await tables.MyTable.put('my-id', { data: blob });
|
|
272
|
+
```
|
|
273
|
+
3. **Use Streaming (Optional)**: For very large files, pass a stream to `createBlob()` to avoid loading the entire file into memory.
|
|
274
|
+
4. **Read Blob Data**: Retrieve the record and use `.bytes()` or streaming interfaces on the blob field:
|
|
275
|
+
```javascript
|
|
276
|
+
const record = await tables.MyTable.get('my-id');
|
|
277
|
+
const buffer = await record.data.bytes();
|
|
278
|
+
```
|
|
279
|
+
5. **Ensure Write Completion**: Use `saveBeforeCommit: true` in `createBlob` options if you need the blob fully written before the record is committed.
|
|
280
|
+
6. **Handle Errors**: Attach error listeners to the blob object to handle streaming failures.
|
|
212
281
|
|
|
213
282
|
### 1.6 Handling Binary Data
|
|
214
283
|
|
|
215
|
-
|
|
284
|
+
Instructions for the agent to follow when handling binary data in Harper.
|
|
216
285
|
|
|
217
286
|
#### When to Use
|
|
218
287
|
|
|
219
|
-
Use this when
|
|
288
|
+
Use this skill when you need to store binary files (images, audio, etc.) in the database or serve them back to clients via REST endpoints.
|
|
220
289
|
|
|
221
290
|
#### How It Works
|
|
222
291
|
|
|
223
|
-
1. **
|
|
224
|
-
2. **Streaming**: For large files, use streaming to minimize memory usage during upload and download.
|
|
225
|
-
3. **MIME Types**: Store the MIME type alongside the binary data to ensure it is served correctly by your application logic.
|
|
292
|
+
1. **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:
|
|
226
293
|
|
|
227
|
-
|
|
294
|
+
```typescript
|
|
295
|
+
async post(target, record) {
|
|
296
|
+
if (record.data) {
|
|
297
|
+
record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {
|
|
298
|
+
type: record.contentType || 'application/octet-stream',
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
return super.post(target, record);
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
2. **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`:
|
|
306
|
+
```typescript
|
|
307
|
+
async get(target) {
|
|
308
|
+
const record = await super.get(target);
|
|
309
|
+
if (record?.data) {
|
|
310
|
+
return {
|
|
311
|
+
status: 200,
|
|
312
|
+
headers: { 'Content-Type': record.data.type || 'application/octet-stream' },
|
|
313
|
+
body: record.data,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
return record;
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
3. **Use the Blob Type**: Ensure your GraphQL schema uses the `Blob` scalar for binary fields.
|
|
228
320
|
|
|
229
321
|
## 2. API & Communication
|
|
230
322
|
|
|
231
|
-
|
|
323
|
+
### 2.1 Automatic APIs
|
|
324
|
+
|
|
325
|
+
Instructions for the agent to follow when enabling and using Harper's automatically generated REST and WebSocket APIs.
|
|
326
|
+
|
|
327
|
+
#### When to Use
|
|
328
|
+
|
|
329
|
+
Apply this rule when adding REST or WebSocket API access to Harper tables or custom resources. Use it when configuring `config.yaml` to expose endpoints, mapping HTTP methods to resource operations, or implementing real-time WebSocket connections on a resource class.
|
|
232
330
|
|
|
233
|
-
|
|
331
|
+
#### How It Works
|
|
234
332
|
|
|
235
|
-
|
|
333
|
+
1. **Enable the REST plugin**: Add `rest: true` to your application's `config.yaml`. This activates the HTTP REST interface and enables WebSocket support by default.
|
|
236
334
|
|
|
237
|
-
|
|
335
|
+
```yaml
|
|
336
|
+
rest: true
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
To configure optional behavior:
|
|
340
|
+
|
|
341
|
+
```yaml
|
|
342
|
+
rest:
|
|
343
|
+
lastModified: true # enables Last-Modified response header support
|
|
344
|
+
webSocket: false # disables automatic WebSocket support (enabled by default)
|
|
345
|
+
```
|
|
238
346
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
-
|
|
246
|
-
-
|
|
347
|
+
2. **Export your resource in the schema**: Tables are not exposed by default. Use the `@export` directive in your schema definition to make a table available as a REST endpoint. The exported name defines the base URL path, served on the application HTTP server port (default `9926`).
|
|
348
|
+
|
|
349
|
+
3. **Use the correct URL structure**: The REST interface follows a consistent path convention.
|
|
350
|
+
|
|
351
|
+
| Path | Description |
|
|
352
|
+
| -------------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
353
|
+
| `/my-resource` | Returns a description of the resource (e.g., table metadata) |
|
|
354
|
+
| `/my-resource/` | Trailing slash — represents the full collection; append query parameters to search |
|
|
355
|
+
| `/my-resource/record-id` | A specific record identified by its primary key |
|
|
356
|
+
| `/my-resource/record-id/` | Trailing slash — collection of records with the given id prefix |
|
|
357
|
+
| `/my-resource/record-id/with/multiple/parts` | Record id with multiple path segments |
|
|
358
|
+
|
|
359
|
+
4. **Map HTTP methods to operations**: Each HTTP method maps to a resource method and operation.
|
|
360
|
+
- **GET** — Retrieve a record or search. Calls `get()`.
|
|
361
|
+
|
|
362
|
+
```
|
|
363
|
+
GET /MyTable/123
|
|
364
|
+
GET /MyTable/?name=Harper
|
|
365
|
+
GET /MyTable/123.propertyName
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Responses include an `ETag` header. Clients may send `If-None-Match` to receive `304 Not Modified` when the record is unchanged.
|
|
369
|
+
|
|
370
|
+
- **PUT** — Create or replace a record (upsert). Calls `put(record)`. Properties not in the body are removed.
|
|
371
|
+
|
|
372
|
+
```
|
|
373
|
+
PUT /MyTable/123
|
|
374
|
+
Content-Type: application/json
|
|
375
|
+
|
|
376
|
+
{ "name": "some data" }
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
- **POST** — Create a new record without specifying a primary key. Calls `post(data)`. The assigned key is returned in the `Location` response header.
|
|
380
|
+
|
|
381
|
+
```
|
|
382
|
+
POST /MyTable/
|
|
383
|
+
Content-Type: application/json
|
|
384
|
+
|
|
385
|
+
{ "name": "some data" }
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
- **PATCH** — Partially update a record, merging only provided properties. Unspecified properties are preserved.
|
|
389
|
+
|
|
390
|
+
```
|
|
391
|
+
PATCH /MyTable/123
|
|
392
|
+
Content-Type: application/json
|
|
393
|
+
|
|
394
|
+
{ "status": "active" }
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
- **DELETE** — Delete a record or all records matching a query.
|
|
398
|
+
```
|
|
399
|
+
DELETE /MyTable/123
|
|
400
|
+
DELETE /MyTable/?status=archived
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
5. **Access the auto-generated OpenAPI spec**: Harper generates an OpenAPI specification for all exported resources. Retrieve it at:
|
|
404
|
+
|
|
405
|
+
```
|
|
406
|
+
GET /openapi
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
6. **Connect via WebSocket**: When `rest` is enabled, WebSocket support is on by default. Connect to a resource URL to subscribe to change events for that resource.
|
|
410
|
+
|
|
411
|
+
```javascript
|
|
412
|
+
let ws = new WebSocket('wss://server/my-resource/341');
|
|
413
|
+
ws.onmessage = (event) => {
|
|
414
|
+
let data = JSON.parse(event.data);
|
|
415
|
+
};
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Connecting to `wss://server/my-resource/341` accesses the `my-resource` resource with record id `341` and subscribes to it. When the record changes or a message is published to it, the WebSocket connection receives the update.
|
|
419
|
+
|
|
420
|
+
7. **Implement a custom `connect()` handler**: Override `connect(incomingMessages)` on a resource class to control WebSocket behavior. The method must return an async iterable or generator that produces messages to send to the client.
|
|
421
|
+
|
|
422
|
+
#### Examples
|
|
423
|
+
|
|
424
|
+
**Simple echo server using an async generator**:
|
|
425
|
+
|
|
426
|
+
```javascript
|
|
427
|
+
export class Echo extends Resource {
|
|
428
|
+
async *connect(incomingMessages) {
|
|
429
|
+
for await (let message of incomingMessages) {
|
|
430
|
+
yield message; // echo each message back
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
**Using the default `connect()` with event-style access and a timer**:
|
|
437
|
+
|
|
438
|
+
```javascript
|
|
439
|
+
export class Example extends Resource {
|
|
440
|
+
connect(incomingMessages) {
|
|
441
|
+
let outgoingMessages = super.connect();
|
|
442
|
+
|
|
443
|
+
let timer = setInterval(() => {
|
|
444
|
+
outgoingMessages.send({ greeting: 'hi again!' });
|
|
445
|
+
}, 1000);
|
|
446
|
+
|
|
447
|
+
incomingMessages.on('data', (message) => {
|
|
448
|
+
outgoingMessages.send(message); // echo incoming messages
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
outgoingMessages.on('close', () => {
|
|
452
|
+
clearInterval(timer);
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
return outgoingMessages;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
**Minimal `config.yaml` enabling REST with WebSocket disabled**:
|
|
461
|
+
|
|
462
|
+
```yaml
|
|
463
|
+
rest:
|
|
464
|
+
webSocket: false
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
#### Notes
|
|
468
|
+
|
|
469
|
+
- Tables must be explicitly exported using `@export` in the schema — they are not exposed by default.
|
|
470
|
+
- `rest: true` is the minimal configuration to enable both REST and WebSocket support. See [real-time-apps.md](real-time-apps.md) for patterns around real-time WebSocket usage.
|
|
471
|
+
- For full query syntax on `GET` and `DELETE` with query parameters, see [querying-rest-apis.md](querying-rest-apis.md).
|
|
472
|
+
- The default `connect()` returns an iterable with a `send(message)` method and a `close` event for cleanup on disconnect.
|
|
473
|
+
- For MQTT over WebSockets, set the sub-protocol header `Sec-WebSocket-Protocol: mqtt`.
|
|
474
|
+
- In distributed environments, non-retained messages are delivered in the order received per node; retained messages (PUT/updated records) keep only the latest-timestamp version as the winning record across the cluster.
|
|
475
|
+
- Use the `Content-Type` request header to specify body format and the `Accept` header to request a specific response format.
|
|
247
476
|
|
|
248
477
|
### 2.2 Querying REST APIs
|
|
249
478
|
|
|
250
|
-
|
|
479
|
+
Instructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.
|
|
251
480
|
|
|
252
|
-
####
|
|
481
|
+
#### When to Use
|
|
253
482
|
|
|
254
|
-
|
|
255
|
-
- `sort(+field1, -field2)`: Fields to sort by. Use `+` for ascending and `-` for descending. Example: `?sort(+name)`, `?sort(-price, +name)`.
|
|
256
|
-
- `select(field1, field2)`: Specific fields to return. Example: `?select(id, name)`.
|
|
257
|
-
- `filter`: Advanced filtering using comparison operators and logic.
|
|
258
|
-
- Operators: `gt`, `ge`, `lt`, `le`, `ne`. Example: `?price=gt=100`.
|
|
259
|
-
- Logic: `&` (AND), `|` (OR), `()` (grouping). Example: `?(category=electronics|category=books)&price=lt=500`.
|
|
483
|
+
Apply this rule when building or modifying code that queries Harper REST endpoints with filtering, sorting, field selection, or pagination. Use it whenever constructing URLs against collection paths exposed by Harper's automatic REST interface (see [automatic-apis.md](automatic-apis.md)).
|
|
260
484
|
|
|
261
|
-
|
|
485
|
+
#### How It Works
|
|
486
|
+
|
|
487
|
+
1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.
|
|
488
|
+
|
|
489
|
+
```
|
|
490
|
+
GET /Product/?category=software
|
|
491
|
+
GET /Product/?category=software&inStock=true
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators directly in query parameter values.
|
|
495
|
+
|
|
496
|
+
| Operator | Meaning |
|
|
497
|
+
| ------------ | -------------------------------------- |
|
|
498
|
+
| `==` | Equal |
|
|
499
|
+
| `=lt=` | Less than |
|
|
500
|
+
| `=le=` | Less than or equal |
|
|
501
|
+
| `=gt=` | Greater than |
|
|
502
|
+
| `=ge=` | Greater than or equal |
|
|
503
|
+
| `=ne=`, `!=` | Not equal |
|
|
504
|
+
| `=ct=` | Contains (strings) |
|
|
505
|
+
| `=sw=` | Starts with (strings) |
|
|
506
|
+
| `=ew=` | Ends with (strings) |
|
|
507
|
+
| `=`, `===` | Strict equality (no type conversion) |
|
|
508
|
+
| `!==` | Strict inequality (no type conversion) |
|
|
509
|
+
|
|
510
|
+
```
|
|
511
|
+
GET /Product/?price=gt=100
|
|
512
|
+
GET /Product/?price=le=20
|
|
513
|
+
GET /Product/?name==Keyboard*
|
|
514
|
+
GET /Product/?category=software&price=gt=100&price=lt=200
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
For date fields, URL-encode colons as `%3A`:
|
|
518
|
+
|
|
519
|
+
```
|
|
520
|
+
GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.
|
|
524
|
+
|
|
525
|
+
```
|
|
526
|
+
GET /Product/?price=gt=100<=200
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
4. **Combine conditions with OR logic**: Use `|` instead of `&`.
|
|
530
|
+
|
|
531
|
+
```
|
|
532
|
+
GET /Product/?rating=5|featured=true
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
5. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.
|
|
536
|
+
|
|
537
|
+
```
|
|
538
|
+
GET /Product/?rating=5|(price=gt=100&price=lt=200)
|
|
539
|
+
GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
Construct grouped queries from JavaScript:
|
|
543
|
+
|
|
544
|
+
```javascript
|
|
545
|
+
let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join('|')}]`;
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
6. **Select specific properties with `select(`**: Use `select()` to control which fields are returned.
|
|
549
|
+
|
|
550
|
+
| Syntax | Returns |
|
|
551
|
+
| -------------------------------------- | ------------------------------------------- |
|
|
552
|
+
| `?select(property)` | Values of a single property directly |
|
|
553
|
+
| `?select(property1,property2)` | Objects with only the specified properties |
|
|
554
|
+
| `?select([property1,property2])` | Arrays of property values |
|
|
555
|
+
| `?select(property1,)` | Objects with a single specified property |
|
|
556
|
+
| `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |
|
|
557
|
+
|
|
558
|
+
```
|
|
559
|
+
GET /Product/?category=software&select(name)
|
|
560
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name})
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
7. **Limit results with `limit(`**: Use `limit(end)` or `limit(start,end)` to paginate.
|
|
564
|
+
|
|
565
|
+
```
|
|
566
|
+
GET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)
|
|
567
|
+
GET /Product/?rating=gt=3&limit(10,30)
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
8. **Sort results with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.
|
|
571
|
+
|
|
572
|
+
```
|
|
573
|
+
GET /Product/?rating=gt=3&sort(+name)
|
|
574
|
+
GET /Product/?sort(+rating,-price)
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
9. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relation`.
|
|
578
|
+
|
|
579
|
+
```
|
|
580
|
+
GET /Product/?brand.name=Microsoft
|
|
581
|
+
GET /Brand/?products.name=Keyboard
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
Use `select()` to include relationship attributes in the response (they are not included by default):
|
|
585
|
+
|
|
586
|
+
```
|
|
587
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name})
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
10. **Access a specific property by URL**: Append the property name with dot syntax to the record ID. Only works for properties declared in the schema.
|
|
591
|
+
```
|
|
592
|
+
GET /MyTable/123.propertyName
|
|
593
|
+
```
|
|
594
|
+
|
|
595
|
+
#### Examples
|
|
596
|
+
|
|
597
|
+
**Range filter with select and limit:**
|
|
598
|
+
|
|
599
|
+
```
|
|
600
|
+
GET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)&limit(20)
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
**Sort descending with multiple fields:**
|
|
262
604
|
|
|
263
|
-
|
|
605
|
+
```
|
|
606
|
+
GET /Product/?sort(+rating,-price)
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
**OR logic with grouping:**
|
|
610
|
+
|
|
611
|
+
```
|
|
612
|
+
GET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
**Relationship join with nested select:**
|
|
616
|
+
|
|
617
|
+
```
|
|
618
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name,id})
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
**Schema defining a relationship for join queries:**
|
|
622
|
+
|
|
623
|
+
```graphql
|
|
624
|
+
type Product @table @export {
|
|
625
|
+
id: Long @primaryKey
|
|
626
|
+
name: String
|
|
627
|
+
brandId: Long @indexed
|
|
628
|
+
brand: Brand @relation(from: "brandId")
|
|
629
|
+
}
|
|
630
|
+
type Brand @table @export {
|
|
631
|
+
id: Long @primaryKey
|
|
632
|
+
name: String
|
|
633
|
+
products: [Product] @relation(to: "brandId")
|
|
634
|
+
}
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
**Many-to-many relationship query:**
|
|
638
|
+
|
|
639
|
+
```graphql
|
|
640
|
+
type Product @table @export {
|
|
641
|
+
id: Long @primaryKey
|
|
642
|
+
name: String
|
|
643
|
+
resellerIds: [Long] @indexed
|
|
644
|
+
resellers: [Reseller] @relation(from: "resellerId")
|
|
645
|
+
}
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
```
|
|
649
|
+
GET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
**Type conversion with explicit prefix:**
|
|
653
|
+
|
|
654
|
+
```
|
|
655
|
+
GET /Product/?price==number:123
|
|
656
|
+
GET /Product/?active==boolean:true
|
|
657
|
+
GET /Product/?listDate==date:2024-01-05T20%3A07%3A27.955Z
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
#### Notes
|
|
661
|
+
|
|
662
|
+
- Only indexed attributes can be used as the primary filter; additional unindexed attributes can be combined with `&` once at least one indexed attribute is present.
|
|
663
|
+
- For null value queries, use `?attribute=null`. Indexes must have been created with null indexing support; existing indexes must be removed and re-added to support null queries.
|
|
664
|
+
- FIQL comparators (`==`, `!=`, `=gt=`, etc.) apply automatic type conversion based on value syntax or schema-declared type. Strict operators (`=`, `===`, `!==`) skip automatic type conversion.
|
|
665
|
+
- Filtering by a related attribute produces INNER JOIN behavior (only records with a matching related record are returned). Using `select()` on a relationship without a filter produces LEFT JOIN behavior.
|
|
666
|
+
- The array order of foreign key values in many-to-many relationships is preserved when resolving the relationship.
|
|
667
|
+
- See [automatic-apis.md](automatic-apis.md) for how Harper tables are automatically exposed as REST endpoints.
|
|
668
|
+
|
|
669
|
+
### 2.3 Real-Time Apps with WebSockets and Pub/Sub
|
|
670
|
+
|
|
671
|
+
Instructions for the agent to follow when building real-time features in Harper using WebSockets and Pub/Sub.
|
|
264
672
|
|
|
265
673
|
#### When to Use
|
|
266
674
|
|
|
267
|
-
|
|
675
|
+
Apply this rule when implementing any feature that requires real-time bidirectional communication, live data streaming, or push-based updates in a Harper application. This includes chat, live dashboards, sensor feeds, and any scenario where clients must receive resource changes as they happen.
|
|
268
676
|
|
|
269
677
|
#### How It Works
|
|
270
678
|
|
|
271
|
-
1. **WebSocket
|
|
272
|
-
|
|
273
|
-
|
|
679
|
+
1. **Enable WebSocket support**: WebSocket support is enabled automatically when the `rest` plugin is enabled. To explicitly disable it, set the following in your config:
|
|
680
|
+
|
|
681
|
+
```yaml
|
|
682
|
+
rest:
|
|
683
|
+
webSocket: false
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
2. **Connect a client to a resource**: A WebSocket connection to a resource URL automatically subscribes to that resource. When the record changes or a message is published to it, the connection receives the update.
|
|
687
|
+
|
|
688
|
+
```javascript
|
|
689
|
+
let ws = new WebSocket('wss://server/my-resource/341');
|
|
690
|
+
ws.onmessage = (event) => {
|
|
691
|
+
let data = JSON.parse(event.data);
|
|
692
|
+
};
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
`new WebSocket('wss://server/my-resource/341')` accesses the resource defined for `my-resource` with record id `341` and subscribes to it.
|
|
696
|
+
|
|
697
|
+
3. **Implement a custom `connect()` handler**: Override the `connect(incomingMessages)` method on a resource class to control WebSocket behavior. The method must return an async iterable (or generator) that produces messages to send to the client. See [automatic-apis.md](automatic-apis.md) for more on defining resource classes.
|
|
698
|
+
|
|
699
|
+
4. **Use the default `connect()` for event-style access**: Call `super.connect()` to get a streaming iterable that provides:
|
|
700
|
+
- A `send(message)` method for pushing outgoing messages
|
|
701
|
+
- A `close` event for cleanup on disconnect
|
|
702
|
+
|
|
703
|
+
5. **Handle message ordering in distributed environments**: Harper delivers messages to local subscribers immediately without inter-node coordination delay.
|
|
704
|
+
|
|
705
|
+
| Message Type | Behavior |
|
|
706
|
+
| -------------------------------------------------------- | ----------------------------------------------------------------------- |
|
|
707
|
+
| Non-retained (no `retain` flag) | Every message delivered in order received; suitable for chat |
|
|
708
|
+
| Retained (published with `retain`, or PUT/updated in DB) | Only the latest-timestamp message is kept; suitable for sensor readings |
|
|
709
|
+
|
|
710
|
+
6. **Use MQTT over WebSockets** when needed by setting the sub-protocol header:
|
|
711
|
+
```
|
|
712
|
+
Sec-WebSocket-Protocol: mqtt
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
#### Examples
|
|
716
|
+
|
|
717
|
+
**Simple echo server** — override `connect(incomingMessages)` to yield each incoming message back to the client:
|
|
718
|
+
|
|
719
|
+
```javascript
|
|
720
|
+
export class Echo extends Resource {
|
|
721
|
+
async *connect(incomingMessages) {
|
|
722
|
+
for await (let message of incomingMessages) {
|
|
723
|
+
yield message; // echo each message back
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
**Custom connect with timer and event-style access** — use `super.connect()` to get the outgoing stream, push periodic messages, echo incoming messages, and clean up on disconnect:
|
|
730
|
+
|
|
731
|
+
```javascript
|
|
732
|
+
export class Example extends Resource {
|
|
733
|
+
connect(incomingMessages) {
|
|
734
|
+
let outgoingMessages = super.connect();
|
|
735
|
+
|
|
736
|
+
let timer = setInterval(() => {
|
|
737
|
+
outgoingMessages.send({ greeting: 'hi again!' });
|
|
738
|
+
}, 1000);
|
|
739
|
+
|
|
740
|
+
incomingMessages.on('data', (message) => {
|
|
741
|
+
outgoingMessages.send(message); // echo incoming messages
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
outgoingMessages.on('close', () => {
|
|
745
|
+
clearInterval(timer);
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
return outgoingMessages;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
#### Notes
|
|
754
|
+
|
|
755
|
+
- WebSocket connections target a resource URL path. By default, connecting to a resource subscribes to changes for that resource.
|
|
756
|
+
- The `connect(incomingMessages)` method **must** return an async iterable or generator; returning a plain value will not work.
|
|
757
|
+
- `super.connect()` returns a streaming iterable with `send(message)` and a `close` event — use this when you need to push messages outside of the incoming message loop.
|
|
758
|
+
- For one-way real-time streaming without bidirectional communication, consider Server-Sent Events instead.
|
|
759
|
+
- For full pub/sub capabilities, Harper also supports MQTT; set `Sec-WebSocket-Protocol: mqtt` to use MQTT over WebSockets.
|
|
274
760
|
|
|
275
761
|
### 2.4 Checking Authentication
|
|
276
762
|
|
|
277
|
-
|
|
763
|
+
Instructions for the agent to follow when handling user authentication and session management inside Harper Resources.
|
|
278
764
|
|
|
279
765
|
#### When to Use
|
|
280
766
|
|
|
281
|
-
|
|
767
|
+
Apply this rule when implementing authentication checks, login/logout flows, or token issuance inside a custom Resource. Use it any time a Resource needs to identify the current user, establish a session, or issue JWTs to clients. See [custom-resources.md](custom-resources.md) for the general Resource authoring pattern.
|
|
282
768
|
|
|
283
769
|
#### How It Works
|
|
284
770
|
|
|
285
|
-
1. **
|
|
286
|
-
2. **Identity Verification**: Check for the presence of a user ID or token.
|
|
287
|
-
3. **Role Checks**: Verify if the user has the required roles for the action.
|
|
771
|
+
1. **Check the current user** with `getCurrentUser()`. Call it inside any Resource method to retrieve the authenticated user or `undefined` if no user is authenticated. Guard protected endpoints by returning a `401` when the result is `undefined`.
|
|
288
772
|
|
|
289
|
-
|
|
773
|
+
```javascript
|
|
774
|
+
async get(target) {
|
|
775
|
+
const user = this.getCurrentUser();
|
|
776
|
+
if (!user) return new Response(null, { status: 401 });
|
|
777
|
+
return { username: user.username, role: user.role };
|
|
778
|
+
}
|
|
779
|
+
```
|
|
290
780
|
|
|
291
|
-
|
|
781
|
+
The returned object exposes `username`, `role`, and `role.permission` flags.
|
|
782
|
+
|
|
783
|
+
2. **Enable sessions** before using session-based login. Set `authentication.enableSessions: true` in `harperdb-config.yaml`:
|
|
292
784
|
|
|
293
|
-
|
|
785
|
+
```yaml
|
|
786
|
+
authentication:
|
|
787
|
+
enableSessions: true
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
3. **Access login and session helpers** via `getContext()`. The context object exposes `context.login` and `context.session` for sign-in/out flows.
|
|
791
|
+
- Call `context.login(username, password)` to verify credentials and establish a session cookie on success.
|
|
792
|
+
- To end a session, delete it via `context.session.delete(context.session.id)`.
|
|
793
|
+
|
|
794
|
+
4. **Implement sign-in and sign-out Resources** using the context helpers:
|
|
795
|
+
|
|
796
|
+
```javascript
|
|
797
|
+
export class SignIn extends Resource {
|
|
798
|
+
async post(_target, data) {
|
|
799
|
+
const context = this.getContext();
|
|
800
|
+
try {
|
|
801
|
+
await context.login(data.username, data.password);
|
|
802
|
+
} catch {
|
|
803
|
+
return new Response('Invalid credentials', { status: 403 });
|
|
804
|
+
}
|
|
805
|
+
return new Response('Logged in', { status: 200 });
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
export class SignOut extends Resource {
|
|
810
|
+
async post() {
|
|
811
|
+
const context = this.getContext();
|
|
812
|
+
if (!context.session) return new Response(null, { status: 401 });
|
|
813
|
+
await context.session.delete(context.session.id);
|
|
814
|
+
return new Response('Logged out', { status: 200 });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
5. **Issue JWTs for non-browser clients** (CLI tools, mobile apps, service-to-service). Cookie-based sessions are intended for browser clients. For other clients, mint tokens programmatically using `server.operation()`:
|
|
820
|
+
|
|
821
|
+
```javascript
|
|
822
|
+
import { Resource, server } from 'harper';
|
|
823
|
+
|
|
824
|
+
export class IssueTokens extends Resource {
|
|
825
|
+
static async get(_target, context) {
|
|
826
|
+
const { operation_token, refresh_token } = await server.operation(
|
|
827
|
+
{ operation: 'create_authentication_tokens' },
|
|
828
|
+
context,
|
|
829
|
+
true,
|
|
830
|
+
);
|
|
831
|
+
return { operation_token, refresh_token };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
static async post(_target, data) {
|
|
835
|
+
const { username, password } = await data;
|
|
836
|
+
if (!username || !password) {
|
|
837
|
+
return new Response('username and password required', { status: 400 });
|
|
838
|
+
}
|
|
839
|
+
const { operation_token, refresh_token } = await server.operation({
|
|
840
|
+
operation: 'create_authentication_tokens',
|
|
841
|
+
username,
|
|
842
|
+
password,
|
|
843
|
+
});
|
|
844
|
+
return { operation_token, refresh_token };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
export class RefreshJWT extends Resource {
|
|
849
|
+
static async post(_target, data) {
|
|
850
|
+
const { refresh_token } = await data;
|
|
851
|
+
if (!refresh_token) {
|
|
852
|
+
return new Response('refresh_token required', { status: 400 });
|
|
853
|
+
}
|
|
854
|
+
const { operation_token } = await server.operation({
|
|
855
|
+
operation: 'refresh_operation_token',
|
|
856
|
+
refresh_token,
|
|
857
|
+
});
|
|
858
|
+
return { operation_token };
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
Pass `true` as the third argument to `server.operation()` when the operation should run as the current authenticated user. Omit it or pass `false` when the operation supplies its own credentials.
|
|
864
|
+
|
|
865
|
+
6. **Configure JWT token expiry** in `harperdb-config.yaml` under the `authentication` section:
|
|
866
|
+
|
|
867
|
+
```yaml
|
|
868
|
+
authentication:
|
|
869
|
+
operationTokenTimeout: 1d
|
|
870
|
+
refreshTokenTimeout: 30d
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
Duration strings follow the `jsonwebtoken` package format (e.g., `1d`, `12h`, `60m`).
|
|
874
|
+
|
|
875
|
+
#### Examples
|
|
876
|
+
|
|
877
|
+
**Protecting a resource endpoint and returning user info:**
|
|
878
|
+
|
|
879
|
+
```javascript
|
|
880
|
+
async get(target) {
|
|
881
|
+
const user = this.getCurrentUser();
|
|
882
|
+
if (!user) return new Response(null, { status: 401 });
|
|
883
|
+
return { username: user.username, role: user.role };
|
|
884
|
+
}
|
|
885
|
+
```
|
|
886
|
+
|
|
887
|
+
**Full session-based sign-in/sign-out flow:**
|
|
888
|
+
|
|
889
|
+
```javascript
|
|
890
|
+
export class SignIn extends Resource {
|
|
891
|
+
async post(_target, data) {
|
|
892
|
+
const context = this.getContext();
|
|
893
|
+
try {
|
|
894
|
+
await context.login(data.username, data.password);
|
|
895
|
+
} catch {
|
|
896
|
+
return new Response('Invalid credentials', { status: 403 });
|
|
897
|
+
}
|
|
898
|
+
return new Response('Logged in', { status: 200 });
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export class SignOut extends Resource {
|
|
903
|
+
async post() {
|
|
904
|
+
const context = this.getContext();
|
|
905
|
+
if (!context.session) return new Response(null, { status: 401 });
|
|
906
|
+
await context.session.delete(context.session.id);
|
|
907
|
+
return new Response('Logged out', { status: 200 });
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
**JWT token refresh endpoint:**
|
|
913
|
+
|
|
914
|
+
```javascript
|
|
915
|
+
export class RefreshJWT extends Resource {
|
|
916
|
+
static async post(_target, data) {
|
|
917
|
+
const { refresh_token } = await data;
|
|
918
|
+
if (!refresh_token) {
|
|
919
|
+
return new Response('refresh_token required', { status: 400 });
|
|
920
|
+
}
|
|
921
|
+
const { operation_token } = await server.operation({
|
|
922
|
+
operation: 'refresh_operation_token',
|
|
923
|
+
refresh_token,
|
|
924
|
+
});
|
|
925
|
+
return { operation_token };
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
#### Notes
|
|
931
|
+
|
|
932
|
+
- `getCurrentUser()` and `getContext()` are instance methods; call them with `this` inside non-static Resource methods.
|
|
933
|
+
- `enableSessions` must be `true` in config before `context.login` or `context.session` will function.
|
|
934
|
+
- Cookie-based sessions target browser clients. Use JWT issuance via `server.operation()` for all other client types.
|
|
935
|
+
- When both `operation_token` and `refresh_token` have expired, the client must call `create_authentication_tokens` again with credentials.
|
|
936
|
+
|
|
937
|
+
## 3. Logic & Extension
|
|
294
938
|
|
|
295
939
|
### 3.1 Custom Resources
|
|
296
940
|
|
|
297
|
-
|
|
941
|
+
Instructions for the agent to follow when creating custom resources in Harper.
|
|
942
|
+
|
|
943
|
+
#### When to Use
|
|
944
|
+
|
|
945
|
+
Use this skill when the automatic CRUD operations provided by `@table @export` are insufficient, and you need custom logic, third-party API integration, or specialized data handling for your REST endpoints.
|
|
298
946
|
|
|
299
947
|
#### How It Works
|
|
300
948
|
|
|
301
|
-
1. **
|
|
302
|
-
2. **
|
|
303
|
-
3. **
|
|
304
|
-
|
|
949
|
+
1. **Check if a Custom Resource is Necessary**: Verify if [Automatic APIs](./automatic-apis.md) or [Extending Tables](./extending-tables.md) can satisfy the requirement first.
|
|
950
|
+
2. **Create the Resource File**: Create a `.ts` or `.js` file in the directory specified by `jsResource` in `config.yaml` (typically `resources/`).
|
|
951
|
+
3. **Define the Resource Class**: Export a class extending `Resource` from `harper`:
|
|
952
|
+
|
|
953
|
+
```typescript
|
|
954
|
+
import { type RequestTargetOrId, Resource } from 'harper';
|
|
955
|
+
|
|
956
|
+
export class MyResource extends Resource {
|
|
957
|
+
async get(target?: RequestTargetOrId) {
|
|
958
|
+
return { message: 'Hello from custom GET!' };
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
```
|
|
962
|
+
|
|
963
|
+
4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests.
|
|
964
|
+
5. **Route Nesting and Naming**: You can control the URL structure by how you export your resources:
|
|
305
965
|
- **Direct Class Export**: `export class Foo extends Resource` creates endpoints at `/Foo/`. Class names are case-sensitive in the URL.
|
|
306
966
|
- **Nested Objects**: `export const Bar = { Foo };` creates endpoints at `/Bar/Foo/`.
|
|
307
967
|
- **Lowercase and Hyphens**: Use object keys to define custom paths: `export const bar = { 'foo-baz': Foo };` exposes endpoints at `/bar/foo-baz/`.
|
|
308
|
-
|
|
968
|
+
6. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:
|
|
969
|
+
```typescript
|
|
970
|
+
import { tables } from 'harper';
|
|
971
|
+
// ... inside a method
|
|
972
|
+
const results = await tables.MyTable.list();
|
|
973
|
+
```
|
|
974
|
+
7. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).
|
|
309
975
|
|
|
310
|
-
### 3.2 Extending
|
|
976
|
+
### 3.2 Extending Tables
|
|
311
977
|
|
|
312
|
-
|
|
978
|
+
Instructions for the agent to follow when extending table resources in Harper.
|
|
979
|
+
|
|
980
|
+
#### When to Use
|
|
981
|
+
|
|
982
|
+
Use 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.
|
|
313
983
|
|
|
314
984
|
#### How It Works
|
|
315
985
|
|
|
316
|
-
1. **Define
|
|
317
|
-
|
|
318
|
-
|
|
986
|
+
1. **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.
|
|
987
|
+
```graphql
|
|
988
|
+
type MyTable @table {
|
|
989
|
+
id: ID @primaryKey
|
|
990
|
+
name: String
|
|
991
|
+
}
|
|
992
|
+
```
|
|
993
|
+
2. **Create the Extension File**: Create a `.ts` file in your `resources/` directory.
|
|
994
|
+
3. **Extend the Table Resource**: Export a class that extends `tables.YourTableName`:
|
|
995
|
+
|
|
996
|
+
```typescript
|
|
997
|
+
import { type RequestTargetOrId, tables } from 'harper';
|
|
998
|
+
|
|
999
|
+
export class MyTable extends tables.MyTable {
|
|
1000
|
+
async post(target: RequestTargetOrId, record: any) {
|
|
1001
|
+
// Custom logic here
|
|
1002
|
+
if (!record.name) {
|
|
1003
|
+
throw new Error('Name required');
|
|
1004
|
+
}
|
|
1005
|
+
return super.post(target, record);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
```
|
|
1009
|
+
|
|
1010
|
+
4. **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.
|
|
1011
|
+
5. **Implement Logic**: Use overrides for validation, side effects, or transforming data before/after database operations.
|
|
319
1012
|
|
|
320
1013
|
### 3.3 Programmatic Table Requests
|
|
321
1014
|
|
|
322
|
-
|
|
1015
|
+
Instructions for the agent to follow when interacting with Harper tables via code.
|
|
1016
|
+
|
|
1017
|
+
#### When to Use
|
|
1018
|
+
|
|
1019
|
+
Use this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.
|
|
1020
|
+
|
|
1021
|
+
#### How It Works
|
|
1022
|
+
|
|
1023
|
+
1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).
|
|
1024
|
+
2. **Perform CRUD Operations**:
|
|
1025
|
+
- **Get**: `await tables.MyTable.get(id)` for a single record or `await tables.MyTable.get({ conditions: [...] })` for multiple.
|
|
1026
|
+
- **Create**: `await tables.MyTable.post(record)` (auto-generates ID) or `await tables.MyTable.put(id, record)`.
|
|
1027
|
+
- **Update**: `await tables.MyTable.patch(id, partialRecord)` for partial updates.
|
|
1028
|
+
- **Delete**: `await tables.MyTable.delete(id)`.
|
|
1029
|
+
3. **Use Updatable Records for Atomic Ops**: Call `update(id)` to get a reference, then use `addTo` or `subtractFrom` for atomic increments/decrements:
|
|
1030
|
+
```typescript
|
|
1031
|
+
const stats = await tables.Stats.update('daily');
|
|
1032
|
+
stats.addTo('viewCount', 1);
|
|
1033
|
+
```
|
|
1034
|
+
4. **Search and Stream**: Use `search(query)` for efficient streaming of large result sets:
|
|
1035
|
+
```typescript
|
|
1036
|
+
for await (const record of tables.MyTable.search({ conditions: [...] })) {
|
|
1037
|
+
// process record
|
|
1038
|
+
}
|
|
1039
|
+
```
|
|
1040
|
+
See the [Query Conditions](#query-conditions) section below for the full query object reference.
|
|
1041
|
+
5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:
|
|
1042
|
+
```typescript
|
|
1043
|
+
for await (const event of tables.MyTable.subscribe(query)) {
|
|
1044
|
+
// handle event
|
|
1045
|
+
}
|
|
1046
|
+
```
|
|
1047
|
+
6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.
|
|
1048
|
+
|
|
1049
|
+
#### Query Conditions
|
|
1050
|
+
|
|
1051
|
+
When passing a query to `search()`, `get()`, or `subscribe()`, use a query object with a `conditions` array.
|
|
1052
|
+
|
|
1053
|
+
##### Condition Object Shape
|
|
1054
|
+
|
|
1055
|
+
| Property | Description |
|
|
1056
|
+
| ------------ | ------------------------------------------------------------------------------------------ |
|
|
1057
|
+
| `attribute` | Field name, or array of field names to traverse a relationship (e.g., `['brand', 'name']`) |
|
|
1058
|
+
| `value` | The value to compare against |
|
|
1059
|
+
| `comparator` | One of the comparator strings below (default: `equals`) |
|
|
1060
|
+
| `operator` | `and` (default) or `or` — applies to a nested `conditions` block |
|
|
1061
|
+
| `conditions` | Nested array of condition objects for complex AND/OR logic |
|
|
1062
|
+
|
|
1063
|
+
##### Comparator Values
|
|
1064
|
+
|
|
1065
|
+
Use these exact strings — incorrect comparator names will silently fail or error:
|
|
1066
|
+
|
|
1067
|
+
| Comparator | Meaning |
|
|
1068
|
+
| -------------------- | ---------------------------------------------------------- |
|
|
1069
|
+
| `equals` | Exact match (default) |
|
|
1070
|
+
| `not_equal` | Not equal |
|
|
1071
|
+
| `greater_than` | `>` |
|
|
1072
|
+
| `greater_than_equal` | `>=` |
|
|
1073
|
+
| `less_than` | `<` |
|
|
1074
|
+
| `less_than_equal` | `<=` |
|
|
1075
|
+
| `starts_with` | String starts with value |
|
|
1076
|
+
| `contains` | String contains value |
|
|
1077
|
+
| `ends_with` | String ends with value |
|
|
1078
|
+
| `between` | Value is between two bounds (pass `value` as `[min, max]`) |
|
|
1079
|
+
|
|
1080
|
+
##### Query Object Parameters
|
|
1081
|
+
|
|
1082
|
+
| Property | Description |
|
|
1083
|
+
| ------------ | ------------------------------------------------------------------------------------ |
|
|
1084
|
+
| `conditions` | Array of condition objects |
|
|
1085
|
+
| `limit` | Maximum number of records to return |
|
|
1086
|
+
| `offset` | Number of records to skip (for pagination) |
|
|
1087
|
+
| `select` | Array of attribute names to return; supports `$id` and `$updatedtime` |
|
|
1088
|
+
| `sort` | Object with `attribute`, `descending` (bool), and optional `next` for secondary sort |
|
|
1089
|
+
|
|
1090
|
+
##### Examples
|
|
1091
|
+
|
|
1092
|
+
**Simple filter:**
|
|
1093
|
+
|
|
1094
|
+
```javascript
|
|
1095
|
+
for await (const record of tables.Product.search({
|
|
1096
|
+
conditions: [{ attribute: 'price', comparator: 'less_than', value: 100 }],
|
|
1097
|
+
limit: 20,
|
|
1098
|
+
})) { ... }
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
**AND + nested OR:**
|
|
1102
|
+
|
|
1103
|
+
```javascript
|
|
1104
|
+
for await (const record of tables.Product.search({
|
|
1105
|
+
conditions: [
|
|
1106
|
+
{ attribute: 'price', comparator: 'less_than', value: 100 },
|
|
1107
|
+
{
|
|
1108
|
+
operator: 'or',
|
|
1109
|
+
conditions: [
|
|
1110
|
+
{ attribute: 'rating', comparator: 'greater_than', value: 4 },
|
|
1111
|
+
{ attribute: 'featured', value: true },
|
|
1112
|
+
],
|
|
1113
|
+
},
|
|
1114
|
+
],
|
|
1115
|
+
})) { ... }
|
|
1116
|
+
```
|
|
1117
|
+
|
|
1118
|
+
**Relationship traversal:**
|
|
323
1119
|
|
|
324
|
-
|
|
1120
|
+
```javascript
|
|
1121
|
+
for await (const record of tables.Book.search({
|
|
1122
|
+
conditions: [{ attribute: ['brand', 'name'], comparator: 'equals', value: 'Harper' }],
|
|
1123
|
+
})) { ... }
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
**Sort and paginate:**
|
|
1127
|
+
|
|
1128
|
+
```javascript
|
|
1129
|
+
for await (const record of tables.Product.search({
|
|
1130
|
+
conditions: [{ attribute: 'inStock', value: true }],
|
|
1131
|
+
sort: { attribute: 'price', descending: false },
|
|
1132
|
+
limit: 10,
|
|
1133
|
+
offset: 20,
|
|
1134
|
+
})) { ... }
|
|
1135
|
+
```
|
|
325
1136
|
|
|
326
|
-
|
|
1137
|
+
#### Cautions
|
|
1138
|
+
|
|
1139
|
+
Be 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.
|
|
327
1140
|
|
|
328
1141
|
### 3.4 TypeScript Type Stripping
|
|
329
1142
|
|
|
330
|
-
|
|
1143
|
+
Instructions for the agent to follow when using TypeScript in Harper.
|
|
331
1144
|
|
|
332
|
-
####
|
|
1145
|
+
#### When to Use
|
|
333
1146
|
|
|
334
|
-
|
|
1147
|
+
Use this skill when you want to write Harper Resources in TypeScript and have them execute directly in Node.js without an intermediate build or compilation step.
|
|
335
1148
|
|
|
336
|
-
|
|
1149
|
+
#### How It Works
|
|
337
1150
|
|
|
338
|
-
|
|
1151
|
+
1. **Verify Node.js Version**: Ensure you are using Node.js v22.6.0 or higher.
|
|
1152
|
+
2. **Name Files with `.ts`**: Create your resource files in the `resources/` directory with a `.ts` extension.
|
|
1153
|
+
3. **Use TypeScript Syntax**: Write your resource classes using standard TypeScript (interfaces, types, etc.).
|
|
1154
|
+
```typescript
|
|
1155
|
+
import { Resource } from 'harper';
|
|
1156
|
+
export class MyResource extends Resource {
|
|
1157
|
+
async get(): Promise<{ message: string }> {
|
|
1158
|
+
return { message: 'Running TS directly!' };
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
```
|
|
1162
|
+
4. **Use Explicit Extensions in Imports**: When importing other local modules, include the `.ts` extension: `import { helper } from './helper.ts'`.
|
|
1163
|
+
5. **Configure `config.yaml`**: Ensure `jsResource` points to your `.ts` files:
|
|
1164
|
+
```yaml
|
|
1165
|
+
jsResource:
|
|
1166
|
+
files: 'resources/*.ts'
|
|
1167
|
+
```
|
|
339
1168
|
|
|
340
|
-
|
|
1169
|
+
### 3.5 Caching External Data Sources in Harper
|
|
341
1170
|
|
|
342
|
-
|
|
343
|
-
- **Distributed**: For scaling across multiple nodes in Harper Fabric.
|
|
1171
|
+
Instructions for the agent to implement integrated data caching in Harper by wrapping external sources with a cache table and `sourcedFrom`.
|
|
344
1172
|
|
|
345
|
-
|
|
1173
|
+
#### When to Use
|
|
346
1174
|
|
|
347
|
-
|
|
1175
|
+
Apply this rule when a Harper application needs to cache responses from an external API, microservice, or database to avoid repeated slow or expensive upstream calls. Use it whenever you need to define TTL-based cache expiration, observe ETag-based conditional responses, or manually invalidate cached entries.
|
|
348
1176
|
|
|
349
|
-
|
|
1177
|
+
#### How It Works
|
|
350
1178
|
|
|
351
|
-
|
|
1179
|
+
1. **Define a cache table with `expiration`**: In `schema.graphql`, add the `expiration` argument to `@table`. The value is in seconds. Any record older than this threshold is considered stale and will be re-fetched on next access.
|
|
352
1180
|
|
|
353
|
-
|
|
1181
|
+
```graphql
|
|
1182
|
+
type JokeCache @table(expiration: 60) @export {
|
|
1183
|
+
id: ID @primaryKey
|
|
1184
|
+
setup: String
|
|
1185
|
+
punchline: String
|
|
1186
|
+
}
|
|
1187
|
+
```
|
|
1188
|
+
|
|
1189
|
+
2. **Wrap the external source in `resources.js`**: Create an object with a `get(id)` method that fetches from the upstream source. Then call `sourcedFrom` on the table to register it.
|
|
1190
|
+
|
|
1191
|
+
```javascript
|
|
1192
|
+
const jokeAPI = {
|
|
1193
|
+
async get(id) {
|
|
1194
|
+
const response = await fetch(`https://official-joke-api.appspot.com/jokes/${id}`);
|
|
1195
|
+
return response.json();
|
|
1196
|
+
},
|
|
1197
|
+
};
|
|
1198
|
+
|
|
1199
|
+
tables.JokeCache.sourcedFrom(jokeAPI);
|
|
1200
|
+
```
|
|
1201
|
+
|
|
1202
|
+
Harper's caching behavior after `sourcedFrom` is registered:
|
|
1203
|
+
- A request arrives for `/JokeCache/1`.
|
|
1204
|
+
- Harper checks if the record with id `1` exists in `JokeCache` and is not stale.
|
|
1205
|
+
- If fresh, Harper returns it immediately.
|
|
1206
|
+
- If missing or stale, Harper calls `jokeAPI.get()`, stores the result in `JokeCache`, and returns it.
|
|
1207
|
+
- Multiple simultaneous requests for the same missing or stale record wait on a single upstream call — Harper prevents cache stampedes automatically.
|
|
1208
|
+
|
|
1209
|
+
3. **Configure plugins in `config.yaml`**: Enable the schema, REST API, and JS resource plugins.
|
|
1210
|
+
|
|
1211
|
+
```yaml
|
|
1212
|
+
graphqlSchema:
|
|
1213
|
+
files: 'schema.graphql'
|
|
1214
|
+
rest: true
|
|
1215
|
+
jsResource:
|
|
1216
|
+
files: 'resources.js'
|
|
1217
|
+
```
|
|
1218
|
+
|
|
1219
|
+
4. **Observe caching via ETags**: Harper automatically computes an ETag from the record's last-modified timestamp. On the first request you receive a `200` with an `etag` header. Pass that value back in `If-None-Match` on subsequent requests; Harper returns `304 Not Modified` with an empty body if the record is unchanged.
|
|
1220
|
+
|
|
1221
|
+
```bash
|
|
1222
|
+
curl -i 'http://localhost:9926/JokeCache/1' \
|
|
1223
|
+
-H 'If-None-Match: "abCDefGHij"'
|
|
1224
|
+
```
|
|
1225
|
+
|
|
1226
|
+
5. **Force a cache bypass**: Send `Cache-Control: no-cache` to make Harper skip the local cache and always call the upstream source, regardless of TTL.
|
|
1227
|
+
|
|
1228
|
+
```bash
|
|
1229
|
+
curl -i 'http://localhost:9926/JokeCache/1' \
|
|
1230
|
+
-H 'Cache-Control: no-cache'
|
|
1231
|
+
```
|
|
1232
|
+
|
|
1233
|
+
6. **Invalidate a cache entry on demand**: Remove `@export` from the schema type, then export a class of the same name in `resources.js` that extends the table and implements a `post` handler calling `this.invalidate(target)`.
|
|
1234
|
+
|
|
1235
|
+
```graphql
|
|
1236
|
+
type JokeCache @table(expiration: 60) {
|
|
1237
|
+
id: ID @primaryKey
|
|
1238
|
+
setup: String
|
|
1239
|
+
punchline: String
|
|
1240
|
+
}
|
|
1241
|
+
```
|
|
1242
|
+
|
|
1243
|
+
```javascript
|
|
1244
|
+
export class JokeCache extends tables.JokeCache {
|
|
1245
|
+
static async post(target, data) {
|
|
1246
|
+
const body = await data;
|
|
1247
|
+
if (body?.action === 'invalidate') {
|
|
1248
|
+
this.invalidate(target);
|
|
1249
|
+
return { status: 200, data: { message: 'invalidated' } };
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
```
|
|
1254
|
+
|
|
1255
|
+
Trigger invalidation with a `POST`:
|
|
1256
|
+
|
|
1257
|
+
```bash
|
|
1258
|
+
curl -X POST 'http://localhost:9926/JokeCache/1' \
|
|
1259
|
+
-H 'Content-Type: application/json' \
|
|
1260
|
+
-d '{"action": "invalidate"}'
|
|
1261
|
+
```
|
|
1262
|
+
|
|
1263
|
+
The next `GET /JokeCache/1` will fetch fresh data from the upstream source regardless of TTL.
|
|
1264
|
+
|
|
1265
|
+
#### Examples
|
|
1266
|
+
|
|
1267
|
+
Complete `schema.graphql` and `resources.js` for a cached external API with on-demand invalidation:
|
|
1268
|
+
|
|
1269
|
+
```graphql
|
|
1270
|
+
type JokeCache @table(expiration: 60) {
|
|
1271
|
+
id: ID @primaryKey
|
|
1272
|
+
setup: String
|
|
1273
|
+
punchline: String
|
|
1274
|
+
}
|
|
1275
|
+
```
|
|
1276
|
+
|
|
1277
|
+
```javascript
|
|
1278
|
+
// resources.js
|
|
1279
|
+
|
|
1280
|
+
const jokeAPI = {
|
|
1281
|
+
async get() {
|
|
1282
|
+
const id = this.getId();
|
|
1283
|
+
const response = await fetch(`https://official-joke-api.appspot.com/jokes/${id}`);
|
|
1284
|
+
return response.json();
|
|
1285
|
+
},
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
tables.JokeCache.sourcedFrom(jokeAPI);
|
|
1289
|
+
|
|
1290
|
+
export class JokeCache extends tables.JokeCache {
|
|
1291
|
+
static async post(target, data) {
|
|
1292
|
+
const body = await data;
|
|
1293
|
+
if (body?.action === 'invalidate') {
|
|
1294
|
+
this.invalidate(target);
|
|
1295
|
+
return { status: 200, data: { message: 'invalidated' } };
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
```
|
|
1300
|
+
|
|
1301
|
+
First request — cache miss, upstream is called, `200` returned:
|
|
1302
|
+
|
|
1303
|
+
```bash
|
|
1304
|
+
curl -i 'http://localhost:9926/JokeCache/1'
|
|
1305
|
+
```
|
|
1306
|
+
|
|
1307
|
+
Second request with ETag — cache hit, `304 Not Modified`:
|
|
1308
|
+
|
|
1309
|
+
```bash
|
|
1310
|
+
curl -i 'http://localhost:9926/JokeCache/1' \
|
|
1311
|
+
-H 'If-None-Match: "abCDefGHij"'
|
|
1312
|
+
```
|
|
1313
|
+
|
|
1314
|
+
#### Notes
|
|
1315
|
+
|
|
1316
|
+
- `expiration` is measured in seconds. Harper also supports separate `eviction` and `scanInterval` arguments on `@table` for fine-grained control over physical record removal.
|
|
1317
|
+
- The `@export` directive on the schema type is not required when you export a Resource class of the same name from `resources.js` — the class export serves as the endpoint registration. See [custom-resources.md](custom-resources.md) for details on building Resource classes.
|
|
1318
|
+
- Harper's REST layer automatically exposes `@export`-ed tables and Resource classes as HTTP endpoints. See [automatic-apis.md](automatic-apis.md) for how endpoints are structured and named.
|
|
1319
|
+
- ETag values include their double quotes as part of the value — include them verbatim when passing the value in `If-None-Match`.
|
|
1320
|
+
- `sourcedFrom` must be called after the table reference (`tables.JokeCache`) is available, which is guaranteed when the call is at the top level of `resources.js`.
|
|
1321
|
+
|
|
1322
|
+
## 4. Infrastructure & Ops
|
|
1323
|
+
|
|
1324
|
+
### 4.1 Deploying to Harper Fabric
|
|
1325
|
+
|
|
1326
|
+
Instructions for the agent to follow when deploying a Harper application to the Harper Fabric cloud using the Harper CLI.
|
|
354
1327
|
|
|
355
1328
|
#### When to Use
|
|
356
1329
|
|
|
357
|
-
|
|
1330
|
+
Apply this rule when deploying a Harper application to a remote Harper instance or Harper Fabric cluster. This covers interactive deployments, CI/CD pipelines, and any scenario where the agent must push a local or remote package to a target environment.
|
|
358
1331
|
|
|
359
|
-
####
|
|
1332
|
+
#### How It Works
|
|
360
1333
|
|
|
361
|
-
|
|
1334
|
+
1. **Authenticate with the remote target**: Run `harper login` once to store an authentication token. The CLI writes `HARPER_CLI_TARGET` to a local `.env` so subsequent commands do not need credentials repeated. Find the **Application URL** on the cluster's **Config → Overview** page (see [creating-a-fabric-account-and-cluster.md](creating-a-fabric-account-and-cluster.md)).
|
|
1335
|
+
|
|
1336
|
+
```bash
|
|
1337
|
+
harper login <Application URL>
|
|
1338
|
+
# Provide cluster username and password when prompted
|
|
1339
|
+
```
|
|
1340
|
+
|
|
1341
|
+
2. **Deploy the application**: Run `harper deploy` with the required parameters. After logging in, no credentials are needed inline.
|
|
1342
|
+
|
|
1343
|
+
```bash
|
|
1344
|
+
harper deploy \
|
|
1345
|
+
project=<name> \
|
|
1346
|
+
package=<package> \
|
|
1347
|
+
target=<remote> \
|
|
1348
|
+
restart=true \
|
|
1349
|
+
replicated=true
|
|
1350
|
+
```
|
|
1351
|
+
|
|
1352
|
+
3. **Choose a package source**: Set the `package` parameter to any valid npm dependency value, or omit it to package and deploy the current local directory.
|
|
1353
|
+
|
|
1354
|
+
| Value | Effect |
|
|
1355
|
+
| ---------------------------------------------------- | ------------------------------------------------ |
|
|
1356
|
+
| _(omitted)_ | Packages and deploys the current local directory |
|
|
1357
|
+
| `"@harperdb/status-check"` | npm package |
|
|
1358
|
+
| `"HarperDB/status-check"` | GitHub repo (short form) |
|
|
1359
|
+
| `"https://github.com/HarperDB/status-check"` | GitHub repo (full URL) |
|
|
1360
|
+
| `"git+ssh://git@github.com:HarperDB/secret-app.git"` | Private repo via SSH |
|
|
1361
|
+
| `"https://example.com/application.tar.gz"` | Remote tarball |
|
|
1362
|
+
|
|
1363
|
+
For git tags, use the `semver` directive for reliable versioning:
|
|
1364
|
+
|
|
1365
|
+
```
|
|
1366
|
+
HarperDB/application-template#semver:v1.0.0
|
|
1367
|
+
```
|
|
362
1368
|
|
|
363
|
-
**
|
|
1369
|
+
4. **Authenticate for CI/CD pipelines**: Use environment variables instead of interactive login. Set credentials before running `harper deploy`.
|
|
1370
|
+
|
|
1371
|
+
```bash
|
|
1372
|
+
export HARPER_CLI_USERNAME=<username>
|
|
1373
|
+
export HARPER_CLI_PASSWORD=<password>
|
|
1374
|
+
harper deploy \
|
|
1375
|
+
project=<name> \
|
|
1376
|
+
package=<package> \
|
|
1377
|
+
target=<remote> \
|
|
1378
|
+
restart=true \
|
|
1379
|
+
replicated=true
|
|
1380
|
+
```
|
|
1381
|
+
|
|
1382
|
+
5. **Register SSH keys for private repos**: Before deploying from an SSH-based private repository, use the Add SSH Key operation to register the key with the remote instance.
|
|
1383
|
+
|
|
1384
|
+
#### Examples
|
|
1385
|
+
|
|
1386
|
+
**Interactive login then deploy (recommended):**
|
|
364
1387
|
|
|
365
1388
|
```bash
|
|
366
|
-
|
|
1389
|
+
# Log in once
|
|
1390
|
+
harper login <remote>
|
|
1391
|
+
# Provide your username and password when prompted
|
|
1392
|
+
|
|
1393
|
+
# Subsequently deploy without credentials
|
|
1394
|
+
harper deploy \
|
|
1395
|
+
project=<name> \
|
|
1396
|
+
package=<package> \
|
|
1397
|
+
target=<remote> \
|
|
1398
|
+
restart=true \
|
|
1399
|
+
replicated=true
|
|
367
1400
|
```
|
|
368
1401
|
|
|
369
|
-
**
|
|
1402
|
+
**Deploy with inline credentials (not recommended for production):**
|
|
370
1403
|
|
|
371
1404
|
```bash
|
|
372
|
-
|
|
1405
|
+
harper deploy \
|
|
1406
|
+
project=<name> \
|
|
1407
|
+
package=<package> \
|
|
1408
|
+
username=<username> \
|
|
1409
|
+
password=<password> \
|
|
1410
|
+
target=<remote> \
|
|
1411
|
+
restart=true \
|
|
1412
|
+
replicated=true
|
|
373
1413
|
```
|
|
374
1414
|
|
|
375
|
-
**
|
|
1415
|
+
**Deploy a specific GitHub release by semver tag:**
|
|
376
1416
|
|
|
377
1417
|
```bash
|
|
378
|
-
|
|
1418
|
+
harper deploy \
|
|
1419
|
+
project=my-app \
|
|
1420
|
+
package="HarperDB/application-template#semver:v1.0.0" \
|
|
1421
|
+
target=<remote> \
|
|
1422
|
+
restart=true \
|
|
1423
|
+
replicated=true
|
|
379
1424
|
```
|
|
380
1425
|
|
|
381
|
-
|
|
1426
|
+
#### Notes
|
|
1427
|
+
|
|
1428
|
+
- Always prefer `harper login` for interactive use and environment variables (`HARPER_CLI_USERNAME`, `HARPER_CLI_PASSWORD`) for CI/CD. Avoid inline `username`/`password` parameters in production.
|
|
1429
|
+
- Omitting `package` causes the CLI to package the current local directory. Specifying a local file path creates a symlink, so changes are picked up between restarts without redeploying.
|
|
1430
|
+
- Harper generates a `package.json` from component configurations and resolves dependencies using a form of `npm install`.
|
|
1431
|
+
- For SSH-based private repos, register keys with the Add SSH Key operation before deploying.
|
|
1432
|
+
|
|
1433
|
+
### 4.2 Creating a Harper Fabric Account and Cluster
|
|
382
1434
|
|
|
383
1435
|
Follow these steps to set up your Harper Fabric environment for deployment.
|
|
384
1436
|
|
|
@@ -389,203 +1441,276 @@ Follow these steps to set up your Harper Fabric environment for deployment.
|
|
|
389
1441
|
3. **Create a Cluster**: Create a new cluster. This can be on the free tier, no credit card required.
|
|
390
1442
|
4. **Set Credentials**: During setup, set the cluster username and password to finish configuring it.
|
|
391
1443
|
5. **Get Application URL**: Navigate to the **Config** tab and copy the **Application URL**.
|
|
392
|
-
6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
CLI_TARGET='YOUR_CLUSTER_URL'
|
|
397
|
-
```
|
|
1444
|
+
6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with cluster-specific credentials.
|
|
1445
|
+
7. **Next Steps**: See the [deploying-to-harper-fabric](deploying-to-harper-fabric.md) rule for detailed instructions on deploying your application successfully.
|
|
1446
|
+
|
|
1447
|
+
#### Examples
|
|
398
1448
|
|
|
399
|
-
|
|
1449
|
+
##### Environment Configuration
|
|
400
1450
|
|
|
401
|
-
|
|
1451
|
+
```bash
|
|
1452
|
+
CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
|
|
1453
|
+
CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
|
|
1454
|
+
CLI_TARGET='YOUR_CLUSTER_URL'
|
|
1455
|
+
```
|
|
402
1456
|
|
|
403
|
-
|
|
1457
|
+
### 4.3 Creating Harper Applications
|
|
404
1458
|
|
|
405
|
-
-
|
|
406
|
-
- **Automatic Sync**: Data is synced across the fabric automatically.
|
|
407
|
-
- **Free Tier**: Start for free and scale as you grow.
|
|
1459
|
+
The fastest way to start a new Harper project is using the `create-harper` CLI tool. This command initializes a project with a standard folder structure, essential configuration files, and basic schema definitions.
|
|
408
1460
|
|
|
409
|
-
####
|
|
1461
|
+
#### When to Use
|
|
410
1462
|
|
|
411
|
-
|
|
412
|
-
2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:
|
|
413
|
-
```bash
|
|
414
|
-
CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'
|
|
415
|
-
CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'
|
|
416
|
-
CLI_TARGET='YOUR_CLUSTER_URL'
|
|
417
|
-
```
|
|
418
|
-
3. **Deploy From Local Environment**: Run `npm run deploy`.
|
|
419
|
-
4. **Set up CI/CD**: Configure `.github/workflows/deploy.yaml` and set repository secrets for automated deployments.
|
|
1463
|
+
Use this command when starting a new Harper application or adding a new Harper microservice to an existing architecture.
|
|
420
1464
|
|
|
421
|
-
####
|
|
1465
|
+
#### Commands
|
|
422
1466
|
|
|
423
|
-
|
|
1467
|
+
Initialize a project using your preferred package manager:
|
|
424
1468
|
|
|
425
|
-
|
|
1469
|
+
##### NPM
|
|
426
1470
|
|
|
427
|
-
|
|
1471
|
+
```bash
|
|
1472
|
+
npm create harper@latest
|
|
1473
|
+
```
|
|
428
1474
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
"deploy:component": "harperdb deploy_component . restart=rolling replicated=true"
|
|
434
|
-
},
|
|
435
|
-
"devDependencies": {
|
|
436
|
-
"dotenv-cli": "^11.0.0",
|
|
437
|
-
"harperdb": "^4.7.20"
|
|
438
|
-
}
|
|
439
|
-
}
|
|
1475
|
+
##### PNPM
|
|
1476
|
+
|
|
1477
|
+
```bash
|
|
1478
|
+
pnpm create harper@latest
|
|
440
1479
|
```
|
|
441
1480
|
|
|
442
|
-
|
|
1481
|
+
##### Bun
|
|
443
1482
|
|
|
444
|
-
|
|
1483
|
+
```bash
|
|
1484
|
+
bun create harper@latest
|
|
1485
|
+
```
|
|
445
1486
|
|
|
446
|
-
|
|
447
|
-
- `deploy:component`: The actual command that performs the deployment.
|
|
1487
|
+
#### Options
|
|
448
1488
|
|
|
449
|
-
|
|
1489
|
+
You can specify the project name and template directly:
|
|
450
1490
|
|
|
451
|
-
|
|
1491
|
+
```bash
|
|
1492
|
+
npm create harper@latest my-app --template default
|
|
1493
|
+
```
|
|
452
1494
|
|
|
453
|
-
|
|
1495
|
+
#### Next Steps
|
|
454
1496
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
# push:
|
|
460
|
-
# branches:
|
|
461
|
-
# - main
|
|
462
|
-
concurrency:
|
|
463
|
-
group: main
|
|
464
|
-
cancel-in-progress: false
|
|
465
|
-
jobs:
|
|
466
|
-
deploy:
|
|
467
|
-
runs-on: ubuntu-latest
|
|
468
|
-
steps:
|
|
469
|
-
- name: Checkout code
|
|
470
|
-
uses: actions/checkout@v4
|
|
471
|
-
- name: Set up Node.js
|
|
472
|
-
uses: actions/setup-node@v4
|
|
473
|
-
with:
|
|
474
|
-
cache: 'npm'
|
|
475
|
-
node-version: '20'
|
|
476
|
-
- name: Install dependencies
|
|
477
|
-
run: npm ci
|
|
478
|
-
- name: Run unit tests
|
|
479
|
-
run: npm test
|
|
480
|
-
- name: Run lint
|
|
481
|
-
run: npm run lint
|
|
482
|
-
- name: Deploy
|
|
483
|
-
run: npm run deploy
|
|
484
|
-
env:
|
|
485
|
-
CLI_TARGET: ${{ secrets.CLI_TARGET }}
|
|
486
|
-
CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}
|
|
487
|
-
CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}
|
|
488
|
-
```
|
|
489
|
-
|
|
490
|
-
Be sure to set the following repository secrets in your GitHub repository:
|
|
491
|
-
|
|
492
|
-
- `CLI_TARGET`
|
|
493
|
-
- `CLI_TARGET_USERNAME`
|
|
494
|
-
- `CLI_TARGET_PASSWORD`
|
|
1497
|
+
1. **Configure Environment**: Set up your `.env` file with local or cloud credentials.
|
|
1498
|
+
2. **Define Schema**: Modify `schema.graphql` to fit your application's data model.
|
|
1499
|
+
3. **Start Development**: Run `npm run dev` to start the local Harper instance.
|
|
1500
|
+
4. **Deploy**: Use `npm run deploy` to push your application to Harper Fabric.
|
|
495
1501
|
|
|
496
1502
|
### 4.4 Serving Web Content
|
|
497
1503
|
|
|
498
|
-
|
|
1504
|
+
Instructions for the agent to follow when serving web content from Harper.
|
|
1505
|
+
|
|
1506
|
+
#### When to Use
|
|
1507
|
+
|
|
1508
|
+
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.
|
|
499
1509
|
|
|
500
|
-
####
|
|
1510
|
+
#### How It Works
|
|
501
1511
|
|
|
502
|
-
1. **
|
|
503
|
-
2. **
|
|
1512
|
+
1. **Choose a Method**: Decide between the simple Static Plugin or the integrated Vite Plugin.
|
|
1513
|
+
2. **Option A: Static Plugin (Simple)**:
|
|
1514
|
+
- Add to `config.yaml`:
|
|
1515
|
+
```yaml
|
|
1516
|
+
static:
|
|
1517
|
+
files: 'web/*'
|
|
1518
|
+
```
|
|
1519
|
+
- Place files in a `web/` folder in the project root.
|
|
1520
|
+
- Files are served at the root URL (e.g., `http://localhost:9926/index.html`).
|
|
1521
|
+
3. **Option B: Vite Plugin (Advanced/Development)**:
|
|
1522
|
+
- Add to `config.yaml`:
|
|
1523
|
+
```yaml
|
|
1524
|
+
'@harperfast/vite-plugin':
|
|
1525
|
+
package: '@harperfast/vite-plugin'
|
|
1526
|
+
```
|
|
1527
|
+
- Ensure `vite.config.ts` and `index.html` are in the project root.
|
|
1528
|
+
|
|
1529
|
+
```javascript
|
|
1530
|
+
import vue from '@vitejs/plugin-vue';
|
|
1531
|
+
import path from 'node:path';
|
|
1532
|
+
import { defineConfig } from 'vite';
|
|
1533
|
+
|
|
1534
|
+
// https://vite.dev/config/
|
|
1535
|
+
export default defineConfig({
|
|
1536
|
+
plugins: [vue()],
|
|
1537
|
+
resolve: {
|
|
1538
|
+
alias: {
|
|
1539
|
+
'@': path.resolve(import.meta.dirname, './src'),
|
|
1540
|
+
},
|
|
1541
|
+
},
|
|
1542
|
+
build: {
|
|
1543
|
+
outDir: 'web',
|
|
1544
|
+
emptyOutDir: true,
|
|
1545
|
+
rolldownOptions: {
|
|
1546
|
+
external: ['**/*.test.*', '**/*.spec.*'],
|
|
1547
|
+
},
|
|
1548
|
+
},
|
|
1549
|
+
});
|
|
1550
|
+
```
|
|
1551
|
+
|
|
1552
|
+
- Install dependencies: `npm install --save-dev vite @harperfast/vite-plugin`.
|
|
1553
|
+
- Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.
|
|
1554
|
+
|
|
1555
|
+
4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:
|
|
1556
|
+
```json
|
|
1557
|
+
"build": "vite build",
|
|
1558
|
+
"deploy": "rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ && (cd deploy && harper deploy_component . project=web restart=rolling replicated=true) && rm -Rf deploy",
|
|
1559
|
+
```
|
|
1560
|
+
Then in production, the "Static Plugin" option will performantly and securely serve your assets. `npm create harper@latest` scaffolds all of this for you.
|
|
504
1561
|
|
|
505
|
-
### 4.5 Logging
|
|
1562
|
+
### 4.5 Harper Logging
|
|
506
1563
|
|
|
507
|
-
|
|
1564
|
+
Instructions for the agent to follow when implementing logging in Harper applications, including direct logger usage, tagged loggers, and console capture behavior.
|
|
508
1565
|
|
|
509
|
-
####
|
|
1566
|
+
#### When to Use
|
|
510
1567
|
|
|
511
|
-
|
|
1568
|
+
Apply this rule when writing any JavaScript component, plugin, or resource that needs to emit structured log entries, filter logs by component, or capture existing `console.log` output into Harper's log system. Use it whenever you need to understand log levels, log entry format, or the `logger` global API.
|
|
512
1569
|
|
|
513
|
-
|
|
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).
|
|
1570
|
+
#### How It Works
|
|
517
1571
|
|
|
518
|
-
|
|
1572
|
+
1. **Use the `logger` global directly** — `logger` is available in all JavaScript components without any imports. Call the method matching the desired severity level:
|
|
519
1573
|
|
|
520
|
-
|
|
1574
|
+
```javascript
|
|
1575
|
+
logger.trace('detailed trace message');
|
|
1576
|
+
logger.debug('debug info', { someContext: 'value' });
|
|
1577
|
+
logger.info('informational message');
|
|
1578
|
+
logger.warn('potential issue');
|
|
1579
|
+
logger.error('error occurred', error);
|
|
1580
|
+
logger.fatal('fatal error');
|
|
1581
|
+
logger.notify('server is ready');
|
|
1582
|
+
```
|
|
521
1583
|
|
|
522
|
-
|
|
1584
|
+
Only entries at or above the configured `logging.level` (or `logging.external.level`) are written to `hdb.log`.
|
|
523
1585
|
|
|
524
|
-
|
|
1586
|
+
2. **Create a tagged logger with `withTag(`** — Call `logger.withTag(tag)` once per module or class to get a `TaggedLogger` scoped to that tag. This prefixes every log entry with the tag, making log output filterable by component.
|
|
525
1587
|
|
|
526
|
-
|
|
527
|
-
-
|
|
528
|
-
|
|
529
|
-
- `warn`
|
|
530
|
-
- `error`
|
|
531
|
-
- `fatal`
|
|
532
|
-
- `notify`
|
|
1588
|
+
```javascript
|
|
1589
|
+
const log = logger.withTag('my-resource');
|
|
1590
|
+
```
|
|
533
1591
|
|
|
534
|
-
|
|
1592
|
+
Because `TaggedLogger` methods for disabled levels are `null`, always use optional chaining (`?.`) when calling them:
|
|
535
1593
|
|
|
536
|
-
```
|
|
537
|
-
|
|
1594
|
+
```javascript
|
|
1595
|
+
log.debug?.('Fetching record', { id });
|
|
1596
|
+
log.warn?.('Record not found', { id });
|
|
1597
|
+
log.error?.('Failed to update record', err);
|
|
1598
|
+
```
|
|
538
1599
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
1600
|
+
`TaggedLogger` does not have a `withTag()` method.
|
|
1601
|
+
|
|
1602
|
+
3. **Understand the interface contracts** — `MainLogger` always has all methods defined:
|
|
1603
|
+
|
|
1604
|
+
```typescript
|
|
1605
|
+
interface MainLogger {
|
|
1606
|
+
trace(...messages: any[]): void;
|
|
1607
|
+
debug(...messages: any[]): void;
|
|
1608
|
+
info(...messages: any[]): void;
|
|
1609
|
+
warn(...messages: any[]): void;
|
|
1610
|
+
error(...messages: any[]): void;
|
|
1611
|
+
fatal(...messages: any[]): void;
|
|
1612
|
+
notify(...messages: any[]): void;
|
|
1613
|
+
withTag(tag: string): TaggedLogger;
|
|
1614
|
+
}
|
|
1615
|
+
```
|
|
542
1616
|
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
1617
|
+
`TaggedLogger` methods may be `null`:
|
|
1618
|
+
|
|
1619
|
+
```typescript
|
|
1620
|
+
interface TaggedLogger {
|
|
1621
|
+
trace: ((...messages: any[]) => void) | null;
|
|
1622
|
+
debug: ((...messages: any[]) => void) | null;
|
|
1623
|
+
info: ((...messages: any[]) => void) | null;
|
|
1624
|
+
warn: ((...messages: any[]) => void) | null;
|
|
1625
|
+
error: ((...messages: any[]) => void) | null;
|
|
1626
|
+
fatal: ((...messages: any[]) => void) | null;
|
|
1627
|
+
notify: ((...messages: any[]) => void) | null;
|
|
1628
|
+
}
|
|
1629
|
+
```
|
|
1630
|
+
|
|
1631
|
+
4. **Know the log levels** — From least to most severe:
|
|
547
1632
|
|
|
548
|
-
|
|
1633
|
+
| Level | Description |
|
|
1634
|
+
| -------- | -------------------------------------------------------------------- |
|
|
1635
|
+
| `trace` | Highly detailed internal execution tracing. |
|
|
1636
|
+
| `debug` | Diagnostic information useful during development. |
|
|
1637
|
+
| `info` | General operational events. |
|
|
1638
|
+
| `warn` | Potential issues that don't prevent normal operation. |
|
|
1639
|
+
| `error` | Errors that affect specific operations. |
|
|
1640
|
+
| `fatal` | Critical errors causing process termination. |
|
|
1641
|
+
| `notify` | Important operational milestones. Always logged regardless of level. |
|
|
549
1642
|
|
|
550
|
-
|
|
1643
|
+
The default log level is `warn`. Setting a level includes that level and all more-severe levels.
|
|
551
1644
|
|
|
552
|
-
|
|
1645
|
+
5. **Enable console capture when porting existing code** — When `logging.console: true` is set, writes via `console.log`, `console.warn`, `console.error`, etc. are appended verbatim to `hdb.log`. Captured lines do **not** pass through `logger`'s level filter. Prefer `logger` directly in production code so that level filtering and tagging apply. Console capture is intended as a convenience for porting existing code and for debugging.
|
|
553
1646
|
|
|
554
|
-
|
|
1647
|
+
6. **Know where logs are written** — All standard log output goes to `<ROOTPATH>/log/hdb.log` (default: `~/hdb/log/hdb.log`). To also log to `stdout`/`stderr`, set `logging.stdStreams: true`.
|
|
555
1648
|
|
|
556
|
-
|
|
1649
|
+
#### Examples
|
|
557
1650
|
|
|
558
|
-
|
|
1651
|
+
##### Basic logging in a resource
|
|
1652
|
+
|
|
1653
|
+
```javascript
|
|
1654
|
+
export class MyResource extends Resource {
|
|
1655
|
+
async get(id) {
|
|
1656
|
+
logger.debug('Fetching record', { id });
|
|
1657
|
+
const record = await super.get(id);
|
|
1658
|
+
if (!record) {
|
|
1659
|
+
logger.warn('Record not found', { id });
|
|
1660
|
+
}
|
|
1661
|
+
return record;
|
|
1662
|
+
}
|
|
559
1663
|
|
|
560
|
-
|
|
561
|
-
{
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
1664
|
+
async put(record) {
|
|
1665
|
+
logger.info('Updating record', { id: record.id });
|
|
1666
|
+
try {
|
|
1667
|
+
return await super.put(record);
|
|
1668
|
+
} catch (err) {
|
|
1669
|
+
logger.error('Failed to update record', err);
|
|
1670
|
+
throw err;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
569
1673
|
}
|
|
570
1674
|
```
|
|
571
1675
|
|
|
572
|
-
#####
|
|
1676
|
+
##### Tagged logging with `withTag()`
|
|
1677
|
+
|
|
1678
|
+
```javascript
|
|
1679
|
+
const log = logger.withTag('my-resource');
|
|
1680
|
+
|
|
1681
|
+
export class MyResource extends Resource {
|
|
1682
|
+
async get(id) {
|
|
1683
|
+
log.debug?.('Fetching record', { id });
|
|
1684
|
+
const record = await super.get(id);
|
|
1685
|
+
if (!record) {
|
|
1686
|
+
log.warn?.('Record not found', { id });
|
|
1687
|
+
}
|
|
1688
|
+
return record;
|
|
1689
|
+
}
|
|
573
1690
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
1691
|
+
async put(record) {
|
|
1692
|
+
log.info?.('Updating record', { id: record.id });
|
|
1693
|
+
try {
|
|
1694
|
+
return await super.put(record);
|
|
1695
|
+
} catch (err) {
|
|
1696
|
+
log.error?.('Failed to update record', err);
|
|
1697
|
+
throw err;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
```
|
|
581
1702
|
|
|
582
|
-
|
|
1703
|
+
Tagged entries appear in `hdb.log` with the tag in the header:
|
|
1704
|
+
|
|
1705
|
+
```
|
|
1706
|
+
2023-03-09T14:25:05.269Z [info] [my-resource]: Updating record
|
|
1707
|
+
```
|
|
583
1708
|
|
|
584
|
-
|
|
1709
|
+
#### Notes
|
|
585
1710
|
|
|
586
|
-
-
|
|
587
|
-
- `
|
|
588
|
-
- `
|
|
589
|
-
- `
|
|
590
|
-
-
|
|
591
|
-
- `
|
|
1711
|
+
- All log output is written to `<ROOTPATH>/log/hdb.log`. The `logger` global writes to this file at the configured `logging.external` level.
|
|
1712
|
+
- Log entry format for `logger`: `<timestamp> [<level>] [<thread>/<id>]: <message>`
|
|
1713
|
+
- Log entry format for `TaggedLogger`: `<timestamp> [<level>] [<tag>]: <message>`
|
|
1714
|
+
- `console.log` output is only forwarded to `hdb.log` when `logging.console: true` is explicitly set; it is not forwarded by default.
|
|
1715
|
+
- When logging to standard streams, run Harper in the foreground (`harper`, not `harper start`).
|
|
1716
|
+
- `TaggedLogger` is bound to the configured log level at creation time — always use `?.` on its methods.
|