@geoprotocol/grc-20

中文文档
0.4.1发布于 2026/03/10MITTypeScriptES Module近 30 天下载 1万

GRC-20 二进制属性图形编码/解码的 TypeScript 库

中文使用文档
文档目录18 节
  1. 安装
  2. 快速启动
  3. 特征
  4. 套装大小
  5. 懒惰装入
  6. API 参考
  7. 类型
  8. 构建器
  9. 操作( 功能 API)
  10. 代码c
  11. 压缩
  12. 标识公用事业
  13. 验证
  14. 数据类型参考
  15. 创世纪标识
  16. 条目点
  17. 发展
  18. 许可证

@ geoprotocol/ grc-20

TypeScript库用于编码和解码GRC-20 二进制属性图形数据.

安装

npm install @geoprotocol/grc-20

快速启动

import {
  EditBuilder,
  encodeEdit,
  decodeEdit,
  randomId,
  properties,
} from "@geoprotocol/grc-20";

// Create an edit with an entity
const edit = new EditBuilder(randomId())
  .setName("Create Alice")
  .addAuthor(randomId())
  .setCreatedNow()
  .createEntity(randomId(), (e) =>
    e
      .text(properties.name(), "Alice", undefined)
      .text(properties.description(), "A person", undefined)
  )
  .build();

// Encode to binary
const bytes = encodeEdit(edit);

// Decode back
const decoded = decodeEdit(bytes);

特征

  • 类型安全 API - 完整类型脚本定义
  • 构建器模式 - 用于构建编辑的流利API
  • 二进制编码c - 纯文本编码器/解码器
  • Zstd 压缩 - 基于WASM的可选压缩(懒惰装入)
  • 树能震动 - 最小捆绑的分出入口
  • 跨平台 - 在节点和浏览器中工作

套装大小

入口击出
完整库~12 KB 键
仅类型~1.4 KB 键
只有构建器~1.2 KB 键
仅编码~8千贝
创世纪标识~1.7 KB 键
公用事业~1.6 KB 键
Zstd WASM(懒惰)~81 KB (韩语)

Zstd WASM模块只有在使用压缩函数时才被加载.

懒惰装入

对于最佳初始负载,请分别导入编码器:

// Initial load (~4.4 KB gzipped)
import { EditBuilder, randomId, properties } from "@geoprotocol/grc-20/builder";
import { properties } from "@geoprotocol/grc-20/genesis";

// Lazy load codec when needed (~8 KB gzipped)
const { encodeEdit } = await import("@geoprotocol/grc-20/codec");

// WASM only loads if you use compression (~81 KB additional)
const { encodeEditAuto } = await import("@geoprotocol/grc-20/codec");

API 参考

类型

import {
  Id,              // 16-byte UUID (Uint8Array branded type)
  Edit,            // Batch of operations with metadata
  Op,              // Union of all operation types
  Value,           // Union of all value types
  DataType,        // Enum: Boolean, Integer, Float, Text, etc.
  PropertyValue,   // Property ID + Value pair
} from "@geoprotocol/grc-20";

构建器

import {
  EditBuilder,          // Build Edit objects
  EntityBuilder,        // Build entity values
  UpdateEntityBuilder,  // Build update operations
  RelationBuilder,      // Build relation operations
  UpdateRelationBuilder,// Build relation update operations
} from "@geoprotocol/grc-20";

编辑构建器

const edit = new EditBuilder(editId)
  .setName("My Edit")
  .addAuthor(authorId)
  .setCreatedAt(BigInt(Date.now()) * 1000n)  // microseconds
  .createEntity(entityId, e => e
    .text(propId, "value", languageId)
    .integer(propId, 42n, unitId)
    .float(propId, 3.14, undefined)
    .decimal(propId, { exponent: -2, mantissa: 1234n }, undefined)
    .boolean(propId, true)
    .bytes(propId, new Uint8Array([1, 2, 3]))
    .point(propId, 40.7128, -74.006)
    .date(propId, "2024-01-15Z")             // RFC 3339 date
    .time(propId, "10:30:00Z")               // RFC 3339 time
    .datetime(propId, "2024-01-15T10:30:00Z")// RFC 3339 datetime
  )
  .updateEntity(entityId, u => u
    .setText(propId, "new value", undefined)
    .setInteger(propId, 100n, undefined)
    .unsetLanguage(propId, languageId)  // Unset specific language
    .unsetAll(propId)                   // Unset all values for property
  )
  .deleteEntity(entityId)
  .restoreEntity(entityId)
  .createRelation(r => r
    .id(relationId)
    .from(fromId)
    .to(toId)
    .relationType(relationTypeId)
  )
  .deleteRelation(relationId)
  .restoreRelation(relationId)
  .addOp({ type: 'createValueRef', id: valueRefId, entity: entityId, property: propId })
  .build();

