Skip to content

Commit 45f6aae

Browse files
committed
Update hyperclayjs
1 parent dea021d commit 45f6aae

11 files changed

Lines changed: 182 additions & 43 deletions

‎CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
# Changelog
22

3+
## [1.38.0] - 2026-08-29
4+
5+
### Breaking Changes
6+
- **The save token is read under one name, `savetoken`.** `htmlclaytoken`, the pre-rename spelling, is no longer accepted as a credential. This breaks documents served by HTML Clay 1.8.0 or earlier, which inject only the old name: the page stays editable, because that host also sets the edit-mode cookie, and every save posts to the bare `/_/save`, which that host does not route. Upgrade HTML Clay to 1.9.0 or newer, which serves both names. The library says so in the console when it finds the old name. The old name is still stripped from every save and kept out of an incoming morph, because what a host injects must be removed whether or not this library reads it.
7+
8+
### Changed
9+
- Saves send `Document-URL`, the header spec §3 names, alongside the older `Page-URL`. Both Hyperclay hosts read the new name first and fall back to the old one, so nothing changes against them; a third-party host implementing only the specification would have refused every save this library sent.
10+
11+
### Fixed
12+
- A document's durable file identity is no longer read as a save token. `documentid` and `htmlclayid` shared one list with the token spellings, so a document carrying an identity but no token posted to `/_/save/{id}` with credentials omitted and opened in edit mode for every visitor. Identities have their own list now: still stripped before a save, still kept out of an incoming morph, never read as a credential.
13+
314
## [1.37.9] - 2026-08-28
415

516
### Changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @jest-environment jsdom
3+
* @jest-environment-options {"url": "http://localhost:4321/index.html"}
4+
*
5+
* Which document a save is for rides in a header, and section 3 of the Malleable
6+
* HTML File specification names that header `Document-URL`.
7+
*
8+
* This library sent only `Page-URL`, the pre-spec spelling. Nothing broke, because
9+
* both Hyperclay hosts read `Document-URL` first and fall back to `Page-URL`, so
10+
* the gap was invisible from inside this workspace. It is not invisible from
11+
* outside it: a third-party host that implements the specification and nothing
12+
* else reads one header, and would have refused every save this library sent.
13+
*
14+
* Both names go out. Dropping the old one is the mirror mistake, since stored
15+
* customer documents hardcode a client that sends it and can never be updated.
16+
*/
17+
18+
jest.mock('../src/core/isAdminOfCurrentResource.js', () => ({
19+
isEditMode: true,
20+
}));
21+
22+
jest.mock('../src/core/snapshot.js', () => ({
23+
captureForSave: jest.fn(() => '<html>captured</html>'),
24+
isCodeMirrorPage: jest.fn(() => false),
25+
getCodeMirrorContents: jest.fn(() => ''),
26+
beforeSave: jest.fn(),
27+
getPageContents: jest.fn(),
28+
onSnapshot: jest.fn(),
29+
onPrepareForSave: jest.fn(),
30+
}));
31+
32+
import { savePage, saveHtml } from '../src/core/savePageCore.js';
33+
34+
const headers = () => global.fetch.mock.calls[0][1].headers;
35+
36+
describe('a save says which document it is for', () => {
37+
beforeEach(() => {
38+
global.fetch = jest.fn(() =>
39+
Promise.resolve({
40+
ok: true,
41+
json: () => Promise.resolve({ msg: 'Saved', msgType: 'success' }),
42+
})
43+
);
44+
});
45+
46+
afterEach(() => {
47+
jest.clearAllMocks();
48+
});
49+
50+
test('savePage sends Document-URL, and Page-URL beside it', async () => {
51+
await savePage();
52+
53+
expect(headers()['Document-URL']).toBe(window.location.href);
54+
expect(headers()['Page-URL']).toBe(window.location.href);
55+
});
56+
57+
test('saveHtml sends Document-URL, and Page-URL beside it', async () => {
58+
await saveHtml('<html>given</html>');
59+
60+
expect(headers()['Document-URL']).toBe(window.location.href);
61+
expect(headers()['Page-URL']).toBe(window.location.href);
62+
});
63+
});

