@markwharton/liquidplanner 2.1.1 → 2.2.0

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/README.md CHANGED
@@ -200,6 +200,7 @@ const client = new LPClient({
200
200
  baseUrl: '...', // Optional: override API base URL
201
201
  onRequest: ({ method, url, description }) => { ... }, // Optional: debug callback
202
202
  cache: {}, // Optional: enable TTL caching (defaults below)
203
+ cacheInstance: cache, // Optional: custom cache backend (e.g., LayeredCache)
203
204
  retry: { // Optional: retry on 429/503
204
205
  maxRetries: 3,
205
206
  initialDelayMs: 1000,
@@ -208,7 +209,7 @@ const client = new LPClient({
208
209
  });
209
210
  ```
210
211
 
211
- `LPConfig` extends `ClientConfig` from api-core, which provides the `baseUrl`, `onRequest`, and `retry` fields. `apiToken`, `workspaceId`, and `cache` are LP-specific.
212
+ `LPConfig` extends `ClientConfig` from api-core, which provides the `baseUrl`, `onRequest`, `retry`, and `cacheInstance` fields. `apiToken`, `workspaceId`, and `cache` are LP-specific. Pass `cacheInstance` to use a custom cache backend (e.g., `LayeredCache` with persistent stores); otherwise `cache: {}` creates an in-memory `TTLCache`.
212
213
 
213
214
  ### Cache TTLs
214
215
 
@@ -223,6 +224,8 @@ const client = new LPClient({
223
224
 
224
225
  Write operations (`createTimesheetEntry`, `updateTimesheetEntry`) automatically invalidate timesheet cache entries. Call `client.invalidateTreeCache()` to refresh the workspace tree, or `client.clearCache()` to clear all cached data.
225
226
 
227
+ Failed API results (`ok: false`) are never cached — transient errors won't persist for the full TTL. See the [root README Cache System section](../../README.md#cache-system) for the full cache architecture (layered stores, PII handling, request coalescing).
228
+
226
229
  ### Retry
227
230
 
228
231
  Automatically retries on HTTP 429 (Too Many Requests) and 503 (Service Unavailable) with exponential backoff. Respects the `Retry-After` header when present.
package/dist/client.d.ts CHANGED
@@ -41,6 +41,8 @@ export declare class LPClient {
41
41
  constructor(config: LPConfig);
42
42
  /**
43
43
  * Route through cache if enabled, otherwise call factory directly.
44
+ * Failed Results (ok === false) are never cached — transient errors
45
+ * shouldn't persist for the full TTL.
44
46
  */
45
47
  private cached;
46
48
  /**
@@ -128,6 +130,7 @@ export declare class LPClient {
128
130
  *
129
131
  * This enables PWA apps to show a task picker populated from LP directly.
130
132
  * Note: userId is not a supported filter field in the LP API, so we filter client-side.
133
+ * The full unfiltered dataset is cached once; all memberId queries share the same cache entry.
131
134
  */
132
135
  getMyAssignments(memberId: number): Promise<Result<LPItem[]>>;
133
136
  /**
package/dist/client.js CHANGED
@@ -10,7 +10,7 @@ import { buildAuthHeader, hoursToMinutes, normalizeItemType, filterIs, filterIsN
10
10
  import { buildTree, getTreeAncestors } from './tree.js';
11
11
  import { parseLPErrorResponse } from './errors.js';
12
12
  import { LP_API_BASE } from './constants.js';
13
- import { TTLCache, batchMap, getErrorMessage, fetchWithRetry, ok, err, resolveRetryConfig } from '@markwharton/api-core';
13
+ import { TTLCache, batchMap, getErrorMessage, fetchWithRetry, ok, okVoid, err, resolveRetryConfig } from '@markwharton/api-core';
14
14
  /** Transform raw API item to LPItem, preserving scheduling and effort fields */
15
15
  function transformItem(raw) {
16
16
  const item = {
@@ -114,8 +114,8 @@ export class LPClient {
114
114
  this.baseUrl = config.baseUrl ?? LP_API_BASE;
115
115
  this.onRequest = config.onRequest;
116
116
  // Initialize cache if configured
117
- if (config.cache) {
118
- this.cache = new TTLCache();
117
+ if (config.cache || config.cacheInstance) {
118
+ this.cache = config.cacheInstance ?? new TTLCache();
119
119
  }
120
120
  this.cacheTtl = {
121
121
  membersTtl: config.cache?.membersTtl ?? 300000,
@@ -130,12 +130,16 @@ export class LPClient {
130
130
  }
131
131
  /**
132
132
  * Route through cache if enabled, otherwise call factory directly.
133
+ * Failed Results (ok === false) are never cached — transient errors
134
+ * shouldn't persist for the full TTL.
133
135
  */
134
- async cached(key, ttlMs, factory) {
135
- if (this.cache) {
136
- return this.cache.get(key, ttlMs, factory);
137
- }
138
- return factory();
136
+ async cached(key, ttlMs, factory, options) {
137
+ if (!this.cache)
138
+ return factory();
139
+ return this.cache.get(key, ttlMs, factory, {
140
+ ...options,
141
+ shouldCache: (data) => data.ok !== false,
142
+ });
139
143
  }
140
144
  /**
141
145
  * Clear all cached API responses.
@@ -158,7 +162,7 @@ export class LPClient {
158
162
  * (e.g., after logging time which updates loggedHoursRollup).
159
163
  */
160
164
  invalidateAssignmentsCache() {
161
- this.cache?.invalidate('assignments:');
165
+ this.cache?.invalidate('assignments');
162
166
  }
163
167
  /**
164
168
  * Invalidate cached workspace tree snapshot only.
@@ -248,7 +252,7 @@ export class LPClient {
248
252
  try {
249
253
  const response = await this.fetch(url);
250
254
  if (response.ok) {
251
- return { ok: true };
255
+ return okVoid();
252
256
  }
253
257
  if (response.status === 401 || response.status === 403) {
254
258
  return err('Invalid or expired API token', response.status);
@@ -372,17 +376,20 @@ export class LPClient {
372
376
  *
373
377
  * This enables PWA apps to show a task picker populated from LP directly.
374
378
  * Note: userId is not a supported filter field in the LP API, so we filter client-side.
379
+ * The full unfiltered dataset is cached once; all memberId queries share the same cache entry.
375
380
  */
376
381
  async getMyAssignments(memberId) {
377
- return this.cached(`assignments:${memberId}`, this.cacheTtl.assignmentsTtl, async () => {
382
+ const result = await this.cached('assignments', this.cacheTtl.assignmentsTtl, async () => {
378
383
  const baseUrl = this.workspaceUrl(`items/v1?${filterIs('itemType', 'assignments')}`);
379
384
  return paginatedFetch({
380
385
  fetchFn: (url) => this.fetch(url),
381
386
  baseUrl,
382
- filter: (data) => data.filter(item => item.userId === memberId),
383
387
  transform: (data) => data.map(transformItem),
384
388
  });
385
389
  });
390
+ if (!result.ok)
391
+ return result;
392
+ return ok(result.data.filter(item => item.userId === memberId));
386
393
  }
387
394
  /**
388
395
  * Get assignments for a member with parent task names resolved
package/dist/index.d.ts CHANGED
@@ -31,8 +31,8 @@
31
31
  export { LPClient } from './client.js';
32
32
  export { resolveTaskToAssignment } from './workflows.js';
33
33
  export type { LPConfig, LPCacheConfig, LPRetryConfig, LPItemType, HierarchyItem, LPItem, LPAncestor, LPWorkspace, LPMember, LPCostCode, LPSyncResult, LPTimesheetEntry, LPTimesheetEntryWithId, LPTaskResolution, LPUpsertOptions, LPAssignmentWithContext, LPFindItemsOptions, LPTreeNode, LPWorkspaceTree, } from './types.js';
34
- export { ok, err, getErrorMessage } from '@markwharton/api-core';
35
- export type { Result, RetryConfig, OnRequestCallback, ClientConfig } from '@markwharton/api-core';
34
+ export { ok, err, getErrorMessage, TTLCache, MemoryCacheStore, LayeredCache } from '@markwharton/api-core';
35
+ export type { Result, RetryConfig, OnRequestCallback, ClientConfig, Cache, CacheStore, CacheGetOptions } from '@markwharton/api-core';
36
36
  export { hoursToMinutes, normalizeItemType, buildAuthHeader, filterIs, filterIsNot, filterIn, filterGt, filterLt, filterAfter, filterBefore, joinFilters, paginatedFetch, } from './utils.js';
37
37
  export type { PaginateOptions } from './utils.js';
38
38
  export { buildTree, getTreeAncestors, getTreeHierarchyPath, findInTree, } from './tree.js';
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ export { LPClient } from './client.js';
33
33
  // Workflows
34
34
  export { resolveTaskToAssignment } from './workflows.js';
35
35
  // Re-exported from @markwharton/api-core
36
- export { ok, err, getErrorMessage } from '@markwharton/api-core';
36
+ export { ok, err, getErrorMessage, TTLCache, MemoryCacheStore, LayeredCache } from '@markwharton/api-core';
37
37
  // Utilities
38
38
  export { hoursToMinutes, normalizeItemType, buildAuthHeader, filterIs, filterIsNot, filterIn, filterGt, filterLt, filterAfter, filterBefore, joinFilters, paginatedFetch, } from './utils.js';
39
39
  // Tree utilities
package/dist/utils.d.ts CHANGED
@@ -49,8 +49,6 @@ export interface PaginateOptions<TRaw, TResult> {
49
49
  baseUrl: string;
50
50
  /** Transform raw API data to result type */
51
51
  transform: (data: TRaw[]) => TResult[];
52
- /** Optional filter to apply to each page */
53
- filter?: (data: TRaw[]) => TRaw[];
54
52
  }
55
53
  /**
56
54
  * Generic pagination helper for LP API endpoints
package/dist/utils.js CHANGED
@@ -76,7 +76,7 @@ export function joinFilters(...filters) {
76
76
  * Handles the continuation token pattern used by LP API.
77
77
  */
78
78
  export async function paginatedFetch(options) {
79
- const { fetchFn, baseUrl, transform, filter } = options;
79
+ const { fetchFn, baseUrl, transform } = options;
80
80
  const hasQueryParams = baseUrl.includes('?');
81
81
  try {
82
82
  const allResults = [];
@@ -93,8 +93,7 @@ export async function paginatedFetch(options) {
93
93
  }
94
94
  const result = await response.json();
95
95
  const rawData = result.data || [];
96
- const filteredData = filter ? filter(rawData) : rawData;
97
- const pageResults = transform(filteredData);
96
+ const pageResults = transform(rawData);
98
97
  allResults.push(...pageResults);
99
98
  continuationToken = result.continuationToken;
100
99
  } while (continuationToken);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markwharton/liquidplanner",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "LiquidPlanner API client for timesheet integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -16,7 +16,7 @@
16
16
  "clean": "rm -rf dist"
17
17
  },
18
18
  "dependencies": {
19
- "@markwharton/api-core": "^1.2.0"
19
+ "@markwharton/api-core": "^1.3.0"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@types/node": "^20.10.0",