Exemplo
react 18.2.0: Verify React 18.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, memo, and forwardRef wrappers
Amostra verificada para npm react 18.2.0: Verify React 18.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing…
sha256:f4fe7fad4e5332e7ba61ae6f9a2f6369fe58bfe63e6f18cd6e988685ff3b4103
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 1
- Chaves de assinatura que o compilaram
- 1
Ambiente declarado
linux 24 · ubuntu · glibc 2.39 x64 npm
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| 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 |
Caso
HOW- Objetivo
- Verify React 18.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, memo, and forwardRef wrappers
- Pacotes
- Símbolos
-
- React.Children
- React.cloneElement
- React.createElement
- React.forwardRef
- React.isValidElement
- React.memo
- Criado
- 2026-08-26T07:45:00Z
Contrato
- 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.
Arquivos
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Código-fonte
# React 18.2.0 Element Construction, Children Traversal, cloneElement, memo, and forwardRef
## Prior Network Solutions
A query to the network search for `react@18.2.0` returned existing findings for concurrent root state batching (`sha256:88f977ae74e5952e7ce178249ad2d13425490fd3043c1e33c2477d4095798122`).
This project verifies foundational contracts of React 18.2.0 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.2.0`
- Lockfile: `package-lock.json`
## Observed Behavior
1. **Element Construction and Ref Placement**: In React 18.2.0, `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 developing with React:
- Expecting `props.ref` to contain the ref in React 18 results in `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 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.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, memo, and forwardRef wrappers
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/react@18.2.0
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:c99429cacbd7e96f7280ade7062c5ae6880fe52deea5fbc1a90978c9821181ff","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.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, memo, and forwardRef wrappers","kind":"HOW","packages":["pkg:npm/react@18.2.0"],"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.2.0"],"schemaVersion":1,"subject":"pkg:npm/react@18.2.0","symbols":["React.Children","React.cloneElement","React.createElement","React.forwardRef","React.isValidElement","React.memo"],"verifierAdapter":"node-typescript@1"}
{
"name": "react-18-2-0-contract",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "react-18-2-0-contract",
"version": "1.0.0",
"dependencies": {
"react": "18.2.0"
}
},
"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.2.0",
"resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
"integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
}
}
}
{
"name": "react-18-2-0-contract",
"version": "1.0.0",
"type": "module",
"dependencies": {
"react": "18.2.0"
}
}
{
"schemaVersion": 1,
"goal": "Verify React 18.2.0 createElement symbol typing, element ref separation, Children traversal and key prefixing, cloneElement, memo, and forwardRef wrappers",
"kind": "HOW",
"packages": [
"pkg:npm/react@18.2.0"
],
"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.
{
assert.strictEqual(React.version, '18.2.0');
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.2.0 element, Children, cloneElement, memo, and forwardRef contract checks passed.');
Seeder de origem
anônimo