CodeSampleX

示例

zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod

已验证示例 — npm zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod. contract 在 node 22 · linux alpine/x64 …

sha256:8481cecd353d1aa53e78f3fe731486c75549aa16aeeab769d5ff48b918566655

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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-23

案例

HOW
目标
Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
包
符号
  • zod.z.lazy
创建时间
2026-08-23T06:52:13Z

契约

  1. z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes
  2. z.lazy validates deeply nested hierarchical structures without infinite recursion
  3. z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths
  4. z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values
  5. z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps
  6. safeParse on recursive schemas returns detailed issue path for malformed deep leaves

文件

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.js

下载源代码构件 (tar.gz)

源代码

PROMPT.md
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: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/zod@3.25.76
Demonstrate these symbols/APIs:
  - zod.z.lazy

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.
csx.json
{"case":{"caseId":"case:sha256:717b2a9fc68a6b8e731ce7d98675ae0d7b1ca4be59d604593d5eeae014df6ba2","contract":["z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes","z.lazy validates deeply nested hierarchical structures without infinite recursion","z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths","z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values","z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps","safeParse on recursive schemas returns detailed issue path for malformed deep leaves"],"goal":"Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod","kind":"HOW","packages":["pkg:npm/zod@3.25.76"],"schemaVersion":1,"symbols":["zod.z.lazy"]},"contractCommand":["node","test/contract.js"],"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/zod@3.25.76"],"schemaVersion":1,"subject":"pkg:npm/zod@3.25.76","symbols":["zod.z.lazy"],"verifierAdapter":"node-typescript@1"}
index.js
const { z } = require('zod');

// Recursive tree node schema using z.lazy
const treeNodeSchema = z.object({
  id: z.string().min(1),
  name: z.string().min(1),
  value: z.number().optional(),
  attributes: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
  children: z.array(z.lazy(() => treeNodeSchema)).default([]),
});

// Recursive JSON value schema using z.lazy and z.record
const jsonValueSchema = z.lazy(() =>
  z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.null(),
    z.array(jsonValueSchema),
    z.record(z.string(), jsonValueSchema),
  ])
);

// Dynamic key-value dictionary schema using z.record
const configMapSchema = z.record(
  z.string().min(1),
  z.object({
    enabled: z.boolean(),
    timeoutMs: z.number().int().positive().default(5000),
    metadata: z.record(z.string(), z.string()).default({}),
  })
);

function parseTreeNode(input) {
  return treeNodeSchema.parse(input);
}

function safeParseTreeNode(input) {
  return treeNodeSchema.safeParse(input);
}

function parseJsonValue(input) {
  return jsonValueSchema.parse(input);
}

function safeParseJsonValue(input) {
  return jsonValueSchema.safeParse(input);
}

function parseConfigMap(input) {
  return configMapSchema.parse(input);
}

function safeParseConfigMap(input) {
  return configMapSchema.safeParse(input);
}

