Skip to content

Commit 53d2fce

Browse files
committed
refactor(react): AdapterContextRegister extension point; app-shell and designer declare ObjectStackAdapter (WIP)
Claude-Session: https://claude.ai/code/session_017sGTFTS9edirCTVBgQysK7 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3d5c4b3 commit 53d2fce

7 files changed

Lines changed: 347 additions & 10 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* The app shell's declaration of the adapter it installs into `AdapterCtx`.
3+
*
4+
* `@object-ui/react` types `AdapterCtx` / `useAdapter` by the protocol-level
5+
* `DataSource`, so the runtime does not depend on any one adapter
6+
* (objectstack#25917). This shell's `AdapterProvider` installs an
7+
* `ObjectStackAdapter`, and shell code reads its members beyond `DataSource`
8+
* (`getClient`, the access probes, the connection state), so the shell
9+
* declares that adapter here, in the package that already depends on it.
10+
*
11+
* Imported from this package's entry so the declaration rides its published
12+
* types: a host that mounts `AdapterProvider` reads the same adapter type.
13+
*/
14+
15+
import type { ObjectStackAdapter } from '@object-ui/data-objectstack';
16+
17+
declare module '@object-ui/react' {
18+
interface AdapterContextRegister {
19+
adapter: ObjectStackAdapter;
20+
}
21+
}
22+
23+
export {};

‎ui/packages/app-shell/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
// Components
99
export { AppShell } from './components/AppShell.js';
1010

11+
// The adapter this shell installs into `AdapterCtx`, declared for every
12+
// reader of `useAdapter` (see the module).
13+
import './adapter-context-register.js';
14+
1115
// Providers
1216
export { AdapterProvider, useAdapter } from './providers/AdapterProvider.js';
1317
export { MetadataProvider, useMetadata, useMetadataItem } from './providers/MetadataProvider.js';
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* The designer's declaration of the adapter its host installs into
3+
* `AdapterCtx`.
4+
*
5+
* `@object-ui/react` types `AdapterCtx` / `useAdapter` by the protocol-level
6+
* `DataSource`, so the runtime does not depend on any one adapter
7+
* (objectstack#25917). The designer's app pages read the ObjectStack client
8+
* (`getClient`), a member beyond `DataSource`, and run inside the ObjectStack
9+
* Console, whose shell installs an `ObjectStackAdapter`; so the designer
10+
* declares that adapter here, in the package that already depends on it.
11+
*/
12+
13+
import type { ObjectStackAdapter } from '@object-ui/data-objectstack';
14+
15+
declare module '@object-ui/react' {
16+
interface AdapterContextRegister {
17+
adapter: ObjectStackAdapter;
18+
}
19+
}
20+
21+
export {};

‎ui/packages/react/README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,30 @@ function MyComponent() {
180180
}
181181
```
182182

183+
### useAdapter / AdapterCtx / AdapterContextRegister
184+
185+
`useAdapter()` reads the host's data adapter from `AdapterCtx`. Both are typed
186+
by the protocol-level `DataSource` from `@object-ui/types`, so this package
187+
depends on no adapter package, and a bring-your-own backend learns at the type
188+
level which members it lacks.
189+
190+
A host whose provider installs a concrete adapter, and whose code reads members
191+
beyond `DataSource`, declares that adapter once, in its own package:
192+
193+
```ts
194+
import type { ObjectStackAdapter } from '@object-ui/data-objectstack'
195+
196+
declare module '@object-ui/react' {
197+
interface AdapterContextRegister {
198+
adapter: ObjectStackAdapter
199+
}
200+
}
201+
```
202+
203+
`useAdapter()` then returns `ObjectStackAdapter | null`, and an
204+
`AdapterCtx.Provider` value is checked against it. `@object-ui/app-shell` ships
205+
this declaration, so a host that mounts its `AdapterProvider` already has it.
206+
183207
### useElementDataSourceSchema / ElementDataSourceGate
184208

185209
Consume `PageComponentSchema.dataSource` — the spec's per-element data binding

‎ui/packages/react/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
},
3333
"dependencies": {
3434
"@object-ui/core": "workspace:*",
35-
"@object-ui/data-objectstack": "workspace:*",
3635
"@object-ui/i18n": "workspace:*",
3736
"@object-ui/types": "workspace:*",
3837
"@objectstack/spec": "workspace:^"
@@ -42,6 +41,7 @@
4241
"react-dom": "^19.0.0"
4342
},
4443
"devDependencies": {
44+
"@object-ui/data-objectstack": "workspace:*",
4545
"@object-ui/test-support": "workspace:*",
4646
"@types/react": "19.3.0",
4747
"@types/react-dom": "19.3.0",

‎ui/packages/react/src/context/AppShellContext.tsx‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,43 @@ import type { DataSource } from '@object-ui/types';
66
// ---------------------------------------------------------------------------
77

88
/**
9-
* The host's data adapter, typed by the protocol-level `DataSource` interface
10-
* from `@object-ui/types` — never by one concrete adapter (AGENTS #1: inject a
11-
* `DataSource`, don't hard-code a backend). The runtime therefore installs
12-
* without any adapter package, and a bring-your-own backend learns at the
13-
* type level which members it is missing, not at runtime.
9+
* Where a host declares the concrete adapter it puts into {@link AdapterCtx}.
1410
*
15-
* A host that provides a concrete adapter and reads members beyond
16-
* `DataSource` narrows in its own package, where it depends on that adapter.
11+
* The runtime types the context by the protocol-level `DataSource` interface
12+
* from `@object-ui/types`, never by one concrete adapter (AGENTS #1: inject a
13+
* `DataSource`, don't hard-code a backend). So `@object-ui/react` installs
14+
* without any adapter package, and a bring-your-own backend learns at the type
15+
* level which members it lacks instead of at runtime.
16+
*
17+
* A host whose provider installs a concrete adapter, and whose own code reads
18+
* members beyond `DataSource`, declares that adapter here by module
19+
* augmentation, in its own package, which already depends on the adapter:
20+
*
21+
* ```ts
22+
* import type { ObjectStackAdapter } from '@object-ui/data-objectstack';
23+
* declare module '@object-ui/react' {
24+
* interface AdapterContextRegister { adapter: ObjectStackAdapter }
25+
* }
26+
* ```
27+
*
28+
* The augmentation is the host's claim about what its provider installs; the
29+
* `AdapterCtx.Provider` value is then checked against the declared type.
1730
*/
18-
export const AdapterCtx = createContext<DataSource | null>(null);
31+
// Deliberately empty: an EXTENSION POINT that hosts fill by augmentation.
32+
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- see above
33+
export interface AdapterContextRegister {}
34+
35+
/**
36+
* The adapter type {@link AdapterCtx} carries: the host's declared adapter
37+
* when {@link AdapterContextRegister} names one, otherwise `DataSource`.
38+
*/
39+
export type ContextAdapter = AdapterContextRegister extends { adapter: infer A extends DataSource }
40+
? A
41+
: DataSource;
42+
43+
export const AdapterCtx = createContext<ContextAdapter | null>(null);
1944

20-
export function useAdapter(): DataSource | null {
45+
export function useAdapter(): ContextAdapter | null {
2146
return useContext(AdapterCtx);
2247
}
2348

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* `AdapterCtx` / `useAdapter` are typed by the protocol-level `DataSource`,
11+
* and a host widens them only by declaring its adapter on
12+
* `AdapterContextRegister` (objectstack#25917).
13+
*
14+
* ## What this pins, and why only the compiler can see it
15+
*
16+
* Both used to be typed by `ObjectStackAdapter`, which made the runtime depend
17+
* on `@object-ui/data-objectstack`, and gave every reader the ObjectStack-only
18+
* members (`getClient`, the access probes) whether or not its host installed
19+
* that adapter. Which reads the compiler refuses is erased before any runtime
20+
* assertion could run, so the gauge is `tsc`, driven here with the same
21+
* harness as `SchemaRendererContext.dataSourceType.pin.test.ts`.
22+
*
23+
* Two programs over the SAME cases-by-line source shape:
24+
*
25+
* - UNDECLARED: no augmentation. A reader reaches `DataSource` members and is
26+
* refused the ObjectStack-only ones; a provider may install any
27+
* `DataSource`. Reverting the context to `ObjectStackAdapter` turns the
28+
* refused `getClient` / `probeAppAccess` rows green and this file red.
29+
* - DECLARED: the virtual module augments `AdapterContextRegister` with a host
30+
* adapter that extends `DataSource`. The reader now reaches that adapter's
31+
* extra member, and the provider's value is checked against it — a bare
32+
* `DataSource` is refused there.
33+
*
34+
* ## Resolution guard
35+
*
36+
* The context resolves from its SOURCE path and `@object-ui/types` through
37+
* `paths`, not `dist`. The CONTROL rows are refusals unrelated to the adapter
38+
* type (`DataSource` declares `getObjectSchema` as required; a context value
39+
* cannot be a string), so a harness that degrades to `any` fires them. A
40+
* diagnostic in the virtual module's import header throws instead of reading
41+
* as a verdict.
42+
*
43+
* Cost note (ui/AGENTS.md 测试纪律): both programs are built at MODULE SCOPE,
44+
* so the compiler work lands in the import phase, which no test or hook
45+
* timeout bounds.
46+
*/
47+
48+
import { describe, it, expect } from 'vitest';
49+
import ts from 'typescript';
50+
import { fileURLToPath } from 'node:url';
51+
import { dirname, join, resolve } from 'node:path';
52+
53+
const HERE = dirname(fileURLToPath(import.meta.url));
54+
// __tests__ → context → src → react → packages → repo root
55+
const REPO_ROOT = resolve(HERE, '..', '..', '..', '..', '..');
56+
/** The seam under test, by SOURCE path — no `dist`, no barrel. */
57+
const CONTEXT_IMPORT = join(HERE, '..', 'AppShellContext').replace(/\\/g, '/');
58+
59+
/**
60+
* One assignment or read, and whether `tsc` must refuse it.
61+
* `code` emits EXACTLY one line — the line index is how a diagnostic is
62+
* attributed back to a case.
63+
*/
64+
interface Case {
65+
readonly what: string;
66+
readonly code: string;
67+
readonly refused: boolean;
68+
}
69+
70+
/** The adapter as a READER reaches it. */
71+
const READ = `(undefined as unknown as ReturnType<typeof useAdapter>)!`;
72+
/** The type a PROVIDER's `value` is checked against. */
73+
const PROVIDED = `React.ContextType<typeof AdapterCtx>`;
74+
/** A complete protocol-level adapter. */
75+
const ADAPTER = `(undefined as unknown as DataSource)`;
76+
77+
const UNDECLARED: readonly Case[] = [
78+
{
79+
what: 'a reader reaches a DataSource member (`find`) with no cast',
80+
code: `const c: DataSource['find'] = ${READ}.find;`,
81+
refused: false,
82+
},
83+
{
84+
what: 'a reader reaches `getObjectSchema`, which DataSource declares',
85+
code: `const c: DataSource['getObjectSchema'] = ${READ}.getObjectSchema;`,
86+
refused: false,
87+
},
88+
{
89+
what: 'a provider may install any DataSource, with no cast',
90+
code: `const c: ${PROVIDED} = ${ADAPTER};`,
91+
refused: false,
92+
},
93+
{
94+
what: 'a provider with no adapter yet may say so with `null`',
95+
code: `const c: ${PROVIDED} = null;`,
96+
refused: false,
97+
},
98+
{
99+
what: 'NARROWED `getClient` is not a DataSource member: refused with no host declaration',
100+
code: `const c = ${READ}.getClient;`,
101+
refused: true,
102+
},
103+
{
104+
what: 'NARROWED `probeAppAccess` is not a DataSource member: refused with no host declaration',
105+
code: `const c = ${READ}.probeAppAccess;`,
106+
refused: true,
107+
},
108+
{
109+
what: 'CONTROL `DataSource` really declares `getObjectSchema` as REQUIRED',
110+
code: `const c: DataSource = { find: (undefined as any), findOne: (undefined as any), create: (undefined as any), update: (undefined as any), delete: (undefined as any) };`,
111+
refused: true,
112+
},
113+
{
114+
what: 'CONTROL a context value cannot be a string',
115+
code: `const c: ${PROVIDED} = 'not-an-adapter';`,
116+
refused: true,
117+
},
118+
];
119+
120+
const DECLARED: readonly Case[] = [
121+
{
122+
what: "a reader reaches the declared host adapter's own member",
123+
code: `const c: () => string = ${READ}.hostOnly;`,
124+
refused: false,
125+
},
126+
{
127+
what: 'a reader still reaches DataSource members',
128+
code: `const c: DataSource['find'] = ${READ}.find;`,
129+
refused: false,
130+
},
131+
{
132+
what: 'a provider may install the declared host adapter',
133+
code: `const c: ${PROVIDED} = (undefined as unknown as HostAdapter);`,
134+
refused: false,
135+
},
136+
{
137+
what: 'a provider value is checked against the declared adapter: a bare DataSource is refused',
138+
code: `const c: ${PROVIDED} = ${ADAPTER};`,
139+
refused: true,
140+
},
141+
{
142+
what: 'CONTROL a member neither type declares is still refused',
143+
code: `const c = ${READ}.notAMember;`,
144+
refused: true,
145+
},
146+
];
147+
148+
function header(declared: boolean): string {
149+
return [
150+
`import type React from 'react';`,
151+
`import type { DataSource } from '@object-ui/types';`,
152+
`import type { AdapterCtx, useAdapter } from '${CONTEXT_IMPORT}';`,
153+
`type _Used = [DataSource, typeof AdapterCtx, typeof useAdapter, React.ReactNode];`,
154+
`interface HostAdapter extends DataSource { hostOnly(): string }`,
155+
...(declared
156+
? [`declare module '${CONTEXT_IMPORT}' { interface AdapterContextRegister { adapter: HostAdapter } }`]
157+
: []),
158+
].join('\n');
159+
}
160+
161+
/**
162+
* Compile one program and return the set of case indices that produced a
163+
* diagnostic. `paths` mirrors the repo root `tsconfig.json` (see the header).
164+
*/
165+
function erroringCases(cases: readonly Case[], declared: boolean): Set<number> {
166+
const head = `${header(declared)}\n`;
167+
// One BLOCK per case so the `const c` declarations do not collide.
168+
const body = cases.map((c) => `{ ${c.code} }`).join('\n');
169+
const source = `${head}${body}\n`;
170+
const headerLines = head.split('\n').length - 1;
171+
172+
const VIRTUAL = join(HERE, `__adapterCtxPins.${declared ? 'declared' : 'undeclared'}.virtual.ts`).replace(/\\/g, '/');
173+
const options: ts.CompilerOptions = {
174+
strict: true,
175+
skipLibCheck: true,
176+
noEmit: true,
177+
jsx: ts.JsxEmit.ReactJSX,
178+
moduleResolution: ts.ModuleResolutionKind.Bundler,
179+
module: ts.ModuleKind.ESNext,
180+
target: ts.ScriptTarget.ESNext,
181+
baseUrl: REPO_ROOT,
182+
paths: {
183+
'@object-ui/types': ['packages/types/src'],
184+
'@object-ui/types/*': ['packages/types/src/*'],
185+
'@object-ui/core': ['packages/core/src'],
186+
'@object-ui/core/*': ['packages/core/src/*'],
187+
},
188+
};
189+
const host = ts.createCompilerHost(options);
190+
const getSourceFile = host.getSourceFile.bind(host);
191+
host.getSourceFile = (fileName, languageVersion, ...rest) =>
192+
fileName === VIRTUAL
193+
? ts.createSourceFile(fileName, source, languageVersion, true)
194+
: getSourceFile(fileName, languageVersion, ...rest);
195+
const fileExists = host.fileExists.bind(host);
196+
host.fileExists = (fileName) => (fileName === VIRTUAL ? true : fileExists(fileName));
197+
const readFile = host.readFile.bind(host);
198+
host.readFile = (fileName) => (fileName === VIRTUAL ? source : readFile(fileName));
199+
200+
const program = ts.createProgram([VIRTUAL], options, host);
201+
const sf = program.getSourceFile(VIRTUAL);
202+
if (!sf) throw new Error('virtual source file was not added to the program');
203+
204+
const hit = new Set<number>();
205+
for (const d of [...program.getSemanticDiagnostics(sf), ...program.getSyntacticDiagnostics(sf)]) {
206+
if (d.start == null) continue;
207+
const index = sf.getLineAndCharacterOfPosition(d.start).line - headerLines;
208+
if (index < 0) {
209+
throw new Error(
210+
'the pin harness failed to resolve its own imports — this is a setup failure, not a ' +
211+
`verdict about \`AdapterCtx\`: ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`,
212+
);
213+
}
214+
hit.add(index);
215+
}
216+
return hit;
217+
}
218+
219+
// Module scope on purpose — see the file header.
220+
const refusedUndeclared = erroringCases(UNDECLARED, false);
221+
const refusedDeclared = erroringCases(DECLARED, true);
222+
223+
describe('`AdapterCtx` is typed by DataSource unless a host declares its adapter (objectstack#25917)', () => {
224+
describe('no host declaration', () => {
225+
for (const [i, c] of UNDECLARED.entries()) {
226+
it(c.what, () => {
227+
expect({ case: c.what, refused: refusedUndeclared.has(i) })
228+
.toEqual({ case: c.what, refused: c.refused });
229+
});
230+
}
231+
});
232+
describe('a host declares its adapter on `AdapterContextRegister`', () => {
233+
for (const [i, c] of DECLARED.entries()) {
234+
it(c.what, () => {
235+
expect({ case: c.what, refused: refusedDeclared.has(i) })
236+
.toEqual({ case: c.what, refused: c.refused });
237+
});
238+
}
239+
});
240+
});

0 commit comments

Comments
 (0)