Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wrapped-value-brand.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fetchium': patch
---

Brand formatted values and live collection bindings with a shared base class instead of adding every instance to a `WeakSet`.
17 changes: 4 additions & 13 deletions packages/fetchium/src/EntityInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,22 @@ import { Entity } from './proxy.js';
import { PROXY_ID } from './proxyId.js';
import { NESTED_WRAPPERS } from './nestedNotifiers.js';
import type { QueryClient } from './QueryClient.js';
import { ValidatorDef, WRAPPED_VALUE } from './typeDefs.js';
import { ValidatorDef, WrappedValue } from './typeDefs.js';
import type { LiveCollectionBinding } from './LiveCollection.js';
import { entitySatisfiesShape } from './parseEntities.js';

// ======================================================
// Nested proxy wrapping — transparently unwraps WRAPPED_VALUE items
// Nested proxy wrapping — transparently unwraps WrappedValue items
// (FormattedValue, LiveCollectionBinding) inside plain objects and arrays.
// ======================================================

const ObjectProto = Object.prototype;
const nestedWrappers = NESTED_WRAPPERS;

/** A `WRAPPED_VALUE` item. A live collection's value changes under its own notifier. */
interface WrappedValue {
getValue(): unknown;
readonly _valueOwner?: Notifier;
}

/** `owner` is the live collection's notifier. Unowned wrappers consume nothing, and merges replace them. */
function wrapValue(value: unknown, owner: Notifier | undefined): unknown {
if (typeof value !== 'object' || value === null) return value;
if (WRAPPED_VALUE.has(value)) {
const wrapped = value as WrappedValue;
return wrapValue(wrapped.getValue(), wrapped._valueOwner ?? owner);
}
if (value instanceof WrappedValue) return wrapValue(value.getValue(), value._valueOwner ?? owner);
if (PROXY_ID.has(value as object)) return value;

if (Array.isArray(value)) {
Expand Down Expand Up @@ -245,7 +236,7 @@ function asPrevObject(prev: unknown): Record<string, unknown> | undefined {
/** Mirrors Signalium's unexported array and object walks. A test asserts they match. */
function snapshotRawValue(value: unknown, prev: unknown, snap: SnapshotFn): unknown {
if (value === null || typeof value !== 'object') return value;
if (WRAPPED_VALUE.has(value)) return snapshotRawValue((value as { getValue(): unknown }).getValue(), prev, snap);
if (value instanceof WrappedValue) return snapshotRawValue(value.getValue(), prev, snap);
if (PROXY_ID.has(value)) return snap(value, prev);

if (Array.isArray(value)) {
Expand Down
7 changes: 3 additions & 4 deletions packages/fetchium/src/LiveCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
type FieldPath,
buildFieldPaths,
} from './ConstraintMatcher.js';
import { ValidatorDef, WRAPPED_VALUE } from './typeDefs.js';
import { ValidatorDef, WrappedValue } from './typeDefs.js';

/**
* Pick the def matching the entity's variant tag. Returns a single
Expand Down Expand Up @@ -93,7 +93,7 @@ export interface LiveInstance {
// LiveCollectionBinding — shared wrapper for constraint routing
// ======================================================

export class LiveCollectionBinding {
export class LiveCollectionBinding extends WrappedValue {
_queryClient: QueryClient;
_parent: LiveCollectionParent;
_constraintHashes: Map<string, number>;
Expand All @@ -111,6 +111,7 @@ export class LiveCollectionBinding {
constraintHashes: Map<string, number>,
instance: LiveInstance,
) {
super();
this._queryClient = queryClient;
this._parent = parent;
this._constraintHashes = constraintHashes;
Expand All @@ -129,8 +130,6 @@ export class LiveCollectionBinding {
}
}
}

WRAPPED_VALUE.add(this);
}

getValue(): unknown {
Expand Down
39 changes: 39 additions & 0 deletions packages/fetchium/src/__tests__/wrapped-value-brand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { describe, it, expect, vi } from 'vitest';
import { t } from '../typeDefs.js';
import { Entity } from '../proxy.js';
import { RESTQuery } from '../rest/index.js';
import { fetchQuery } from '../query.js';
import { testWithClient, setupTestClient } from './utils.js';

describe('Formatted values', () => {
const getClient = setupTestClient();

// Hermes walks every WeakSet entry on each young GC, and a list of formatted fields makes one value per field.
it('read through without registering each value in a WeakSet', async () => {
const { client, mockFetch } = getClient();
class Event extends Entity {
__typename = t.typename('Event');
id = t.id;
day = t.format('date');
}
mockFetch.get('/events', {
events: Array.from({ length: 5 }, (_, id) => ({ __typename: 'Event', id, day: `2024-01-1${id}` })),
});

const add = vi.spyOn(WeakSet.prototype, 'add');
try {
await testWithClient(client, async () => {
class GetEvents extends RESTQuery {
path = '/events';
result = { events: t.array(t.entity(Event)) };
}
const relay = fetchQuery(GetEvents);
await relay;
expect(relay.value!.events.map(event => event.day.getUTCDate())).toEqual([10, 11, 12, 13, 14]);
});
expect(add.mock.calls.filter(([value]) => value?.constructor?.name === 'FormattedValue')).toHaveLength(0);
} finally {
add.mockRestore();
}
});
});
12 changes: 9 additions & 3 deletions packages/fetchium/src/typeDefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from './types.js';
import { Prettify } from './type-utils.js';
import { hashValue, registerCustomHash } from 'signalium/utils';
import type { Notifier } from 'signalium';

const entries = Object.entries;
const isArray = Array.isArray;
Expand Down Expand Up @@ -802,15 +803,21 @@ const FORMAT_SERIALIZERS: ((value: unknown) => unknown)[] = [];
const FORMAT_MAP = new Map<string, number>();
const FORMAT_ID_TO_NAME: Map<number, string> | undefined = IS_DEV ? new Map<number, string>() : undefined;

export const WRAPPED_VALUE = new WeakSet();
/** A value read through `getValue()`: a formatted value or a live collection binding. */
export abstract class WrappedValue {
/** A live collection's value changes under its own notifier. */
declare readonly _valueOwner?: Notifier;
abstract getValue(): unknown;
}

export class FormattedValue {
export class FormattedValue extends WrappedValue {
_raw: unknown;
private _formatted: unknown;
private _parsed: boolean;
private _formatId: number;

constructor(raw: unknown, formatId: number, eager: boolean) {
super();
this._raw = raw;
this._formatId = formatId;
if (eager) {
Expand All @@ -819,7 +826,6 @@ export class FormattedValue {
} else {
this._parsed = false;
}
WRAPPED_VALUE.add(this);
}

getValue(): unknown {
Expand Down
Loading