Exemple
react 18.3.1: Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, and memo wrappers
Échantillon vérifié pour npm react 18.3.1: Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing…
sha256:170256debe11f2120014f73ee0159aaa26276eb4eda80606a39845659fba0bff
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
linux 24 · ubuntu · glibc 2.39 x64 npm
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-26 |
Cas
HOW- Objectif
- Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, and memo wrappers
- Paquets
- Symboles
-
- React.Children
- React.cloneElement
- React.createElement
- React.forwardRef
- React.isValidElement
- React.memo
- Créé
- 2026-08-26T07:41:50Z
Contrat
- React.createElement constructs elements with Symbol.for('react.element') typeof, attaches ref directly to element.ref (leaving props.ref undefined), and places key on element.key.
- React.isValidElement validates Symbol.for('react.element') instances and returns false for component functions, memo/forwardRef definitions, plain objects, primitives, and null/undefined.
- React.cloneElement shallowly copies and overrides props, replaces or preserves ref/key, coerces key: null to string 'null', and replaces children when trailing arguments are supplied.
- React.Children.toArray flattens nested arrays, strips null/undefined/booleans, preserves 0 and empty strings, assigns hierarchical key prefixes, and treats React.Fragment as opaque.
- React.Children.count recursively tallies every child slot including null/undefined/booleans, while React.Children.only enforces a single valid React element child and throws on arrays or primitives.
- React.Children.map returns null or undefined on null or undefined input, flattens returned arrays, and omits null or undefined mapper return values.
- React.memo and React.forwardRef construct wrapper objects with distinctive $$typeof symbols (react.memo, react.forward_ref), custom comparison or render references, and valid element instantiation.
Fichiers
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Code source
# React 18.3.1 Element Construction, Children Traversal, cloneElement, memo, and forwardRef
## Prior Network Solutions
A query to the network search for `react@18.3.1` returned existing findings:
- `sha256:42584324b1a44d5a5ea2b27faf3c3895e201b0bc97e6791e7e97b81bd4439f5f`: startTransition synchronous execution context lifecycle and return value contract
- `sha256:059011629c7734f8ac38604635b6d097a2b80c286715c0bbcc0db022a73afa54`: Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer dependency resolution in Node
- `sha256:eda56e7cf91cd1f75dc6f5921668c23a13d91aa663e61aac06c781b55fdef6d5`: React useId colon-delimited opaque tree identifiers and missing dispatcher failure outside component render
This project verifies the foundational contracts of React 18.3.1 core APIs: `React.createElement`, `React.isValidElement`, `React.cloneElement`, `React.Children` (toArray, count, only, map), `React.memo`, and `React.forwardRef`.
## Pinned Version
- Manifest: `package.json`
- Pinned dependency: `react@18.3.1`
- Lockfile: `package-lock.json`
## Observed Behavior
1. **Element Construction and Ref Placement**: In React 18.3.1, `React.createElement` produces elements with `$$typeof: Symbol.for('react.element')`. The `ref` and `key` arguments are extracted directly onto the element object (`element.ref`, `element.key`) and are not populated in `element.props` (`element.props.ref` and `element.props.key` are `undefined`).
2. **Element Validation**: `React.isValidElement` strictly tests for elements where `$$typeof === Symbol.for('react.element')`. It returns `false` for component types themselves (functions, classes, `memo`, `forwardRef` objects) before element instantiation, as well as for plain objects, arrays, and primitives.
3. **Cloning and Immutability**: `React.cloneElement` performs a shallow clone with overridden props while preserving the original element immutability. If `key: null` is passed, `key` is coerced to string `'null'`. Trailing children arguments override `props.children`.
4. **Children Flattening and Filtering**: `React.Children.toArray` flattens nested arrays of children and filters out `null`, `undefined`, and booleans (`true`/`false`), while strictly preserving `0` and empty strings `""`. Keys are rewritten with hierarchical prefix paths (e.g. `.$key` or `.2:2`). `React.Fragment` elements are treated as single opaque items and not unwrapped.
5. **Children Counting and Single Element Enforcement**: `React.Children.count` tallies all child slots including `null`, `undefined`, and booleans across nested arrays. `React.Children.only` returns the single valid React element, throwing an error if passed an array (even length 1), primitive, or null/undefined.
6. **Children Mapping**: `React.Children.map` passes through `null` or `undefined` roots as `null` or `undefined` (rather than returning empty arrays), flattens returned arrays, and omits `null`/`undefined` mapper results.
7. **Memo and ForwardRef Wrappers**: `React.memo` creates a wrapper object with `$$typeof: Symbol.for('react.memo')`, wrapping a functional component and custom comparison function (`arePropsEqual`, where `true` indicates props are equal and skips re-render). `React.forwardRef` creates a wrapper object with `$$typeof: Symbol.for('react.forward_ref')` wrapping the render function `(props, ref) => ...`.
## Failure Mode
When migrating across React versions or writing custom element manipulation utilities:
- Developers expecting `props.ref` to contain the ref in React 18 find `undefined`, as `ref` is located on `element.ref`.
- Using `React.isValidElement` on a component definition (e.g. `React.isValidElement(MyComponent)`) returns `false`, causing incorrect conditional branching.
- Using `React.Children.toArray` on elements inside `<React.Fragment>` does not unwrap the fragment's children.
- Assuming `React.Children.only([<div />])` accepts a single-element array causes a runtime TypeError/Error.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, and memo wrappers
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/react@18.3.1
Demonstrate these symbols/APIs:
- React.Children
- React.cloneElement
- React.createElement
- React.forwardRef
- React.isValidElement
- React.memo
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:9dd3e4294402bdd9391a33a274ae38420d2ac4c59985dcbd940ddb585b60d8d1","contract":["React.createElement constructs elements with Symbol.for('react.element') typeof, attaches ref directly to element.ref (leaving props.ref undefined), and places key on element.key.","React.isValidElement validates Symbol.for('react.element') instances and returns false for component functions, memo/forwardRef definitions, plain objects, primitives, and null/undefined.","React.cloneElement shallowly copies and overrides props, replaces or preserves ref/key, coerces key: null to string 'null', and replaces children when trailing arguments are supplied.","React.Children.toArray flattens nested arrays, strips null/undefined/booleans, preserves 0 and empty strings, assigns hierarchical key prefixes, and treats React.Fragment as opaque.","React.Children.count recursively tallies every child slot including null/undefined/booleans, while React.Children.only enforces a single valid React element child and throws on arrays or primitives.","React.Children.map returns null or undefined on null or undefined input, flattens returned arrays, and omits null or undefined mapper return values.","React.memo and React.forwardRef construct wrapper objects with distinctive $$typeof symbols (react.memo, react.forward_ref), custom comparison or render references, and valid element instantiation."],"goal":"Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, and memo wrappers","kind":"HOW","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"symbols":["React.Children","React.cloneElement","React.createElement","React.forwardRef","React.isValidElement","React.memo"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"subject":"pkg:npm/react@18.3.1","symbols":["React.Children","React.cloneElement","React.createElement","React.forwardRef","React.isValidElement","React.memo"],"verifierAdapter":"node-typescript@1"}
{
"name": "react-elements-children-contract",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "react-elements-children-contract",
"version": "1.0.0",
"dependencies": {
"react": "18.3.1"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
}
}
}
{
"name": "react-elements-children-contract",
"version": "1.0.0",
"type": "module",
"dependencies": {
"react": "18.3.1"
}
}
{
"schemaVersion": 1,
"goal": "Verify React 18.3.1 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, and memo wrappers",
"kind": "HOW",
"packages": [
"pkg:npm/react@18.3.1"
],
"symbols": [
"React.Children",
"React.cloneElement",
"React.createElement",
"React.forwardRef",
"React.isValidElement",
"React.memo"
]
}
import assert from 'node:assert/strict';
import React from 'react';
// Contract 1: React.createElement constructs elements with Symbol.for('react.element') typeof,
// attaches ref directly to element.ref (leaving props.ref undefined), and places key on element.key.
{
const refObj = React.createRef();
const element = React.createElement(
'div',
{ id: 'container', key: 'custom-key', ref: refObj, className: 'box' },
'Child Content'
);
assert.strictEqual(element.$$typeof, Symbol.for('react.element'));
assert.strictEqual(element.type, 'div');
assert.strictEqual(element.key, 'custom-key');
assert.strictEqual(element.ref, refObj);
assert.strictEqual(element.props.id, 'container');
assert.strictEqual(element.props.className, 'box');
assert.strictEqual(element.props.children, 'Child Content');
assert.strictEqual(element.props.key, undefined, 'key must not be exposed on element.props');
assert.strictEqual(element.props.ref, undefined, 'ref must not be exposed on element.props in React 18');
}
// Contract 2: React.isValidElement validates Symbol.for('react.element') instances and returns false
// for component functions, memo/forwardRef definitions, plain objects, primitives, and null/undefined.
{
const Component = () => React.createElement('div', null);
const MemoComponent = React.memo(Component);
const ForwardComponent = React.forwardRef((props, ref) => React.createElement('div', { ref }));
const element = React.createElement('div', null);
assert.strictEqual(React.isValidElement(element), true);
assert.strictEqual(React.isValidElement(React.createElement(Component)), true);
assert.strictEqual(React.isValidElement(React.createElement(MemoComponent)), true);
assert.strictEqual(React.isValidElement(React.createElement(ForwardComponent)), true);
// Non-elements return false
assert.strictEqual(React.isValidElement(Component), false);
assert.strictEqual(React.isValidElement(MemoComponent), false);
assert.strictEqual(React.isValidElement(ForwardComponent), false);
assert.strictEqual(React.isValidElement({ type: 'div', props: {} }), false);
assert.strictEqual(React.isValidElement(null), false);
assert.strictEqual(React.isValidElement(undefined), false);
assert.strictEqual(React.isValidElement(123), false);
assert.strictEqual(React.isValidElement('string'), false);
assert.strictEqual(React.isValidElement(true), false);
assert.strictEqual(React.isValidElement([element]), false);
}
// Contract 3: React.cloneElement shallowly copies and overrides props, replaces or preserves ref/key,
// coerces key: null to string 'null', and replaces children when trailing arguments are supplied.
{
const originalRef = React.createRef();
const newRef = React.createRef();
const original = React.createElement('div', { id: 'orig', key: 'orig-key', ref: originalRef, count: 1 }, 'Initial');
// Clone with prop overrides, preserving key and ref
const clone1 = React.cloneElement(original, { count: 2, extra: 'val' });
assert.strictEqual(clone1.$$typeof, Symbol.for('react.element'));
assert.strictEqual(clone1.type, 'div');
assert.strictEqual(clone1.key, 'orig-key');
assert.strictEqual(clone1.ref, originalRef);
assert.strictEqual(clone1.props.id, 'orig');
assert.strictEqual(clone1.props.count, 2);
assert.strictEqual(clone1.props.extra, 'val');
assert.strictEqual(clone1.props.children, 'Initial');
// Clone with key and ref override, and children override
const clone2 = React.cloneElement(original, { key: 'new-key', ref: newRef }, 'New Child A', 'New Child B');
assert.strictEqual(clone2.key, 'new-key');
assert.strictEqual(clone2.ref, newRef);
assert.deepStrictEqual(clone2.props.children, ['New Child A', 'New Child B']);
// Key coercion of null to 'null'
const cloneNullKey = React.cloneElement(original, { key: null });
assert.strictEqual(cloneNullKey.key, 'null');
// Original element remains unchanged
assert.strictEqual(original.props.count, 1);
assert.strictEqual(original.key, 'orig-key');
}
// Contract 4: React.Children.toArray flattens nested arrays, strips null/undefined/booleans,
// preserves 0 and empty strings, assigns hierarchical key prefixes, and treats React.Fragment as opaque.
{
const el1 = React.createElement('span', { key: 'alpha' }, 'A');
const el2 = React.createElement('span', null, 'B');
const el3 = React.createElement('span', { key: 'gamma' }, 'C');
const fragment = React.createElement(React.Fragment, null, React.createElement('span', null, 'D'));
const childrenTree = [
el1,
null,
[undefined, false, el2, [true, el3]],
0,
'',
fragment
];
const flatArray = React.Children.toArray(childrenTree);
// null, undefined, false, true are stripped; el1, el2, el3, 0, '', fragment are kept -> 6 items
assert.strictEqual(flatArray.length, 6);
// Key rewriting: array slots track actual indices in the nested structure
assert.strictEqual(flatArray[0].key, '.$alpha');
assert.strictEqual(flatArray[1].key, '.2:2'); // sub-index 2 within outer index 2 array
assert.strictEqual(flatArray[2].key, '.2:3:$gamma'); // keyed element nested within sub-array
assert.strictEqual(flatArray[3], 0); // number 0 strictly preserved
assert.strictEqual(flatArray[4], ''); // empty string strictly preserved
assert.strictEqual(flatArray[5].type, React.Fragment, 'Fragment is not unwrapped by toArray');
}
// Contract 5: React.Children.count recursively tallies every child slot including null/undefined/booleans,
// while React.Children.only enforces a single valid React element child and throws on arrays or primitives.
{
const el = React.createElement('div', null);
// count tallies all slots across nested structures
const slotCount = React.Children.count([el, null, [undefined, true, el]]);
assert.strictEqual(slotCount, 5);
// only returns single element directly
assert.strictEqual(React.Children.only(el), el);
// only throws on arrays (even with length 1), primitives, or null
assert.throws(
() => React.Children.only([el]),
{ name: 'Error', message: /React\.Children\.only expected to receive a single React element child/ }
);
assert.throws(
() => React.Children.only('single text string'),
{ name: 'Error', message: /React\.Children\.only expected to receive a single React element child/ }
);
assert.throws(
() => React.Children.only(null),
{ name: 'Error', message: /React\.Children\.only expected to receive a single React element child/ }
);
}
// Contract 6: React.Children.map returns null or undefined on null or undefined input,
// flattens returned arrays, and omits null or undefined mapper return values.
{
assert.strictEqual(React.Children.map(null, c => c), null);
assert.strictEqual(React.Children.map(undefined, c => c), undefined);
const el1 = React.createElement('span', null, '1');
const el2 = React.createElement('span', null, '2');
// Mapper returning arrays is flattened
const mappedArray = React.Children.map([el1, el2], c => [c, c]);
assert.strictEqual(mappedArray.length, 4);
// Mapper returning null filters that entry
const filteredMap = React.Children.map([el1, el2], (c, idx) => (idx === 0 ? null : c));
assert.strictEqual(filteredMap.length, 1);
assert.strictEqual(filteredMap[0].props.children, '2');
}
// Contract 7: React.memo and React.forwardRef construct wrapper objects with distinctive $$typeof
// symbols (react.memo, react.forward_ref), custom comparison or render references, and valid element instantiation.
{
const BaseComponent = (props) => React.createElement('div', null, props.title);
const arePropsEqual = (prevProps, nextProps) => prevProps.title === nextProps.title;
const MemoComponent = React.memo(BaseComponent, arePropsEqual);
assert.strictEqual(MemoComponent.$$typeof, Symbol.for('react.memo'));
assert.strictEqual(MemoComponent.type, BaseComponent);
assert.strictEqual(MemoComponent.compare, arePropsEqual);
const renderFunction = (props, ref) => React.createElement('button', { ref }, props.label);
const ForwardComponent = React.forwardRef(renderFunction);
assert.strictEqual(ForwardComponent.$$typeof, Symbol.for('react.forward_ref'));
assert.strictEqual(ForwardComponent.render, renderFunction);
const ref = React.createRef();
const forwardElement = React.createElement(ForwardComponent, { ref, label: 'Submit' });
assert.strictEqual(React.isValidElement(forwardElement), true);
assert.strictEqual(forwardElement.type, ForwardComponent);
assert.strictEqual(forwardElement.ref, ref);
assert.strictEqual(forwardElement.props.label, 'Submit');
}
console.log('All React 18.3.1 element, Children, cloneElement, memo, and forwardRef contract checks passed.');
Seeder d'origine
anonyme