@hamak/ui-remote-fs 0.11.0 → 0.12.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.
@@ -1 +1 @@
1
- {"version":3,"file":"remote-fs-middleware.d.ts","sourceRoot":"","sources":["../../../src/impl/middleware/remote-fs-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAkB,MAAM,WAAW,CAAC;AACnF,OAAO,EAAuB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAWlE;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,gBAAgB,CAAC;IACzB,cAAc,EAAE,eAAe,CAAC;IAChC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;IAC1D,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;CACtD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,GAAG,GAAG,EAC9C,MAAM,EAAE,wBAAwB,GAC/B,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CAmQnB;AAED,eAAe,wBAAwB,CAAC"}
1
+ {"version":3,"file":"remote-fs-middleware.d.ts","sourceRoot":"","sources":["../../../src/impl/middleware/remote-fs-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAkB,MAAM,WAAW,CAAC;AACnF,OAAO,EAAyC,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAWpF;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,gBAAgB,CAAC;IACzB,cAAc,EAAE,eAAe,CAAC;IAChC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;IAC1D,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;CACtD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,GAAG,GAAG,EAC9C,MAAM,EAAE,wBAAwB,GAC/B,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CA8bnB;AAED,eAAe,wBAAwB,CAAC"}
@@ -27,7 +27,7 @@
27
27
  * different paths still run concurrently.
28
28
  */
29
29
  import { Pathway } from '@hamak/shared-utils';
30
- import { RemoteFsActionTypes } from '../../api/index.js';
30
+ import { RemoteFsActionTypes, VERSION_MISMATCH } from '../../api/index.js';
31
31
  import { rfsActions, } from '../actions/remote-fs-actions.js';
32
32
  /**
33
33
  * Create remote filesystem middleware
@@ -55,16 +55,191 @@ export function createRemoteFsMiddleware(config) {
55
55
  const pathway = Array.isArray(path) ? Pathway.of(path) : Pathway.of([path]);
56
56
  return pathTranslator.toRemotePath(pathway);
57
57
  };
58
+ /**
59
+ * `code` is only ever taken from the caught value when it is actually a
60
+ * non-empty string — a numeric or otherwise typed `code` must not leak
61
+ * through as an ErrorObject's `code`, which callers expect to be a string
62
+ * (matches the same guard in the HTTP client) (#77 second review, finding D).
63
+ */
64
+ const codeOf = (candidate) => typeof candidate === 'string' && candidate.length > 0 ? candidate : 'UNKNOWN';
65
+ /**
66
+ * First non-blank (after trim) of the candidate messages, else the fixed
67
+ * fallback — one message-resolution rule for every branch of `handleError`
68
+ * (#77 second review).
69
+ */
70
+ const messageOf = (...candidates) => {
71
+ for (const candidate of candidates) {
72
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
73
+ return candidate;
74
+ }
75
+ }
76
+ return 'Unknown error';
77
+ };
78
+ /** A non-null, non-array, non-Date, plain-prototype object. */
79
+ const isPlainObject = (value) => {
80
+ if (typeof value !== 'object' ||
81
+ value === null ||
82
+ Array.isArray(value) ||
83
+ value instanceof Date) {
84
+ return false;
85
+ }
86
+ const proto = Object.getPrototypeOf(value);
87
+ return proto === Object.prototype || proto === null;
88
+ };
89
+ /**
90
+ * A fresh, JSON-safe deep copy of `candidate`: strings, finite numbers,
91
+ * booleans, `null`, plain objects and arrays are kept; functions, symbols,
92
+ * `undefined` and any other non-plain object (a class instance, a `Map`, a
93
+ * live axios config) are dropped; a `Date` becomes its ISO string. A cycle
94
+ * — the same object reachable from itself along its own path — drops the
95
+ * repeated reference instead of recursing forever.
96
+ *
97
+ * Passing `params` through by reference let a function or a live axios
98
+ * config nested under it reach the Redux store and the `onError` callback
99
+ * unsanitized, and made the result alias the object the caller threw
100
+ * (#77 third review, finding 4). The top-level result is `undefined`
101
+ * unless `candidate` itself is a plain object — `params` on the returned
102
+ * `ErrorObject` is either a (possibly empty) object or absent, never a
103
+ * bare string/array/etc.
104
+ */
105
+ const asParams = (candidate) => {
106
+ if (!isPlainObject(candidate)) {
107
+ return undefined;
108
+ }
109
+ const onPath = new WeakSet();
110
+ const sanitize = (value) => {
111
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') {
112
+ return value;
113
+ }
114
+ if (typeof value === 'number') {
115
+ return Number.isFinite(value) ? value : undefined;
116
+ }
117
+ if (value instanceof Date) {
118
+ // An invalid Date throws from toISOString(), and this runs inside the
119
+ // error handler, so it must not throw.
120
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
121
+ }
122
+ if (Array.isArray(value)) {
123
+ if (onPath.has(value)) {
124
+ return undefined;
125
+ }
126
+ onPath.add(value);
127
+ const out = value.map((item) => {
128
+ const sanitized = sanitize(item);
129
+ return sanitized === undefined ? null : sanitized;
130
+ });
131
+ onPath.delete(value);
132
+ return out;
133
+ }
134
+ if (isPlainObject(value)) {
135
+ if (onPath.has(value)) {
136
+ return undefined;
137
+ }
138
+ onPath.add(value);
139
+ const out = {};
140
+ for (const key of Object.keys(value)) {
141
+ // A key present with an `undefined` value is kept: its presence can
142
+ // be the contract. A version-mismatch error on a deleted file carries
143
+ // `current: undefined`, and `isVersionMismatchError` tests
144
+ // `'current' in params`. Dropping the key turned that refusal into a
145
+ // plain failure, so knownVersions was never refreshed and every later
146
+ // PUT to the path was refused again. Only values with no JSON-safe
147
+ // form (functions, symbols, class instances) are dropped.
148
+ const original = value[key];
149
+ const sanitized = sanitize(original);
150
+ if (sanitized !== undefined || original === undefined) {
151
+ out[key] = sanitized;
152
+ }
153
+ }
154
+ onPath.delete(value);
155
+ return out;
156
+ }
157
+ // Functions, symbols, and non-plain objects (class instances, `Map`,
158
+ // a live axios config, an `Error` instance, …) carry no JSON-safe
159
+ // value of their own — drop them.
160
+ return undefined;
161
+ };
162
+ return sanitize(candidate);
163
+ };
58
164
  /**
59
165
  * Handle errors and convert to ErrorObject
60
166
  */