module.exports = {
  z,
  treeNodeSchema,
  jsonValueSchema,
  configMapSchema,
  parseTreeNode,
  safeParseTreeNode,
  parseJsonValue,
  safeParseJsonValue,
  parseConfigMap,
  safeParseConfigMap,
};
package-lock.json
{
  "name": "sample-zod-lazy",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-zod-lazy",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "zod": "3.25.76"
      }
    },
    "node_modules/zod": {
      "version": "3.25.76",
      "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
      "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/colinhacks"
      }
    }
  }
}
package.json
{
  "name": "sample-zod-lazy",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for zod.z.lazy and z.record in zod",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "license": "MIT-0",
  "dependencies": {
    "zod": "3.25.76"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod",
  "kind": "HOW",
  "packages": [
    "pkg:npm/zod@3.25.76"
  ],
  "symbols": [
    "zod.z.lazy"
  ]
}
test/contract.js
const assert = require('assert');
const {
  z,
  treeNodeSchema,
  jsonValueSchema,
  configMapSchema,
  parseTreeNode,
  safeParseTreeNode,
  parseJsonValue,
  safeParseJsonValue,
  parseConfigMap,
  safeParseConfigMap,
} = require('../index.js');

function runTests() {
  // 1. z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes
  {
    const rootNode = {
      id: 'root',
      name: 'Root Node',
      attributes: { priority: 1, isRoot: true },
      children: [
        {
          id: 'child-1',
          name: 'First Child',
          attributes: { tag: 'leaf' },
          children: [],
        },
        {
          id: 'child-2',
          name: 'Second Child',
          children: [
            {
              id: 'grandchild-1',
              name: 'Deep Child',
            },
          ],
        },
      ],
    };

    const parsed = parseTreeNode(rootNode);
    assert.strictEqual(parsed.id, 'root');
    assert.strictEqual(parsed.children.length, 2);
    assert.strictEqual(parsed.children[0].name, 'First Child');
    assert.deepStrictEqual(parsed.children[0].children, []);
    assert.strictEqual(parsed.children[1].children.length, 1);
    assert.strictEqual(parsed.children[1].children[0].id, 'grandchild-1');
    assert.deepStrictEqual(parsed.children[1].children[0].attributes, {});
    assert.deepStrictEqual(parsed.children[1].children[0].children, []);
  }

  // 2. z.lazy validates deeply nested hierarchical structures without infinite recursion
  {
    let deepNode = { id: 'leaf-10', name: 'Level 10 Node', children: [] };
    for (let i = 9; i >= 1; i--) {
      deepNode = {
        id: `node-${i}`,
        name: `Level ${i} Node`,
        value: i * 100,
        children: [deepNode],
      };
    }

    const parsed = parseTreeNode(deepNode);
    assert.strictEqual(parsed.id, 'node-1');
    assert.strictEqual(parsed.value, 100);

    let current = parsed;
    for (let i = 1; i <= 9; i++) {
      assert.strictEqual(current.id, `node-${i}`);
      assert.strictEqual(current.children.length, 1);
      current = current.children[0];
    }
    assert.strictEqual(current.id, 'leaf-10');
    assert.deepStrictEqual(current.children, []);
  }

  // 3. z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths
  {
    const invalidTree = {
      id: 'root',
      name: 'Root',
      children: [
        {
          id: 'valid-branch',
          name: 'Branch',
          children: [
            {
              id: '', // Invalid empty id
              name: 'Invalid Leaf',
            },
          ],
        },
      ],
    };

    const res = safeParseTreeNode(invalidTree);
    assert.strictEqual(res.success, false);
    const issue = res.error.issues.find((iss) =>
      iss.path.join('.').includes('children.0.children.0.id')
    );
    assert.ok(issue, 'reports error at exact nested path children.0.children.0.id');
    assert.strictEqual(issue.code, 'too_small');
  }

  // 4. z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values
  {
    const validConfig = {
      database: { enabled: true, timeoutMs: 3000, metadata: { region: 'us-east' } },
      cache: { enabled: false },
    };

    const parsed = parseConfigMap(validConfig);
    assert.strictEqual(parsed.database.enabled, true);
    assert.strictEqual(parsed.database.timeoutMs, 3000);
    assert.strictEqual(parsed.database.metadata.region, 'us-east');
    assert.strictEqual(parsed.cache.enabled, false);
    assert.strictEqual(parsed.cache.timeoutMs, 5000, 'applies default timeout');
    assert.deepStrictEqual(parsed.cache.metadata, {});

    const invalidConfig = {
      serviceA: { enabled: 'not-a-boolean' },
    };
    const invalidRes = safeParseConfigMap(invalidConfig);
    assert.strictEqual(invalidRes.success, false);
    assert.ok(
      invalidRes.error.issues.some(
        (iss) => iss.path.join('.') === 'serviceA.enabled' && iss.code === 'invalid_type'
      ),
      'reports invalid type on dictionary value property'
    );
  }

  // 5. z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps
  {
    const complexJson = {
      title: 'Config Tree',
      version: 1,
      nested: {
        active: true,
        tags: ['alpha', 'beta', null, 42],
        subRecord: {
          innerKey: {
            deepList: [{ flag: false }],
          },
        },
      },
    };

    const parsed = parseJsonValue(complexJson);
    assert.strictEqual(parsed.title, 'Config Tree');
    assert.strictEqual(parsed.version, 1);
    assert.strictEqual(parsed.nested.active, true);
    assert.deepStrictEqual(parsed.nested.tags, ['alpha', 'beta', null, 42]);
    assert.strictEqual(parsed.nested.subRecord.innerKey.deepList[0].flag, false);

    const invalidValue = safeParseJsonValue(undefined);
    assert.strictEqual(invalidValue.success, false, 'rejects undefined');

    const invalidFunc = safeParseJsonValue({ fn: () => {} });
    assert.strictEqual(invalidFunc.success, false, 'rejects functions');
  }

  // 6. safeParse on recursive schemas returns detailed issue path for malformed deep leaves
  {
    const malformedPayload = {
      menu: {
        header: 'Main',
        items: [
          { name: 'Home' },
          { name: 'Settings', sub: { invalidKey: Symbol('cannot serialize') } },
        ],
      },
    };

    const result = safeParseJsonValue(malformedPayload);
    assert.strictEqual(result.success, false);
    assert.ok(result.error.issues.length > 0);
  }

  // 7. Verify z.lazy export and function signature
  {
    assert.strictEqual(typeof z.lazy, 'function');
    assert.strictEqual(typeof z.record, 'function');
  }

  console.log('Contract tests passed successfully.');
}

runTests();

原始种子者

匿名