Skip to content

Commit 3182a36

Browse files
authored
Enforce completion owners for public type aliases (#350)
## Summary - validate that public `Foo.t` aliases have `@editor.completeFrom(Foo)` on their internal backing types - correct the existing completion owners and the `Element.Impl.setAttributeNS` receiver type - add compile-time coverage for recursive DOM aliases and inherited element methods ## Why Public modules expose internal record types through aliases. Several backing types either had a stale completion owner or no annotation, so editor completions could point at the internal module instead of the public API. The feature validator now enforces this relationship for future aliases while excluding intentional public-to-public `t` aliases. This addresses the first follow-up item in #342. ## Validation - `npm run build` - `npm run check:features` - `npm test` - `npm run format:check` - `git diff --check`
1 parent 04b37c0 commit 3182a36

16 files changed

Lines changed: 165 additions & 34 deletions

‎package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@
3838
"scripts": {
3939
"test": "node tests/index.js",
4040
"build": "rescript",
41-
"check:features": "node scripts/check-features.mjs",
42-
"format": "rescript format && oxfmt ./tests/index.js ./scripts/check-features.mjs ./package.json ./docs && prettier --write ./docs/pages",
43-
"format:check": "rescript format --check && oxfmt ./tests/index.js ./scripts/check-features.mjs ./package.json ./docs --check && prettier --check ./docs/pages",
41+
"check:features": "node --test scripts/check-features.test.mjs && node scripts/check-features.mjs",
42+
"format": "rescript format && oxfmt ./tests/index.js ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./package.json ./docs && prettier --write ./docs/pages",
43+
"format:check": "rescript format --check && oxfmt ./tests/index.js ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./package.json ./docs --check && prettier --check ./docs/pages",
4444
"docs": "astro dev",
4545
"prebuild:docs": "node docs/llm.js",
4646
"build:docs": "astro build"

‎scripts/check-features.mjs‎

Lines changed: 116 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import path from "node:path";
33
import { spawnSync } from "node:child_process";
44
import { fileURLToPath } from "node:url";
55

6-
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
6+
const scriptPath = fileURLToPath(import.meta.url);
7+
const repoRoot = path.resolve(path.dirname(scriptPath), "..");
78
const configPath = path.join(repoRoot, "rescript.json");
89

910
const expectedFeatureOwners = new Map([
@@ -43,6 +44,57 @@ const uniqueDuplicates = (values) => [
4344
const sameMembers = (left, right) =>
4445
left.length === right.length && left.every((value) => right.includes(value));
4546

47+
const publicModulesFrom = (sourceEntries) =>
48+
sourceEntries.flatMap((source) =>
49+
(source.public ?? []).map((moduleName) => ({ moduleName, sourceDir: source.dir })),
50+
);
51+
52+
const readSource = (filePath) => {
53+
try {
54+
return { _tag: "Success", value: readFileSync(filePath, "utf8") };
55+
} catch (error) {
56+
return {
57+
_tag: "Failure",
58+
message: error instanceof Error ? error.message : String(error),
59+
};
60+
}
61+
};
62+
63+
// Only direct `Foo.t = BackingModule.backingType` aliases, with or without type parameters,
64+
// expose an internal type whose editor completion owner needs validation.
65+
export const parsePublicTypeAlias = (source) => {
66+
const match =
67+
/^type t(?:<[^>\r\n]+>)?[ \t]*=[ \t]*([A-Z][A-Za-z0-9_]*)\.([A-Za-z][A-Za-z0-9_]*)\b/m.exec(
68+
source,
69+
);
70+
return match === null ? null : { backingModule: match[1], backingType: match[2] };
71+
};
72+
73+
// Public-to-public `Foo.t = Bar.t` re-exports keep Bar as the completion owner. Requiring
74+
// the backing type to point at both public modules would make these valid aliases conflict.
75+
const isPublicToPublicAlias = (alias, publicModuleNames) =>
76+
alias.backingType === "t" && publicModuleNames.has(alias.backingModule);
77+
78+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
79+
80+
// Match the annotation attached to the backing declaration so an unrelated annotation
81+
// elsewhere in the source file cannot satisfy the check.
82+
const completionOwnerFor = (source, backingType) => {
83+
const escapedType = escapeRegExp(backingType);
84+
const attributes = String.raw`(?:[ \t]+@[A-Za-z][A-Za-z0-9_.]*(?:\([^\r\n)]*\))?)*`;
85+
const declaration = String.raw`(?:type(?:[ \t]+rec)?|and)[ \t]+${escapedType}\b`;
86+
const pattern = new RegExp(
87+
String.raw`@editor\.completeFrom\(([^)]+)\)${attributes}[ \t]*(?:\r?\n[ \t]*)?${declaration}`,
88+
"m",
89+
);
90+
return pattern.exec(source)?.[1] ?? null;
91+
};
92+
93+
const modulePathFor = (sourceEntries, moduleName) =>
94+
sourceEntries
95+
.map((source) => path.join(repoRoot, source.dir, `${moduleName}.res`))
96+
.find(existsSync);
97+
4698
const readConfig = () => {
4799
try {
48100
return { _tag: "Success", value: JSON.parse(readFileSync(configPath, "utf8")) };
@@ -110,9 +162,7 @@ const validateFeatureOwners = (featureEntries, sourceEntries) => {
110162
};
111163

112164
const validatePublicModules = (sourceEntries) => {
113-
const publicModules = sourceEntries.flatMap((source) =>
114-
(source.public ?? []).map((moduleName) => ({ moduleName, sourceDir: source.dir })),
115-
);
165+
const publicModules = publicModulesFrom(sourceEntries);
116166
const duplicateModules = uniqueDuplicates(publicModules.map(({ moduleName }) => moduleName));
117167
const missingModules = publicModules
118168
.filter(
@@ -131,6 +181,48 @@ const validatePublicModules = (sourceEntries) => {
131181
];
132182
};
133183

184+
// Internal backing types must complete from their public module. This keeps editor suggestions
185+
// on `Foo` instead of leaking implementation modules such as DOMTree or *Types modules.
186+
const validateCompletionAlias = (publicModule, sourceEntries, publicModuleNames) => {
187+
const publicPath = path.join(repoRoot, publicModule.sourceDir, `${publicModule.moduleName}.res`);
188+
const publicSource = readSource(publicPath);
189+
if (publicSource._tag === "Failure") {
190+
return [`Unable to read ${publicPath}: ${publicSource.message}`];
191+
}
192+
193+
const alias = parsePublicTypeAlias(publicSource.value);
194+
if (alias === null || isPublicToPublicAlias(alias, publicModuleNames)) {
195+
return [];
196+
}
197+
198+
const backingPath = modulePathFor(sourceEntries, alias.backingModule);
199+
if (backingPath === undefined) {
200+
return [
201+
`Unable to resolve backing module ${alias.backingModule} for ${publicModule.moduleName}.t.`,
202+
];
203+
}
204+
205+
const backingSource = readSource(backingPath);
206+
if (backingSource._tag === "Failure") {
207+
return [`Unable to read ${backingPath}: ${backingSource.message}`];
208+
}
209+
210+
const actualOwner = completionOwnerFor(backingSource.value, alias.backingType);
211+
return actualOwner === publicModule.moduleName
212+
? []
213+
: [
214+
`${alias.backingModule}.${alias.backingType}, aliased by ${publicModule.moduleName}.t, must use @editor.completeFrom(${publicModule.moduleName}); received ${actualOwner ?? "no annotation"}.`,
215+
];
216+
};
217+
218+
const validateCompletionAliases = (sourceEntries) => {
219+
const publicModules = publicModulesFrom(sourceEntries);
220+
const publicModuleNames = new Set(publicModules.map(({ moduleName }) => moduleName));
221+
return publicModules.flatMap((publicModule) =>
222+
validateCompletionAlias(publicModule, sourceEntries, publicModuleNames),
223+
);
224+
};
225+
134226
const validateConfig = (config) => {
135227
const featureEntries = Object.entries(config.features ?? {});
136228
const sourceEntries = (config.sources ?? []).filter(
@@ -142,6 +234,7 @@ const validateConfig = (config) => {
142234
...validateSources(sourceEntries),
143235
...validateFeatureOwners(featureEntries, sourceEntries),
144236
...validatePublicModules(sourceEntries),
237+
...validateCompletionAliases(sourceEntries),
145238
];
146239
};
147240

@@ -170,25 +263,27 @@ const compileFeature = (featureName) => {
170263
: { _tag: "Failure", message: formatProcessFailure(featureName, "build", buildResult) };
171264
};
172265

173-
const configResult = readConfig();
174-
if (configResult._tag === "Failure") {
175-
console.error(`Unable to read rescript.json: ${configResult.message}`);
176-
process.exit(1);
177-
}
266+
if (process.argv[1] !== undefined && path.resolve(process.argv[1]) === scriptPath) {
267+
const configResult = readConfig();
268+
if (configResult._tag === "Failure") {
269+
console.error(`Unable to read rescript.json: ${configResult.message}`);
270+
process.exit(1);
271+
}
178272

179-
const validationErrors = validateConfig(configResult.value);
180-
if (validationErrors.length > 0) {
181-
console.error(validationErrors.join("\n\n"));
182-
process.exit(1);
183-
}
273+
const validationErrors = validateConfig(configResult.value);
274+
if (validationErrors.length > 0) {
275+
console.error(validationErrors.join("\n\n"));
276+
process.exit(1);
277+
}
184278

185-
console.log(`Validated ${expectedFeatureOwners.size} public feature definitions.`);
279+
console.log(`Validated ${expectedFeatureOwners.size} public feature definitions.`);
186280

187-
for (const featureName of expectedFeatureOwners.keys()) {
188-
const result = compileFeature(featureName);
189-
if (result._tag === "Failure") {
190-
console.error(result.message);
191-
process.exit(1);
281+
for (const featureName of expectedFeatureOwners.keys()) {
282+
const result = compileFeature(featureName);
283+
if (result._tag === "Failure") {
284+
console.error(result.message);
285+
process.exit(1);
286+
}
287+
console.log(`[ok] ${featureName}`);
192288
}
193-
console.log(`[ok] ${featureName}`);
194289
}

‎scripts/check-features.test.mjs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import { parsePublicTypeAlias } from "./check-features.mjs";
5+
6+
test("parses a public type alias without type parameters", () => {
7+
assert.deepEqual(parsePublicTypeAlias("type t = DOMTree.element"), {
8+
backingModule: "DOMTree",
9+
backingType: "element",
10+
});
11+
});
12+
13+
test("parses a public type alias with type parameters", () => {
14+
assert.deepEqual(parsePublicTypeAlias("type t<'r> = FileTypes.readableStream<'r>"), {
15+
backingModule: "FileTypes",
16+
backingType: "readableStream",
17+
});
18+
});

‎src/core/DOM.res‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ type document = private {}
1010
An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
1111
[See DOMException on MDN](https://developer.mozilla.org/docs/Web/API/DOMException)
1212
*/
13+
@editor.completeFrom(DOMException)
1314
type domException = {
1415
/**
1516
[Read more on MDN](https://developer.mozilla.org/docs/Web/API/DOMException/name)
@@ -25,6 +26,7 @@ type domException = {
2526
A type returned by some APIs which contains a list of DOMString (strings).
2627
[See DOMStringList on MDN](https://developer.mozilla.org/docs/Web/API/DOMStringList)
2728
*/
29+
@editor.completeFrom(DOMStringList)
2830
type domStringList = {
2931
/**
3032
Returns the number of strings in strings.

‎src/device/WebMidiTypes.res‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type midiOutputMap = {}
1313
/**
1414
[See MIDIAccess on MDN](https://developer.mozilla.org/docs/Web/API/MIDIAccess)
1515
*/
16+
@editor.completeFrom(WebMIDI)
1617
type midiAccess = {
1718
...DOM.eventTarget,
1819
/**

‎src/dom-nodes/DOMTree.res‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1302,7 +1302,7 @@ TODO: mark as private once mutating fields of private records is allowed
13021302
length: int,
13031303
}
13041304

1305-
@editor.completeFrom(htmlFormControlsCollection)
1305+
@editor.completeFrom(HTMLFormControlsCollection)
13061306
and htmlFormControlsCollection = {
13071307
length: int,
13081308
}
@@ -1602,6 +1602,7 @@ and htmlSlotElement = {
16021602
mutable name: string,
16031603
}
16041604

1605+
@editor.completeFrom(ElementInternals)
16051606
and elementInternals = {
16061607
shadowRoot: Null.t<shadowRoot>,
16071608
form: Null.t<htmlFormElement>,

‎src/dom-nodes/Element.res‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ Sets the value of element's attribute whose namespace is namespace and local nam
475475
*/
476476
@send
477477
external setAttributeNS: (
478-
DOMTree.element,
478+
T.t,
479479
~namespace: string,
480480
~qualifiedName: string,
481481
~value: string,

‎src/file/FileTypes.res‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ type blob = DOM.blob = private {
3636
This Streams API interface represents a readable stream of byte data. The WebApiFetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
3737
[See ReadableStream on MDN](https://developer.mozilla.org/docs/Web/API/ReadableStream)
3838
*/
39+
@editor.completeFrom(ReadableStream)
3940
type readableStream<'r> = {
4041
/**
4142
[Read more on MDN](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)
@@ -70,7 +71,7 @@ type writableStreamDefaultController = private {
7071
Provides information about files and allows JavaScript in a web page to access their content.
7172
[See WebApiFile on MDN](https://developer.mozilla.org/docs/Web/API/File)
7273
*/
73-
@editor.completeFrom(WebApiFile)
74+
@editor.completeFrom(File)
7475
type file = DOM.file = private {
7576
...blob,
7677
/**

‎src/media/MediaSessionTypes.res‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ type mediaMetadata = {
5050
[See WebApiMediaSession on MDN](https://developer.mozilla.org/docs/Web/API/MediaSession)
5151
TODO: mark as private once mutating fields of private records is allowed
5252
*/
53-
@editor.completeFrom(WebApiMediaSession)
53+
@editor.completeFrom(MediaSession)
5454
type mediaSession = {
5555
/**
5656
[Read more on MDN](https://developer.mozilla.org/docs/Web/API/MediaSession/metadata)

‎src/media/PictureInPictureTypes.res‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
/**
44
[See PictureInPictureWindow on MDN](https://developer.mozilla.org/docs/Web/API/PictureInPictureWindow)
55
*/
6+
@editor.completeFrom(PictureInPicture)
67
type pictureInPictureWindow = {
78
...DOM.eventTarget,
89
/**

0 commit comments

Comments
 (0)