61
167
  const handleError = (error) => {
168
+ // An Error instance (AxiosError, a Node SystemError) also satisfies the
169
+ // duck-type check below — `'code' in error && 'message' in error` is
170
+ // true for most Errors — so that check used to return the live Error
171
+ // instance itself as the "ErrorObject". That instance carries
172
+ // `config`/`request`/`stack` and fails `instanceof Error` checks
173
+ // downstream once it's expected to be a plain object, and it is not
174
+ // serializable for the Redux store. Extract only `code`/`message`/`params`
175
+ // here, before the duck-type check gets a chance to pass it through
176
+ // untouched (#77 review).
177
+ //
178
+ // `params` is included when the rejection carries one, e.g.
179
+ // `Object.assign(new Error(msg), { code: 'version-mismatch', params:
180
+ // { current: 'v9', status: 412 } })` — dropping it silently degraded a
181
+ // version-mismatch PUT failure to a plain `reason: 'error'` and left
182
+ // `knownVersions` stale (#77 second review, finding E).
183
+ if (error instanceof Error) {
184
+ // A client that rethrows a raw AxiosError (rather than the shaped
185
+ // ErrorObject http-workspace-client.ts produces) still carries the
186
+ // server's `code`/`message`/`hint` under `response.data` — discarding
187
+ // it made a real server error indistinguishable from "the network
188
+ // dropped" (#77 third review, finding 5). Only used when there is an
189
+ // actual plain-object body to read; a response-less Error (or one
190
+ // whose `response.data` isn't a plain object) keeps the behaviour
191
+ // below untouched.
192
+ const response = error.response;
193
+ const data = response && typeof response === 'object' ? response.data : undefined;
194
+ if (isPlainObject(data)) {
195
+ const message = messageOf(data.message, typeof data.error === 'string' ? data.error : undefined, error.message);
196
+ const code = typeof data.code === 'string' && data.code.trim().length > 0
197
+ ? data.code
198
+ : codeOf(error.code);
199
+ const ownParams = asParams(error.params);
200
+ const params = {
201
+ ...ownParams,
202
+ status: response.status,
203
+ body: asParams(data),
204
+ };
205
+ // A raw 412 refusal: lift the server's `current` to where
206
+ // `isVersionMismatchError` looks for it, as the HTTP client's own 412
207
+ // branch does. Left in `body` only, the failure read as
208
+ // `reason: 'error'` beside `code: 'version-mismatch'`, and
209
+ // knownVersions was never refreshed.
210
+ if (code === VERSION_MISMATCH) {
211
+ params.current = typeof data.current === 'string' ? data.current : undefined;
212
+ }
213
+ return { code, message, params };
214
+ }
215
+ const params = asParams(error.params);
216
+ return {
217
+ code: codeOf(error.code),
218
+ message: messageOf(error.message),
219
+ ...(params ? { params } : {}),
220
+ };
221
+ }
62
222
  if (error && typeof error === 'object' && 'code' in error && 'message' in error) {
63
- return error;
223
+ // Project to a plain object rather than passing the caught value
224
+ // through untouched — it may carry non-serializable baggage (a
225
+ // function, a live request handle, …) that must not land in the
226
+ // Redux store (#77 second review, finding G).
227
+ const params = asParams(error.params);
228
+ return {
229
+ code: codeOf(error.code),
230
+ message: messageOf(error.message),
231
+ ...(params ? { params } : {}),
232
+ };
233
+ }
234
+ // A client that rejects with a bare string still has a sentence to show;
235
+ // reading `.message` off it would yield "Unknown error" (#77). A
236
+ // whitespace-only string is not a sentence either (finding F).
237
+ if (typeof error === 'string' && error.trim().length > 0) {
238
+ return { code: 'UNKNOWN', message: error };
64
239
  }
65
240
  return {
66
- code: error?.code || 'UNKNOWN',
67
- message: error?.message || 'Unknown error',
241
+ code: codeOf(error?.code),
242
+ message: messageOf(error?.message),
68
243
  };
69
244
  };
70
245
  /** Version last seen for a remote path (key: segments joined by '/'). */
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Structural equality for file content held in store-fs.
3
+ *
4
+ * Store-sync uses it to tell whether a node still holds exactly the content a
5
+ * write sent (#71). Autosave sends the node's own `content` reference, so the
6
+ * common case is decided by the identity check; the recursive walk only runs
7
+ * when something was edited or cloned in between.
8
+ *
9
+ * Content decoded from a file body is JSON-shaped, but a host's
10
+ * `transformContent` or a programmatic write can put anything in the store, so
11
+ * only the shapes whose equality is unambiguous are compared by value:
12
+ * - plain objects and arrays, member by member;
13
+ * - `Date`s, by time.
14
+ * Every other object (`Map`, `Set`, class instances, …) is equal only to
15
+ * itself. Comparing those by own enumerable keys would call any two of them
16
+ * equal — they have none — and in store-sync "equal" means "safe to
17
+ * overwrite".
18
+ *
19
+ * Cyclic structures terminate: a pair already being compared further up is
20
+ * assumed equal, which is the standard coinductive rule.
21
+ */
22
+ export declare function sameContent(a: unknown, b: unknown): boolean;
23
+ //# sourceMappingURL=same-content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"same-content.d.ts","sourceRoot":"","sources":["../../../src/impl/middleware/same-content.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,GAAG,OAAO,CAE3D"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Structural equality for file content held in store-fs.
3
+ *
4
+ * Store-sync uses it to tell whether a node still holds exactly the content a
5
+ * write sent (#71). Autosave sends the node's own `content` reference, so the
6
+ * common case is decided by the identity check; the recursive walk only runs
7
+ * when something was edited or cloned in between.
8
+ *
9
+ * Content decoded from a file body is JSON-shaped, but a host's
10
+ * `transformContent` or a programmatic write can put anything in the store, so
11
+ * only the shapes whose equality is unambiguous are compared by value:
12
+ * - plain objects and arrays, member by member;
13
+ * - `Date`s, by time.
14
+ * Every other object (`Map`, `Set`, class instances, …) is equal only to
15
+ * itself. Comparing those by own enumerable keys would call any two of them
16
+ * equal — they have none — and in store-sync "equal" means "safe to
17
+ * overwrite".
18
+ *
19
+ * Cyclic structures terminate: a pair already being compared further up is
20
+ * assumed equal, which is the standard coinductive rule.
21
+ */
22
+ export function sameContent(a, b) {
23
+ return compare(a, b, []);
24
+ }
25
+ function isPlainObject(value) {
26
+ const proto = Object.getPrototypeOf(value);
27
+ return proto === Object.prototype || proto === null;
28
+ }
29
+ function compare(a, b, path) {
30
+ if (Object.is(a, b)) {
31
+ return true;
32
+ }
33
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
34
+ return false;
35
+ }
36
+ if (a instanceof Date || b instanceof Date) {
37
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
38
+ }
39
+ const bothArrays = Array.isArray(a) && Array.isArray(b);
40
+ if (!bothArrays && !(isPlainObject(a) && isPlainObject(b))) {
41
+ return false;
42
+ }
43
+ if (path.some(([x, y]) => x === a && y === b)) {
44
+ return true;
45
+ }
46
+ path.push([a, b]);
47
+ try {
48
+ if (bothArrays) {
49
+ const left = a;
50
+ const right = b;
51
+ return left.length === right.length && left.every((item, i) => compare(item, right[i], path));
52
+ }
53
+ const left = a;
54
+ const right = b;
55
+ const keys = Object.keys(left);
56
+ return (keys.length === Object.keys(right).length &&
57
+ keys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && compare(left[key], right[key], path)));
58
+ }
59
+ finally {
60
+ path.pop();
61
+ }
62
+ }
@@ -12,10 +12,12 @@ import { StoreSyncMiddlewareConfig } from '../../spi/index.js';
12
12
  *