操作( 功能 API)

createEdit 默认 id 改为 randomId() 财务报告和审定财务报表 createdAt 改为 0n 当省略时.

import {
  createEdit,
  createEntity,
  createRelation,
  randomId,
  properties,
  relationTypes,
} from "@geoprotocol/grc-20";

const entityId = randomId();
const authorId = randomId();

const ops = [
  createEntity({
    id: entityId,
    values: [
      { property: properties.name(), value: { type: "text", value: "Alice" } },
      { property: properties.description(), value: { type: "text", value: "A person" } },
    ],
  }),
  createRelation({
    id: randomId(),
    relationType: relationTypes.types(),
    from: entityId,
    to: randomId(),
  }),
];

const edit = createEdit({
  name: "Create Alice",
  author: authorId,
  ops,
});

代码c

import { encodeEdit, decodeEdit } from "@geoprotocol/grc-20";

// Encode (uncompressed)
const bytes = encodeEdit(edit);
const bytesCanonical = encodeEdit(edit, { canonical: true });

// Decode (uncompressed)
const edit = decodeEdit(bytes);

压缩

库通过懒惰的WASM模块支持Zstd压缩. WASM只在首先使用压缩函数时才被下载.

import {
  preloadCompression,
  isCompressionReady,
  encodeEditAuto,
  decodeEditAuto,
  encodeEditCompressed,
  decodeEditCompressed,
} from "@geoprotocol/grc-20";

// Preload WASM on app startup (recommended)
await preloadCompression();

// Check if compression is ready
if (isCompressionReady()) {
  console.log("Compression ready!");
}

// Auto encode/decode (recommended for most use cases)
// Compresses if data > 256 bytes, otherwise uncompressed
const data = await encodeEditAuto(edit);
const decoded = await decodeEditAuto(data);

// Control compression threshold
const data = await encodeEditAuto(edit, { threshold: 0 });       // always compress
const data = await encodeEditAuto(edit, { threshold: 1024 });    // compress if > 1KB
const data = await encodeEditAuto(edit, { threshold: Infinity }); // never compress

// Explicit compressed encode/decode
const compressed = await encodeEditCompressed(edit);
const decoded = await decodeEditCompressed(compressed);

浏览器使用( 没有捆绑)

如果使用没有捆绑器的本地 ES 模块, 请为 WASM 依赖添加导入映射 :

<script type="importmap">
{
  "imports": {
    "@bokuweb/zstd-wasm": "https://esm.sh/@bokuweb/[email protected]"
  }
}
</script>

标识公用事业

import {
  randomId,             // Generate random UUIDv4
  parseId,              // Parse hex string to Id
  formatId,             // Format Id as hex string
  derivedUuid,          // Derive UUIDv8 from bytes (SHA-256, sync)
  derivedUuidAsync,     // Derive UUIDv8 from bytes (SHA-256, async)
  derivedUuidFromString,
  uniqueRelationId,     // Derive relation ID from endpoints
  relationEntityId,     // Derive entity ID from relation ID
  idsEqual,             // Compare two Ids for equality
  compareIds,           // Compare two Ids for ordering (-1, 0, 1)
  NIL_ID,               // Zero UUID
} from "@geoprotocol/grc-20";

验证

编码前验证值和位置 :

import { validateValue, validatePosition } from "@geoprotocol/grc-20";

// Validate a value matches its declared type
const result = validateValue(value, DataType.Text);
if (!result.valid) {
  console.error(result.error);
}

// Validate position string format
const posResult = validatePosition("a0");
if (!posResult.valid) {
  console.error(posResult.error);
}

数据类型参考