‎__tests__/save-htmlclay-endpoint.test.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,19 @@ describe('savePage — htmlclay endpoint routing', () => {
3434
json: () => Promise.resolve({ msg: 'Saved', msgType: 'success' }),
3535
})
3636
);
37+
document.documentElement.removeAttribute('savetoken');
3738
document.documentElement.removeAttribute('htmlclaytoken');
3839
delete window.__hyperclaySnapshotHtml;
3940
});
4041

4142
afterEach(() => {
4243
jest.clearAllMocks();
44+
document.documentElement.removeAttribute('savetoken');
4345
document.documentElement.removeAttribute('htmlclaytoken');
4446
});
4547

46-
test('posts to /_/save/{token} with a plain-text body when htmlclaytoken is present', async () => {
47-
document.documentElement.setAttribute('htmlclaytoken', 'TOK123');
48+
test('posts to /_/save/{token} with a plain-text body when savetoken is present', async () => {
49+
document.documentElement.setAttribute('savetoken', 'TOK123');
4850

4951
const result = await savePage();
5052

@@ -56,7 +58,7 @@ describe('savePage — htmlclay endpoint routing', () => {
5658
expect(result).toEqual({ msg: 'Saved', msgType: 'success' });
5759
});
5860

59-
test('posts to bare /_/save when htmlclaytoken is absent', async () => {
61+
test('posts to bare /_/save when savetoken is absent', async () => {
6062
await savePage();
6163

6264
expect(global.fetch).toHaveBeenCalledTimes(1);

‎__tests__/save-token-endpoint.test.js‎

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
/**
22
* @jest-environment jsdom
33
*
4-
* The save lane resolves the host's per-file token under BOTH of its spellings,
5-
* and pairs the endpoint with the right credential mode.
4+
* The save lane resolves the host's per-file token, and pairs the endpoint with the
5+
* right credential mode.
66
*
7-
* Spec §9 names the attribute `savetoken`; `htmlclaytoken` is the original name.
8-
* The save lane used to read only the old one while host-meta.js read both, so a
9-
* host serving the spec's spelling got a save posted to the bare `/_/save` with no
10-
* identity on it. Neither name may ever be dropped: a saved document is a frozen
11-
* client that keeps sending whatever library version wrote it, so a host still
12-
* serves the old name to documents written years ago.
7+
* Spec §9 names one attribute, `savetoken`, and that is now the only name read as a
8+
* credential. `htmlclaytoken` is the original spelling and is still STRIPPED before
9+
* every save and kept out of a peer's morph, because a host goes on injecting it
10+
* forever: a saved document is a frozen client that keeps reading whatever name the
11+
* library that wrote it read. Stripping it and accepting it are separate decisions,
12+
* and only the second one was reversed.
1313
*/
1414

1515
jest.mock('../src/core/isAdminOfCurrentResource.js', () => ({
@@ -61,15 +61,21 @@ describe('save token resolution', () => {
6161
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/SPEC123');
6262
});
6363

64-
test('still posts to /_/save/{token} under the original htmlclaytoken name', async () => {
64+
// The pre-rename name is no longer a credential. A deliberate break: a document served by an
65+
// htmlclay at or below 1.8.0, which injects only the old name, posts to the bare route and gets a
66+
// 404 from a host that registers only POST /_/save/{token}. Taken knowingly while htmlclay is
67+
// days old, rather than carrying a second credential name in the save path forever, and
68+
// host-attrs.js warns in the console so the failure names its own cause.
69+
// ⚠️ htmlclay 1.9.0, which injects both names, must publish before this does.
70+
test('does not post to /_/save/{token} under the pre-rename name', async () => {
6571
document.documentElement.setAttribute('htmlclaytoken', 'OLD123');
6672

6773
await savePage();
6874

69-
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/OLD123');
75+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save');
7076
});
7177

72-
test('prefers savetoken when a host serves both spellings', async () => {
78+
test('reads savetoken when a host still serves both spellings', async () => {
7379
document.documentElement.setAttribute('savetoken', 'SPEC123');
7480
document.documentElement.setAttribute('htmlclaytoken', 'OLD123');
7581

@@ -78,13 +84,16 @@ describe('save token resolution', () => {
7884
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/SPEC123');
7985
});
8086

81-
test('falls through an empty savetoken to the older spelling', async () => {
87+
// An empty token is a host that minted none, and there is no second name to fall through to. The
88+
// bare route is right: it is the cookie-authenticated lane, so a host that meant to mint a token
89+
// and failed gets an honest refusal rather than a save posted under a stale credential.
90+
test('an empty savetoken means no token, with nothing to fall through to', async () => {
8291
document.documentElement.setAttribute('savetoken', '');
8392
document.documentElement.setAttribute('htmlclaytoken', 'OLD123');
8493

8594
await savePage();
8695

87-
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/OLD123');
96+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save');
8897
});
8998

9099
test('posts to the bare /_/save when the host minted no token', async () => {
@@ -141,7 +150,7 @@ describe('save credentials follow the endpoint', () => {
141150
});
142151

143152
test('saveHtml pairs credentials with the endpoint too', async () => {
144-
document.documentElement.setAttribute('htmlclaytoken', 'OLD123');
153+
document.documentElement.setAttribute('savetoken', 'OLD123');
145154

146155
await saveHtml('<html>direct</html>');
147156

‎docs/api/data-loss-panel.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ In `standard`, `cms`, `smooth-sailing`, and `everything`. Not in `minimal`. It a
1414
- External / cross-device clobbers (another device, a CLI tool, a raw disk edit) produce no `save-saved` here, so on non-livesync presets they surface on the next reload (the page-load `GET`). Hyperclay Local's sync watcher reloads the page on external change, which re-runs that check.
1515
- A user choice POSTs to `POST /_/data-loss/<id>` with `{ choice, file }`. Restore and revert reload the page (~350ms) after success.
1616
- On init it also calls `initUserGesture()` (so save provenance is correct even in presets without autosave) and `Mutation.ensureObserving()`.
17-
- The chip's root carries `no-save` and `snapshot-remove`, so it never reaches a saved file. Feedback uses `window.toast`.
17+
- The chip's root carries `no-save` and `snapshot-remove`, the legacy alias for `no-snapshot`, so it never reaches a saved file. Feedback uses `window.toast`.
1818

1919
## Requirements
2020

‎docs/api/liveSync.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# live-sync
22

3-
Real-time DOM sync across browsers via SSE. When one user saves, all connected browsers see the changes instantly via HyperMorph. Works with Hyperclay Local app.
3+
Real-time DOM sync across browsers via SSE. Edit-mode tabs exchange working snapshots on the live lane as changes are captured. View-mode tabs receive durable documents on the saved lane after the host persists them. HyperMorph applies both in place. Works with Hyperclay Local app.
44

55
## Access
66

@@ -17,7 +17,7 @@ Real-time DOM sync across browsers via SSE. When one user saves, all connected b
1717

1818
| Name | Type | Default | Description |
1919
|------|------|---------|-------------|
20-
| file | string | — | Optional. A presence guard and log label only; it does **not** select the sync channel. The channel is keyed off the page URL (`window.location.href` / the `Page-URL` header). Auto-detected from the pathname when omitted |
20+
| file | string | — | Optional. A presence guard and log label only; it does **not** select the sync channel. The current page URL selects the channel, sent as `Document-URL` on the spec POST and `document-url` on the spec GET. Older hosts use the discovered legacy wire. Auto-detected from the pathname when omitted |
2121

2222
## Example
2323

‎docs/api/snapshot.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ In every preset: `minimal`, `standard`, `smooth-sailing`, and `everything`. The
2424

2525
```
2626
1. CLONE document.documentElement.cloneNode(true)
27-
2. SNAPSHOT onSnapshot hooks + [onbeforesnapshot] + [snapshot-remove] + extension-noise strip
27+
2. SNAPSHOT onSnapshot hooks + [onbeforesnapshot] + [no-snapshot] + extension-noise strip
2828
├─ used by SAVE and LIVE-SYNC
2929
└─ emits hyperclay:snapshot-ready
30-
3. PREPARE [onbeforesave] + [no-save] + onPrepareForSave hooks
30+
3. PREPARE [onbeforesave] + onPrepareForSave hooks + [no-save]
3131
└─ used by SAVE only (live-sync stops at step 2)
3232
4. SERIALIZE "<!DOCTYPE html>" + clone.outerHTML → sent to server
3333
```
3434

35-
`captureForComparison` and the compare half of `captureForSaveAndComparison` additionally strip every region whose autosave-trigger is off (`[no-trigger-autosave]`, plus `[no-save]`, `[freeze]`, and `[no-watch]`) so runtime-only elements do not trip dirty-checking. See [region attributes](./region-attributes.md); the legacy `save-*` / `mutations-ignore` markers are recognized as aliases.
35+
`captureForComparison` and the compare half of `captureForSaveAndComparison` additionally strip every region whose autosave-trigger is off (`[no-trigger-autosave]`, plus `[no-save]`, `[freeze]`, and `[no-watch]`) so runtime-only elements do not trip dirty-checking. See [region attributes](./region-attributes.md); the legacy `save-*`, `mutations-ignore`, and `snapshot-remove` markers are recognized as aliases.
3636

3737
## Hooks
3838

@@ -48,7 +48,7 @@ Each callback receives the cloned `<html>` element (`HTMLElement`) and mutates i
4848

4949
| Function | Returns | Description |
5050
|----------|---------|-------------|
51-
| `captureSnapshot()` | `HTMLElement` | Clones `<html>`, runs `onSnapshot` hooks, `[onbeforesnapshot]`, `[snapshot-remove]`, and strips extension noise. Nothing save-specific stripped yet |
51+
| `captureSnapshot()` | `HTMLElement` | Clones `<html>`, runs `onSnapshot` hooks, `[onbeforesnapshot]`, `[no-snapshot]`, and strips extension noise. Nothing save-specific stripped yet |
5252
| `captureForSave({ emitForSync = true })` | `string` | Full save pipeline. Emits `hyperclay:snapshot-ready`, then runs prepare phase. Returns `"<!DOCTYPE html>" + outerHTML` |
5353
| `captureForComparison()` | `string` | Like the save path but also strips every region whose autosave-trigger is off (`[no-trigger-autosave]` and friends). For comparing current state against a baseline. Does not emit `snapshot-ready` |
5454
| `captureForSaveAndComparison({ emitForSync = true })` | `{ forSave, forComparison }` | Single clone, then forks into a save string and a comparison string. Cheaper than calling both separately |
@@ -70,7 +70,7 @@ These markup hooks are processed during capture. Inline attribute handlers run v
7070
| Attribute | Phase | Effect |
7171
|-----------|-------|--------|
7272
| `onbeforesnapshot` | snapshot (save + sync) | Inline JS runs on the cloned element before any stripping |
73-
| `snapshot-remove` | snapshot (save + sync) | Element is removed from every snapshot, so it never reaches a save, a comparison, or a live-sync broadcast |
73+
| `no-snapshot` | snapshot (save + sync) | Element is removed from every snapshot, so it never reaches a save, a comparison, or a live-sync broadcast (legacy alias: `snapshot-remove`) |
7474
| `onbeforesave` | prepare (save + compare) | Inline JS runs on the cloned element before save-specific stripping |
7575
| `no-save` | prepare (save + compare) | Element is removed from the saved HTML entirely (legacy alias: `save-remove`) |
7676
| `no-trigger-autosave` | comparison only | Element is excluded from dirty-checking but still saved as-is (legacy alias: `save-ignore`) |
@@ -89,7 +89,7 @@ When `isCodeMirrorPage()` is true, the capture functions bypass the DOM snapshot
8989

9090
## Hyperclay Local
9191

92-
On `localhost` / `127.0.0.1`, `captureForSaveAndComparison` stores the full unstripped snapshot HTML on `window.__hyperclaySnapshotHtml`. The save system sends both the stripped content and this full snapshot as JSON so the desktop platform can mirror the page exactly. The value is cleared after each send.
92+
Saving uses the same two requests on every host. The save system sends the stripped document as text to `/_/save`. When live-sync is loaded, it separately sends the prepared snapshot root as JSON to `/_/sync`, or to the discovered legacy relay on an older host.
9393

9494
## Undo Flush
9595

@@ -117,7 +117,7 @@ const html = captureForSave({ emitForSync: false });
117117
```html
118118
<!-- Markup-level hooks -->
119119
<div onbeforesnapshot="this.dataset.snappedAt = Date.now()">...</div>
120-
<div snapshot-remove>Never appears in any snapshot</div>
120+
<div no-snapshot>Never appears in any snapshot</div>
121121
<button no-save>Hidden from the saved file</button>
122122
<div no-trigger-autosave>Saved as-is but skipped by dirty-checking</div>
123123
```

‎docs/api/toast.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ toast('Uploaded successfully');
3535
## Notes
3636

3737
- `message` is inserted as HTML (`innerHTML`), so do not pass untrusted user input.
38-
- A toast auto-dismisses after ~6.6s and is also click-to-dismiss. Its container and styles carry `save-remove`/`snapshot-remove`, so they never reach a saved file.
38+
- A toast auto-dismisses after ~6.6s and is also click-to-dismiss. Its container and styles use the legacy `save-remove` and `snapshot-remove` aliases for `no-save` and `no-snapshot`, so they never reach a saved file.
3939

4040
## toastPersistent
4141

‎src/core/host-attrs.js‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,32 @@
1212
* answerable by a single diff.
1313
*/
1414

15-
import { SAVE_TOKEN_ATTRS } from "../utilities/root-attrs.js";
15+
import { SAVE_TOKEN_ATTRS, LEGACY_SAVE_TOKEN_ATTRS } from "../utilities/root-attrs.js";
16+
17+
let warnedAboutLegacyToken = false;
18+
19+
/**
20+
* Say so, once, when this response carries only the pre-rename save token.
21+
*
22+
* Dropping the old spelling is a deliberate break (see root-attrs.js), and its failure
23+
* mode is the kind worth spending five lines on: the host that serves the old name also
24+
* sets the edit-mode cookie, so the page stays editable and every save 404s. Without
25+
* this the reader sees a working page that quietly keeps nothing.
26+
*/
27+
function warnAboutLegacyToken() {
28+
if (warnedAboutLegacyToken) return;
29+
const carries = LEGACY_SAVE_TOKEN_ATTRS.some(
30+
(attr) => document.documentElement.getAttribute(attr)
31+
);
32+
if (!carries) return;
33+
warnedAboutLegacyToken = true;
34+
console.warn(
35+
"[hyperclay] This page was served with the pre-1.9.0 save token (" +
36+
LEGACY_SAVE_TOKEN_ATTRS.join(", ") +
37+
"), which this version no longer accepts. Saving will fail until the host is " +
38+
"updated. If this is HTML Clay, upgrade it to 1.9.0 or newer."
39+
);
40+
}
1641

1742
/**
1843
* The per-document save token this response carries, or null.
@@ -28,5 +53,6 @@ export function saveToken() {
2853
const value = document.documentElement.getAttribute(attr);
2954
if (value) return value;
3055
}
56+
warnAboutLegacyToken();
3157
return null;
3258
}

‎src/core/savePageCore.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,12 @@ export function savePage(callback = () => {}) {
260260
credentials: target.credentials,
261261
signal: controller.signal,
262262
headers: {
263+
// Spec §3's name for the header that says which document this save is for.
264+
'Document-URL': window.location.href,
265+
// The older spelling of the same header. Stored customer documents hardcode it
266+
// and both Hyperclay hosts read Document-URL first and fall back to this one,
267+
// so sending both is what lets a spec-conforming third-party host accept a
268+
// save from this library without breaking the documents already out there.
263269
'Page-URL': window.location.href,
264270
'Save-Trigger': userDriven ? 'user' : 'auto'
265271
},
@@ -372,6 +378,12 @@ export function saveHtml(html, callback = () => {}, { replacesDocument = false }
372378
credentials: target.credentials,
373379
signal: controller.signal,
374380
headers: {
381+
// Spec §3's name for the header that says which document this save is for.
382+
'Document-URL': window.location.href,
383+
// The older spelling of the same header. Stored customer documents hardcode it
384+
// and both Hyperclay hosts read Document-URL first and fall back to this one,
385+
// so sending both is what lets a spec-conforming third-party host accept a
386+
// save from this library without breaking the documents already out there.
375387
'Page-URL': window.location.href,
376388
'Save-Trigger': userDriven ? 'user' : 'auto'
377389
},

0 commit comments

Comments
 (0)