13
13
  * This middleware intercepts remote FS completion actions and synchronizes them
14
14
  * to the Redux Store FileSystem. It handles:
15
- * - LS_COMPLETED: Creates directories and file entries in Store FS
15
+ * - LS_COMPLETED: Creates directories and file entries in Store FS, without
16
+ * disturbing the body of an entry that has already been read (#71)
16
17
  * - MKDIR_COMPLETED: Creates directory in Store FS
17
18
  * - GET_COMPLETED: Creates/updates file content in Store FS
18
- * - POST/PUT_COMPLETED: Reloads file content from remote
19
+ * - POST/PUT_COMPLETED: Writes the completion payload's own body into the
20
+ * node, and re-GETs when it carried none (or when `autoReload` says so) (#71)
19
21
  * - DELETE_COMPLETED: Removes node from Store FS
20
22
  *
21
23
  * @param config Middleware configuration
@@ -25,8 +27,7 @@ import { StoreSyncMiddlewareConfig } from '../../spi/index.js';
25
27
  * ```typescript
26
28
  * const middleware = createStoreSyncMiddleware({
27
29
  * fileSystemAdapter: storeFs,
28
- * pathTranslator: new PathTranslator(Pathway.ofRoot().resolve('remote')),
29
- * autoReload: true
30
+ * pathTranslator: new PathTranslator(Pathway.ofRoot().resolve('remote'))
30
31
  * });
31
32
  * ```
32
33
  */
@@ -1 +1 @@
1
- {"version":3,"file":"store-sync-middleware.d.ts","sourceRoot":"","sources":["../../../src/impl/middleware/store-sync-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAa,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAGzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AAYtD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,GAAG,GAAG,EAC/C,MAAM,EAAE,yBAAyB,GAChC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CAoLnB;AAED,eAAe,yBAAyB,CAAC"}
1
+ {"version":3,"file":"store-sync-middleware.d.ts","sourceRoot":"","sources":["../../../src/impl/middleware/store-sync-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAa,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAGzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AActD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,GAAG,GAAG,EAC/C,MAAM,EAAE,yBAAyB,GAChC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CA2anB;AAED,eAAe,yBAAyB,CAAC"}
@@ -9,15 +9,18 @@ import { Pathway } from '@hamak/shared-utils';
9
9
  import { RemoteFsActionTypes } from '../../api/index.js';
10
10
  import { rfsActions, } from '../actions/remote-fs-actions.js';
11
11
  import { decodeFileContent } from './file-content-type.js';
12
+ import { sameContent } from './same-content.js';
12
13
  /**
13
14
  * Create store sync middleware
14
15
  *
15
16
  * This middleware intercepts remote FS completion actions and synchronizes them
16
17
  * to the Redux Store FileSystem. It handles:
17
- * - LS_COMPLETED: Creates directories and file entries in Store FS
18
+ * - LS_COMPLETED: Creates directories and file entries in Store FS, without
19
+ * disturbing the body of an entry that has already been read (#71)
18
20
  * - MKDIR_COMPLETED: Creates directory in Store FS
19
21
  * - GET_COMPLETED: Creates/updates file content in Store FS
20
- * - POST/PUT_COMPLETED: Reloads file content from remote
22
+ * - POST/PUT_COMPLETED: Writes the completion payload's own body into the
23
+ * node, and re-GETs when it carried none (or when `autoReload` says so) (#71)
21
24
  * - DELETE_COMPLETED: Removes node from Store FS
22
25
  *
23
26
  * @param config Middleware configuration
@@ -27,13 +30,12 @@ import { decodeFileContent } from './file-content-type.js';
27
30
  * ```typescript
28
31
  * const middleware = createStoreSyncMiddleware({
29
32
  * fileSystemAdapter: storeFs,
30
- * pathTranslator: new PathTranslator(Pathway.ofRoot().resolve('remote')),
31
- * autoReload: true
33
+ * pathTranslator: new PathTranslator(Pathway.ofRoot().resolve('remote'))
32
34
  * });
33
35
  * ```
34
36
  */
35
37
  export function createStoreSyncMiddleware(config) {
36
- const { fileSystemAdapter, pathTranslator, autoReload = true, transformContent, scopeToMount = false, onContentError, } = config;
38
+ const { fileSystemAdapter, pathTranslator, autoReload, transformContent, scopeToMount = false, onContentError, } = config;
37
39
  const storeFsActions = fileSystemAdapter.getActions();
38
40
  // Selects the fs slice out of root state for the existence probe below.
39
41
  // Defaults to the adapter's own slice key (`'fs'` in the canonical store) so a
@@ -41,6 +43,193 @@ export function createStoreSyncMiddleware(config) {
41
43
  // config.sliceSelector. See amah/app-framework#31.
42
44
  const sliceSelector = config.sliceSelector ??
43
45
  ((state) => state?.[fileSystemAdapter.sliceName]);
46
+ const nodeAt = (store, localPath) => fileSystemAdapter.createSelector(sliceSelector, localPath)(store.getState());
47
+ const keyOf = (localPath) => localPath.join('/');
48
+ /**
49
+ * The name a body is classified by: the one the response carries, else the
50
+ * path's last segment. A mount may address files by id, or a request may be
51
+ * redirected, so the path is not guaranteed to end in the file's own name —
52
+ * and the suffix is the whole basis of the decision. Every path that decodes
53
+ * a body uses this, so they cannot disagree about its type.
54
+ */
55
+ const fileNameOf = (localPath, data) => data?.name ?? localPath[localPath.length - 1] ?? '';
56
+ /**
57
+ * Was this node edited after `sent` was written?
58
+ *
59
+ * A write completes asynchronously, so the user may have typed on while it
60
+ * was in flight: the node then holds newer text than the one the server
61
+ * stored. Overwriting it would discard those keystrokes AND mark the node
62
+ * clean, leaving nothing to recover them from.
63
+ *
64
+ * Neither signal alone answers it:
65
+ * - "is the node dirty" fires on every ordinary save, because a node is
66
+ * dirty precisely because it was edited and that edit triggered the save;
67
+ * - "does the node differ from what was sent" fires on every programmatic
68
+ * write — a host PUTting generated content the node never held — and
69
+ * would leave the node showing the old bytes.
70
+ * An in-flight edit is the conjunction: the node was edited locally AND no
71
+ * longer holds what was sent. A string sent for a file whose node holds a
72
+ * parsed value is compared after decoding it the same way a read would.
73
+ *
74
+ * Every node store-sync creates carries a memo (see {@link storeContent}),
75
+ * so the dirty half of the test is always available for remote files.
76
+ */
77
+ const editedSinceSent = (store, localPath, sent, name) => {
78
+ const node = nodeAt(store, localPath);
79
+ if (node?.type !== 'file' || node.content === undefined) {
80
+ return false;
81
+ }
82
+ if (node.state?.memo?.modified !== true) {
83
+ return false;
84
+ }
85
+ if (sameContent(node.content, sent)) {
86
+ return false;
87
+ }
88
+ if (typeof sent === 'string' && typeof node.content !== 'string') {
89
+ return !sameContent(node.content, decodeFileContent(name, sent).content);
90
+ }
91
+ return true;
92
+ };
93
+ /**
94
+ * Put `content`, already in store shape, into the node as the server's copy.
95
+ *
96
+ * A new node is created and then given its content through
97
+ * `setFileContent(fromRemote)` as well: `setFile` seeds no memo, and a node
98
+ * without one has no edit tracking — no dirty indicator ever lights, and the
99
+ * in-flight guard above could never fire for it, so a write echo would
100
+ * silently discard the user's keystrokes. That is exactly the node an
101
+ * on-demand host creates by reading a file before anything lists its
102
+ * directory.
103
+ */
104
+ const storeContent = (store, localPath, content) => {
105
+ const node = nodeAt(store, localPath);
106
+ if (node === undefined) {
107
+ store.dispatch(storeFsActions.setFile(localPath, content, 'xs:any', {
108
+ override: true,
109
+ contentIsPresent: true,
110
+ }));
111
+ store.dispatch(storeFsActions.setFileContent(localPath, content, true));
112
+ return true;
113
+ }
114
+ if (node.type === 'file') {
115
+ // `fromRemote: true` — this is the server's own copy, so it clears the
116
+ // node's dirty memo rather than counting as a local edit.
117
+ store.dispatch(storeFsActions.setFileContent(localPath, content, true));
118
+ return true;
119
+ }
120
+ // A directory of the same name: nothing was written.
121
+ return false;
122
+ };
123
+ /**
124
+ * Take what a successful write sent as the server's copy.
125
+ *
126
+ * - A string is decoded and transformed exactly as a read would.
127
+ * - A value the node already holds is an ordinary save: it is already in
128
+ * store shape, so it is confirmed as-is — transforming it again would
129
+ * change its shape under the user.
130
+ * - Any other value is a programmatic write, new to the store, so it gets
131
+ * the same `transformContent` a read would give it.
132
+ */
133
+ const adoptSentContent = (store, localPath, sent, name) => {
134
+ if (sent === undefined) {
135
+ return;
136
+ }
137
+ if (typeof sent === 'string') {
138
+ writeContentToStore(store, localPath, { name, content: sent });
139
+ return;
140
+ }
141
+ const node = nodeAt(store, localPath);
142
+ if (node?.type === 'file' && sameContent(node.content, sent)) {
143
+ storeContent(store, localPath, node.content);
144
+ return;
145
+ }
146
+ storeContent(store, localPath, transformContent ? transformContent(sent) : sent);
147
+ };
148
+ /** Extension-state key under which store-sync records what it last synced. */
149
+ const SYNC_STATE_KEY = 'remote-fs';
150
+ /**
151
+ * Remember the server version of a node, so a later listing can tell a file
152
+ * that changed on the server from one that did not (#70, #71).
153
+ *
154
+ * `fileSystemAdapter` is typed loosely and a host may hand in its own; one
155
+ * without `setExtensionState` simply gets no listing invalidation rather
156
+ * than a TypeError on every versioned completion.
157
+ */
158
+ const recordVersion = (store, localPath, version) => {
159
+ if (typeof version !== 'string' ||
160
+ typeof storeFsActions.setExtensionState !== 'function' ||
161
+ nodeAt(store, localPath) === undefined) {
162
+ return;
163
+ }
164
+ store.dispatch(storeFsActions.setExtensionState(localPath, SYNC_STATE_KEY, { version }));
165
+ };
166
+ const recordedVersion = (node) => {
167
+ const version = node?.state?.extensionStates?.[SYNC_STATE_KEY]?.version;
168
+ return typeof version === 'string' ? version : undefined;
169
+ };
170
+ /**
171
+ * Refreshes a listing has already asked for, by path, with the version the
172
+ * listing reported. Without it every listing that lands before the GET
173
+ * returns would dispatch the same GET again, and a backend that reports
174
+ * `version` on listings but not on reads would re-fetch the file on every
175
+ * listing forever, because nothing would ever record the new version.
176
+ */
177
+ const pendingRefresh = new Map();
178
+ /**
179
+ * Write a completion payload's body into the store-fs node at `localPath`.
180
+ *
181
+ * Shared by GET_COMPLETED and POST/PUT_COMPLETED so a file that was just
182
+ * written lands exactly the way a file that was just read does — decoded by
183
+ * the same suffix table, through the same transform, into the same node
184
+ * (#71).
185
+ *
186
+ * A GET calls this unconditionally: an absent body is itself the answer, and
187
+ * storing `undefined` with `contentLoaded: true` is what "this file is empty"
188
+ * has always meant here. A write only calls it when the response carried a
189
+ * body — see {@link carriedBody}. Returns whether anything was written.
190
+ */
191
+ const writeContentToStore = (store, localPath, data) => {
192
+ // Classify by suffix before parsing, so a non-JSON body (.md, .sql,
193
+ // .txt, .css, .xqm, ...) never hits JSON.parse, and a malformed
194
+ // .json body is contained rather than thrown into the dispatch
195
+ // chain (which would otherwise unwind into createRemoteFsMiddleware's
196
+ // try and turn a successful GET into a spurious GET_FAILED). See #44.
197
+ // Prefer the name the response carries: the request path is not
198
+ // guaranteed to end in the file's own name (a mount addressing files
199
+ // by id, a redirect), and the suffix is the whole basis of the
200
+ // decision. Fall back to the path's last segment.
201
+ const fileName = fileNameOf(localPath, data);
202
+ const decoded = decodeFileContent(fileName, data?.content);
203
+ if (decoded.error) {
204
+ // Reporting only — the failure is already contained by
205
+ // decodeFileContent, which falls back to the raw text. A host that
206
+ // supplies onContentError takes over the reporting entirely, so it
207
+ // does not get its own message plus ours.
208
+ if (onContentError) {
209
+ onContentError(decoded.error, localPath, data?.content ?? '');
210
+ }
211
+ else {
212
+ console.warn(`[ui-remote-fs] store-sync: ${fileName} claims to be JSON but failed to parse; storing raw text.`, decoded.error);
213
+ }
214
+ }
215
+ let content = decoded.content;
216
+ // Apply content transform if provided. Unchanged guard (#31/#44):
217
+ // JSON files still get the parsed value here, bit-identical to
218
+ // before; non-JSON and malformed-JSON-fallback bodies now also
219
+ // reach this point (they used to throw before ever arriving),
220
+ // and are handed to transformContent as-is, same as any other
221
+ // resolved content.
222
+ if (content !== undefined && transformContent) {
223
+ content = transformContent(content);
224
+ }
225
+ return storeContent(store, localPath, content);
226
+ };
227
+ /**
228
+ * Did this completion payload bring the file's bytes back with it? A write
229
+ * whose response carries the stored `FileInfo` can be echoed straight into
230
+ * the node; one that answers with metadata only cannot.
231
+ */
232
+ const carriedBody = (data) => data?.content !== undefined && data?.content !== null;
44
233
  const storeSyncMiddleware = (store) => (next) => (action) => {
45
234
  const result = next(action);
46
235
  const anyAction = action;
@@ -76,10 +265,35 @@ export function createStoreSyncMiddleware(config) {
76
265
  dispatch(storeFsActions.mkdir(localPath, true, fileInfo.extensions));
77
266
  }
78
267
  else {
79
- // Create file entry without content (contentIsPresent: false)
268
+ // A file already read whose version moved on the server is stale.
269
+ // Keep showing it — blanking it is what #71 was about — and fetch
270
+ // the new body instead. Skipped for a node with unsaved edits: the
271
+ // next save of those is refused as a version mismatch (#70), which
272
+ // is where that conflict belongs. A backend without versions gives
273
+ // nothing to compare, so the body is simply kept.
274
+ const existing = nodeAt(store, localPath);
275
+ const known = recordedVersion(existing);
276
+ if (existing?.type === 'file' &&
277
+ existing.state?.contentLoaded &&
278
+ known !== undefined &&
279
+ typeof fileInfo.version === 'string' &&
280
+ fileInfo.version !== known &&
281
+ existing.state?.memo?.modified !== true) {
282
+ const key = keyOf(localPath);
283
+ if (pendingRefresh.get(key) !== fileInfo.version) {
284
+ pendingRefresh.set(key, fileInfo.version);
285
+ dispatch(rfsActions.ofGetRequest(localPath));
286
+ }
287
+ }
288
+ // Create the file entry without content. `preserveContent` keeps
289
+ // the body of an entry that was already fetched: a listing carries
290
+ // no content, so replacing the node would blank a document that a
291
+ // surface is displaying (#71). An entry whose content was never
292
+ // loaded is refreshed exactly as before.
80
293
  dispatch(storeFsActions.setFile(localPath, undefined, 'xs:any', {
81
294
  override: true,
82
295
  contentIsPresent: false,
296
+ preserveContent: true,
83
297
  extensionStates: fileInfo.extensions,
84
298
  }));
85
299
  }
@@ -98,63 +312,61 @@ export function createStoreSyncMiddleware(config) {
98
312
  const completedAction = anyAction;
99
313
  const { request, data } = completedAction.payload;
100
314
  const localPath = Pathway.of(request.payload.path).getSegments();
101
- // Classify by suffix before parsing, so a non-JSON body (.md, .sql,
102
- // .txt, .css, .xqm, ...) never hits JSON.parse, and a malformed
103
- // .json body is contained rather than thrown into the dispatch
104
- // chain (which would otherwise unwind into createRemoteFsMiddleware's
105
- // try and turn a successful GET into a spurious GET_FAILED). See #44.
106
- // Prefer the name the response carries: the request path is not
107
- // guaranteed to end in the file's own name (a mount addressing files
108
- // by id, a redirect), and the suffix is the whole basis of the
109
- // decision. Fall back to the path's last segment.
110
- const fileName = data?.name ?? localPath[localPath.length - 1] ?? '';
111
- const decoded = decodeFileContent(fileName, data?.content);
112
- if (decoded.error) {
113
- // Reporting only — the failure is already contained by
114
- // decodeFileContent, which falls back to the raw text. A host that
115
- // supplies onContentError takes over the reporting entirely, so it
116
- // does not get its own message plus ours.
117
- if (onContentError) {
118
- onContentError(decoded.error, localPath, data?.content ?? '');
119
- }
120
- else {
121
- console.warn(`[ui-remote-fs] store-sync: ${fileName} claims to be JSON but failed to parse; storing raw text.`, decoded.error);
122
- }
123
- }
124
- let content = decoded.content;
125
- // Apply content transform if provided. Unchanged guard (#31/#44):
126
- // JSON files still get the parsed value here, bit-identical to
127
- // before; non-JSON and malformed-JSON-fallback bodies now also
128
- // reach this point (they used to throw before ever arriving),
129
- // and are handed to transformContent as-is, same as any other
130
- // resolved content.
131
- if (content !== undefined && transformContent) {
132
- content = transformContent(content);
133
- }
134
- // Check if file exists in Store FS
135
- const fileSystemNode = fileSystemAdapter.createSelector(sliceSelector, localPath)(store.getState());
136
- if (fileSystemNode === undefined) {
137
- // File doesn't exist, create it with content
138
- dispatch(storeFsActions.setFile(localPath, content, 'xs:any', {
139
- override: true,
140
- contentIsPresent: true,
141
- }));
142
- }
143
- else {
144
- // File exists, update content only if it's a file
145
- if (fileSystemNode?.type === 'file') {
146
- dispatch(storeFsActions.setFileContent(localPath, content, true));
147
- }
148
- }
315
+ // A read that reports no version still settles a refresh a listing
316
+ // asked for: the listing's version is the one this body belongs to.
317
+ const listed = pendingRefresh.get(keyOf(localPath));
318
+ pendingRefresh.delete(keyOf(localPath));
319
+ writeContentToStore(store, localPath, data);
320
+ recordVersion(store, localPath, typeof data?.version === 'string' ? data.version : listed);
321
+ break;
322
+ }
323
+ case RemoteFsActionTypes.GET_FAILED: {
324
+ // Let the next listing try again.
325
+ const failedAction = anyAction;
326
+ pendingRefresh.delete(keyOf(Pathway.of(failedAction.payload.request.payload.path).getSegments()));
149
327
  break;
150
328
  }
151
329
  case RemoteFsActionTypes.POST_COMPLETED:
152
330
  case RemoteFsActionTypes.PUT_COMPLETED: {
153
331
  const completedAction = anyAction;
154
- const { request } = completedAction.payload;
332
+ const { request, data } = completedAction.payload;
155
333
  const localPath = Pathway.of(request.payload.path).getSegments();
156
- // Reload file content from remote if autoReload is enabled
157
- if (autoReload) {
334
+ // Keystrokes that landed while the write was in flight are newer than
335
+ // anything this completion can tell us, so neither the echo nor the
336
+ // reload may run: both would discard them and mark the node clean. The
337
+ // node stays dirty, so the next save carries them. The server does hold
338
+ // this version now, though, so a later listing must not treat it as a
339
+ // change made elsewhere.
340
+ const name = fileNameOf(localPath, data);
341
+ if (editedSinceSent(store, localPath, request.payload.content, name)) {
342
+ recordVersion(store, localPath, data?.version);
343
+ break;
344
+ }
345
+ // The completion already carries what the server stored, so write it
346
+ // into the node now. Waiting for a re-GET left every surface reading
347
+ // the node showing the OLD bytes until the round-trip landed (#71).
348
+ const echoed = carriedBody(data) && writeContentToStore(store, localPath, data);
349
+ // No body came back, but the write succeeded, so the server holds
350
+ // exactly what was sent: adopt that now rather than after a reload.
351
+ // For an ordinary save it is what the node already holds, and this
352
+ // just clears the dirty flag; for a programmatic write it is the new
353
+ // content. Without this a metadata-only backend with
354
+ // `autoReload: false` would leave every saved file flagged modified
355
+ // forever, and a generated file would keep showing its old bytes.
356
+ if (!echoed) {
357
+ adoptSentContent(store, localPath, request.payload.content, name);
358
+ }
359
+ // After the echo, so a POST that just created the node records too.
360
+ recordVersion(store, localPath, data?.version);
361
+ // Left unset, `autoReload` follows the response: a write that brought
362
+ // its own body needs no round-trip, and one that did not still gets
363
+ // the re-GET it has always had. `@hamak/filesystem-server` answers a
364
+ // write with metadata only, so without this fallback a save would
365
+ // leave the node untouched — the dirty memo would never clear, a POST
366
+ // would never create its node, and extension state synced on GET (the
367
+ // git status badge) would stop refreshing. Setting it forces the
368
+ // behaviour either way.
369
+ if (autoReload ?? !echoed) {
158
370
  dispatch(rfsActions.ofGetRequest(localPath));
159
371
  }
160
372
  break;
@@ -39,8 +39,10 @@ export interface RemoteFsPluginFactoryConfig {
39
39
  */
40
40
  jsonIndent?: number;
41
41
  /**
42
- * Whether to automatically reload file content after PUT/POST
43
- * Default: true
42
+ * Re-GET a file after a PUT/POST completes. Left unset it follows the
43
+ * response: skipped when the write answered with `content` (already written
44
+ * into the node), performed when it answered with metadata only. `true`
45
+ * always re-GETs, `false` never does. See amah/app-framework#71.
44
46
  */
45
47
  autoReload?: boolean;
46
48
  /**
@@ -80,8 +82,7 @@ export interface RemoteFsPluginFactoryConfig {
80
82
  * const plugin = createRemoteFsPlugin({
81
83
  * workspaceId: '0',
82
84
  * mountPoint: Pathway.ofRoot().resolve('remote'),
83
- * baseUrl: 'http://localhost:3000/api',
84
- * autoReload: true
85
+ * baseUrl: 'http://localhost:3000/api'
85
86
  * });
86
87
  * ```
87
88
  */
@@ -1 +1 @@
1
- {"version":3,"file":"remote-fs-plugin-factory.d.ts","sourceRoot":"","sources":["../../../src/impl/plugin/remote-fs-plugin-factory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAKnD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAkB,MAAM,WAAW,CAAC;AAU9E;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,GAAG,CAAC;IAEzC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;O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B,CAAC"}
@@ -29,8 +29,7 @@ import { STORE_MANAGER_TOKEN, STORE_EXTENSIONS_TOKEN, } from '@hamak/ui-store-ap
29
29
  * const plugin = createRemoteFsPlugin({
30
30
  * workspaceId: '0',
31
31
  * mountPoint: Pathway.ofRoot().resolve('remote'),
32
- * baseUrl: 'http://localhost:3000/api',
33
- * autoReload: true
32
+ * baseUrl: 'http://localhost:3000/api'
34
33
  * });
35
34
  * ```
36
35
  */
@@ -1 +1 @@
1
- {"version":3,"file":"http-workspace-client.d.ts","sourceRoot":"","sources":["../../../src/impl/providers/http-workspace-client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAc,EAAE,aAAa,EAAc,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAG/C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;IAE9B;;;;;;;;;OASG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,mBAAoB,YAAW,gBAAgB;IAC1D,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;gBAExB,MAAM,EAAE,yBAAyB;IAoB7C;;OAEG;IACH,OAAO,CAAC,UAAU;IAIlB;;OAEG;IACH,OAAO,CAAC,QAAQ;IAmBhB;;OAEG;IACH,OAAO,CAA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AU,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,QAAQ,CAAC;IAc7E;;OAEG;IACH,cAAc,IAAI,MAAM;IAIxB;;OAEG;IACH,UAAU,IAAI,MAAM;CAGrB;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,IAAI,CAAC,yBAAyB,EAAE,aAAa,GAAG,SAAS,CAAC,GACnE,mBAAmB,CAMrB"}
@@ -5,7 +5,84 @@
5
5
  * Migrated from amk/libs/server/ws/ws-client/src/lib/server-ws-ws-client.ts
6
6
  */
7
7
  import axios from 'axios';
8
- import { VERSION_MISMATCH } from '../../api/index.js';
8
+ import { isErrorObject, VERSION_MISMATCH, } from '../../api/index.js';
9
+ /**
10
+ * Resolve a non-blank message from an ordered list of candidates, falling
11
+ * back to the underlying axios message, then a fixed sentence.
12
+ *
13
+ * Both the structured-passthrough path and the raw-body path in
14
+ * {@link HttpWorkspaceClient.handleError} need to pick a message out of a few
15
+ * candidate fields in priority order, skipping any that are blank/nullish —
16
+ * a body like `{ message: '' }` must not win over a usable `error` field, and
17
+ * a candidate that is present but empty must not surface as an empty message
18
+ * (#77 second review, findings B/C).
19
+ */
20
+ function resolveMessage(candidates, axiosMessage) {
21
+ for (const candidate of candidates) {
22
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
23
+ return candidate;
24
+ }
25
+ }
26
+ if (typeof axiosMessage === 'string' && axiosMessage.trim().length > 0) {
27
+ return axiosMessage;
28
+ }
29
+ return 'Unknown error occurred';
30
+ }
31
+ /**
32
+ * Render an `error` field that is not an {@link ErrorObject} as a sentence,
33
+ * so a body carrying no `message` still reaches the screen as something
34
+ * better than "Unknown error".
35
+ *
36
+ * `null`/`undefined` render as `''` rather than the literal words "null" or
37
+ * "undefined" — the caller treats an empty result as "no usable message" and
38
+ * falls back accordingly (#77 review). An empty object (`{}`) or empty array
39
+ * (`[]`) also render as `''` — `JSON.stringify` would otherwise turn those
40
+ * into the literal text "{}" or "[]", which reads as a message but carries no
41
+ * information, defeating the axios-message fallback (#77 third review,
42
+ * finding 2).
43
+ */
44
+ function stringifyError(error) {
45
+ if (error === null || error === undefined) {
46
+ return '';
47
+ }
48
+ if (typeof error === 'string') {
49
+ return error;
50
+ }
51
+ if (error instanceof Error) {
52
+ return error.message;
53
+ }
54
+ if (Array.isArray(error)) {
55
+ if (error.length === 0) {
56
+ return '';
57
+ }
58
+ }
59
+ else if (typeof error === 'object') {
60
+ if (Object.keys(error).length === 0) {
61
+ return '';
62
+ }
63
+ const nestedMessage = error.message;
64
+ if (typeof nestedMessage === 'string' && nestedMessage.trim().length > 0) {
65
+ return nestedMessage;
66
+ }
67
+ }
68
+ try {
69
+ return JSON.stringify(error);
70
+ }
71
+ catch {
72
+ return String(error);
73
+ }
74
+ }
75
+ /**
76
+ * A non-null, non-array object — safe to spread as `params`.
77
+ *
78
+ * `isErrorObject` only checks `code`/`message`, so `data.error.params` can be
79
+ * anything the server sent, including a string or an array; spreading either
80
+ * one produces numeric-index junk keys rather than being dropped (#77 third
81
+ * review, finding 1).
82
+ */
83
+ function isPlainObjectParams(candidate) {
84
+ return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate);
85
+ }
9
86
  /**
10
87
  * HTTP-based implementation of IWorkspaceClient
11
88
  *
@@ -111,9 +188,74 @@ export class HttpWorkspaceClient {
111
188
  };
112
189
  throw mismatch;
113
190
  }
114
- // Try to extract error from response
115
- if (axiosError.response?.data?.error) {
116
- throw axiosError.response.data.error;
191
+ // The server answered with a body of its own (amah/app-framework#77).
192
+ // Keep every field it sent: `message` is the sentence written for a
193
+ // person, `code` lets the host branch on the cause, and `params.body`
194
+ // carries the rest — `hint` above all, which a host renders as a link.
195
+ //
196
+ // The plain ErrorObject shape (`{ code, message }`, no `error` key) is
197
+ // just as valid a server response as one carrying `error`, so the
198
+ // branch has to fire on any of the three fields, not just `error`
199
+ // (#77 review).
200
+ const data = axiosError.response?.data;
201
+ if (data &&
202
+ typeof data === 'object' &&
203
+ (data.error !== undefined || typeof data.message === 'string' || typeof data.code === 'string')) {
204
+ // A server that already speaks ErrorObject is passed through, but
205
+ // still merged with `params.status`/`params.body` like the other
206
+ // path below — otherwise a sibling field such as `hint` next to the
207
+ // nested error object would be silently dropped (#77 review).
208
+ //
209
+ // The transport fields (`status`/`statusText`/`body`) are spread
210
+ // LAST, after the nested object's own `params`, so they always win:
211
+ // a server-supplied `params.status` or `params.body` must not shadow
212
+ // the real HTTP status/body, and `hint` (whether top-level or nested
213
+ // under `params`) must survive. Other server param keys (e.g. `path`)
214
+ // still pass through untouched (#77 second review, finding A).
215
+ if (isErrorObject(data.error)) {
216
+ const passthroughMessage = resolveMessage([data.error.message, typeof data.message === 'string' ? data.message : undefined], axiosError.message);
217
+ const passthroughCode = data.error.code.trim().length > 0 ? data.error.code : 'REMOTE';
218
+ // `data.error.params` is only ever spread when it is itself a safe
219
+ // object to spread — a server that sent `params: 'oops'` (a string)
220
+ // would otherwise explode into numeric-index keys ({"0":"o",...})
221
+ // rather than being ignored (#77 third review, finding 1).
222
+ const nestedParams = isPlainObjectParams(data.error.params)
223
+ ? data.error.params
224
+ : undefined;
225
+ const passthrough = {
226
+ ...data.error,
227
+ code: passthroughCode,
228
+ message: passthroughMessage,
229
+ params: {
230
+ ...nestedParams,
231
+ status: axiosError.response?.status,
232
+ statusText: axiosError.response?.statusText,
233
+ body: data,
234
+ },
235
+ };
236
+ throw passthrough;
237
+ }
238
+ // Resolve a non-empty message: the server's own `message`, else the
239
+ // stringified `error` field, else the underlying axios message, else
240
+ // a fixed fallback. An empty/blank/nullish candidate at any step is
241
+ // never used — a body like `{ error: '' }` or `{ error: null }`
242
+ // must not produce a blank or literal "null" message (#77 review).
243
+ const message = resolveMessage([data.message, stringifyError(data.error)], axiosError.message);
244
+ // `code` is only ever taken from the body when it is actually a
245
+ // string — a numeric HTTP-status-like `code` must not leak through
246
+ // as an ErrorObject's `code`, which callers expect to be a string
247
+ // (#77 review).
248
+ const code = typeof data.code === 'string' && data.code.length > 0 ? data.code : 'REMOTE';
249
+ const fromBody = {
250
+ code,
251
+ message,
252
+ params: {
253
+ status: axiosError.response?.status,
254
+ statusText: axiosError.response?.statusText,
255
+ body: data,
256
+ },
257
+ };
258
+ throw fromBody;
117
259
  }
118
260
  // Create error from axios error
119
261
  const errorObj = {
@@ -41,8 +41,27 @@ export interface StoreSyncMiddlewareConfig {
41
41
  */
42
42
  pathTranslator: IPathTranslator;
43
43
  /**
44
- * Whether to automatically reload file content after PUT/POST
45
- * Default: true
44
+ * Re-GET a file after a PUT/POST completes.
45
+ *
46
+ * **Left unset it follows the response** — changed in
47
+ * amah/app-framework#71, where it was unconditionally `true`.
48
+ * `PUT_COMPLETED` now writes the completion payload's own body into the node
49
+ * synchronously, so a write that answers with `content` needs no round-trip;
50
+ * with the old behaviour every surface showed the pre-save bytes for as long
51
+ * as the reload was in flight. A write that answers with metadata only —
52
+ * which is what `@hamak/filesystem-server` does — still gets the re-GET it
53
+ * has always had, so the dirty memo clears, a POST creates its node, and
54
+ * extension state synced on GET keeps refreshing.
55
+ *
56
+ * - `true` — always re-GET, even when the body was already written. Costs a
57
+ * request; use it when the server rewrites what it stores and the host
58
+ * wants that canonical copy. Never reintroduces the stale window, because
59
+ * the synchronous write still lands first.
60
+ * - `false` — never re-GET. Only safe when the write response carries
61
+ * `content`.
62
+ *
63
+ * Either way, a node edited while the write was in flight is left alone:
64
+ * those keystrokes are newer than anything the completion can report.
46
65
  */
47
66
  autoReload?: boolean;
48
67
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"remote-fs-middleware.types.d.ts","sourceRoot":"","sources":["../../../src/spi/middleware/remote-fs-middleware.types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,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AE,EAAE,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"remote-fs-middleware.types.d.ts","sourceRoot":"","sources":["../../../src/spi/middleware/remote-fs-middleware.types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC;;OAEG;IACH,MAAM,EAAE,gBAAgB,CAAC;IAEzB;;OAEG;IACH,cAAc,EAAE,eAAe,CAAC;IAEhC;;OAEG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,IAAI,CAAC;IAE9C;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK,IAAI,CAAC;CAChD;AAED;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,iBAAiB,EAAE,GAAG,CAAC;IAEvB;;OAEG;IACH,cAAc,EAAE,eAAe,CAAC;IAEhC;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,GAAG,CAAC;IAEzC;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,CAAC;IAEpC;;;;;;;;;;;;OAYG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;;;;;;;;;;;;;OAeG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CACtE;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,GAAG,GAAG,IAAI,CAC/C,MAAM,EAAE,wBAAwB,KAC7B,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAEvB;;GAEG;AACH,MAAM,MAAM,0BAA0B,CAAC,CAAC,GAAG,GAAG,IAAI,CAChD,MAAM,EAAE,yBAAyB,KAC9B,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hamak/ui-remote-fs",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Remote filesystem synchronization for microkernel-based applications",
@@ -52,18 +52,19 @@
52
52
  }
53
53
  },
54
54
  "dependencies": {
55
- "@hamak/shared-utils": "*",
56
- "@hamak/ui-store-api": "*",
57
- "@hamak/ui-store-impl": "*",
58
- "@hamak/microkernel-api": "*",
59
- "@hamak/microkernel-spi": "*",
55
+ "@hamak/shared-utils": "^0.12.0",
56
+ "@hamak/ui-store-api": "^0.12.0",
57
+ "@hamak/ui-store-impl": "^0.12.0",
58
+ "@hamak/microkernel-api": "^0.12.0",
59
+ "@hamak/microkernel-spi": "^0.12.0",
60
60
  "@reduxjs/toolkit": "^2.0.0",
61
61
  "axios": "^1.6.0",
62
62
  "redux": "^5.0.1"
63
63
  },
64
64
  "devDependencies": {
65
+ "@hamak/ui-store": "^0.12.0",
66
+ "@types/node": "^20.0.0",
65
67
  "typescript": "~5.4.0",
66
- "vitest": "^2.0.0",
67
- "@types/node": "^20.0.0"
68
+ "vitest": "^2.0.0"
68
69
  }
69
70
  }