类型类型脚本代表
BOOLEAN{ type: "boolean", value: boolean }
INTEGER{ type: "integer", value: bigint, unit?: Id }
FLOAT{ type: "float", value: number, unit?: Id }
DECIMAL{ type: "decimal", exponent: number, mantissa: bigint, unit?: Id }
TEXT{ type: "text", value: string, language?: Id }
BYTES{ type: "bytes", value: Uint8Array }
DATE{ type: "date", value: string } (RFC 3339,例如:. "2024-01-15Z"(中文(简体) )
TIME{ type: "time", value: string } (RFC 3339,例如:. "14:30:00Z"(中文(简体) )
DATETIME{ type: "datetime", value: string } (RFC 3339,例如:. "2024-01-15T14:30:00Z"(中文(简体) )
SCHEDULE{ type: "schedule", value: string } (RFC 5545/7953 iCalendar) (法语)
POINT{ type: "point", lat: number, lon: number, alt?: number }
RECT{ type: "rect", minLat: number, minLon: number, maxLat: number, maxLon: number }
EMBEDDING{ type: "embedding", subType: EmbeddingSubType, dims: number, data: Uint8Array }

创世纪标识

创世纪空间的知名ID:

import { properties, types, relationTypes, languages } from "@geoprotocol/grc-20";

// Properties
properties.name()        // a126ca530c8e48d5b88882c734c38935 - Name (TEXT)
properties.description() // 9b1f76ff9711404c861e59dc3fa7d037 - Description (TEXT)
properties.cover()       // 34f535072e6b42c5a84443981a77cfa2 - Cover image URL (TEXT)

// Types
types.image()            // f3f790c4c74e4d23a0a91e8ef84e30d9 - Image entity

// Relation Types
relationTypes.types()    // 8f151ba4de204e3c9cb499ddf96f48f1 - Type membership

// Languages (derived from BCP 47 codes)
languages.english()      // or languages.fromCode("en")
languages.spanish()
languages.french()
// ... etc

条目点

对于摇树,请使用特定的切入点:

import { ... } from "@geoprotocol/grc-20";          // Full library
import { ... } from "@geoprotocol/grc-20/types";    // Types only
import { ... } from "@geoprotocol/grc-20/builder";  // Builders only
import { ... } from "@geoprotocol/grc-20/codec";    // Codec only
import { ... } from "@geoprotocol/grc-20/genesis";  // Genesis IDs only
import { ... } from "@geoprotocol/grc-20/util";     // Utilities only

发展

# Install dependencies
npm install

# Build
npm run build

# Test (Node.js)
npm test

# Test (Browser via Playwright)
npm run test:browser

# Test both
npm run test:all

# Analyze bundle sizes
npm run bundle:analyze

# Run performance benchmark
npm run benchmark

# Run browser demo
npm run demo
# Then open http://localhost:3000/examples/browser-demo.html

许可证

麻省理工学院

版本与发布记录

@geoprotocol/grc-20 共发布 14 个版本,首次发布于 2026/01/10;过去 12 个月发布了 14 个版本。

版本发布日期距今
0.4.1latest2026/03/108 个月前
0.4.02026/02/109 个月前
0.3.12026/02/109 个月前
0.3.02026/01/289 个月前
0.2.32026/01/279 个月前
0.2.22026/01/249 个月前

关于 @geoprotocol/grc-20 的常见问题

@geoprotocol/grc-20 是什么?

GRC-20 二进制属性图形编码/解码的 TypeScript 库

如何安装 @geoprotocol/grc-20?

在项目目录运行 npm install @geoprotocol/grc-20,或使用 pnpm add / yarn add / bun add。

@geoprotocol/grc-20 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geoprotocol/grc-20 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@geoprotocol/grc-20 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@geoprotocol/grc-20 可以商用吗?

@geoprotocol/grc-20 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@geoprotocol/grc-20 的下载量有多少?

根据 npm 官方下载统计,@geoprotocol/grc-20 在 2026/10/16 – 2026/11/14 这 30 天内被下载 10,193 次,日均约 340 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geoprotocol/grc-20 还在维护吗?

最新版本 0.4.1 发布于 2026/03/10(8 个月前);至今共发布 14 个版本,其中过去 12 个月发布了 14 个;首次发布于 2026/01/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。