AgentSkillsCN

core-type-mapping

OpenAPI 格式到 TypeScript 核心类型的类型映射参考

SKILL.md
--- frontmatter
name: core-type-mapping
description: Type mapping reference for OpenAPI formats to TypeScript core types

Core Type Mapping Guide

Overview

This guide provides the mapping between OpenAPI string formats and their corresponding TypeScript type classes for use in Tasks 5, 7, 8, and 9.

🚨 Critical Usage Rules

  • Task 5: Use these mappings when creating OpenAPI specifications - set the correct format field
  • Task 7: Use these mappings in data transformation and validation
  • Task 8 & 9: Use these mappings for type assertions in tests (e.g., instanceof Email, instanceof UUID)
  • String Conversion: All types support .toString() method and template literal interpolation
  • Import Sources: Import types from the specified packages, not from Node.js built-ins

AWS Types (@zerobias-org/types-amazon-js)

String FormatTypeScript TypeUsage Example
arnArntoEnum(Arn, value) or new Arn(value)
awsPartitionAwsPartitiontoEnum(AwsPartition, value)
awsServiceAwsServicetoEnum(AwsService, value)
awsImageIdAwsImageIdtoEnum(AwsImageId, value)
awsAccessPolicyAwsAccessPolicynew AwsAccessPolicy(value)
awsAccessPolicyStatementAwsAccessPolicyStatementnew AwsAccessPolicyStatement(value)
awsAccessPolicyStatementConditionAwsAccessPolicyStatementConditionnew AwsAccessPolicyStatementCondition(value)
awsAccessPolicyStatementEffectAwsAccessPolicyStatementEffecttoEnum(AwsAccessPolicyStatementEffect, value)
awsAccessPolicyStatementOperatorAwsAccessPolicyStatementOperatortoEnum(AwsAccessPolicyStatementOperator, value)

Microsoft Azure Types (@zerobias-org/types-microsoft-js)

String FormatTypeScript TypeUsage Example
azureVmSizeAzureVmSizetoEnum(AzureVmSize, value)
azureResourceProviderAzureResourceProvidertoEnum(AzureResourceProvider, value)
azureResourceAzureResourcenew AzureResource(value)
azureResourceInfoAzureResourceInfonew AzureResourceInfo(value)
azureResourceTypeAzureResourceTypetoEnum(AzureResourceType, value)
azureResourcePlanAzureResourcePlannew AzureResourcePlan(value)
azureResourceSkuAzureResourceSkunew AzureResourceSku(value)
azureResourceSkuTierAzureResourceSkuTiertoEnum(AzureResourceSkuTier, value)
azureResourceIdentityAzureResourceIdentitynew AzureResourceIdentity(value)
azureResourceIdentityTypeAzureResourceIdentityTypetoEnum(AzureResourceIdentityType, value)

Google Cloud Types (@zerobias-org/types-google-js)

String FormatTypeScript TypeUsage Example
gcpAccessPolicyGcpAccessPolicynew GcpAccessPolicy(value)
gcpAccessPolicyAuditConfigGcpAccessPolicyAuditConfignew GcpAccessPolicyAuditConfig(value)
gcpAccessPolicyAuditLogConfigGcpAccessPolicyAuditLogConfignew GcpAccessPolicyAuditLogConfig(value)
gcpAccessPolicyAuditLogConfigTypeGcpAccessPolicyAuditLogConfigTypetoEnum(GcpAccessPolicyAuditLogConfigType, value)
gcpAccessPolicyBindingGcpAccessPolicyBindingnew GcpAccessPolicyBinding(value)
gcpAccessPolicyBindingConditionGcpAccessPolicyBindingConditionnew GcpAccessPolicyBindingCondition(value)
gcpAccessPolicyVersionGcpAccessPolicyVersiontoEnum(GcpAccessPolicyVersion, value)

Core Types (@zerobias-org/types-core-js)

Binary/Encoding

String FormatTypeScript TypeUsage Example
byteBytenew Byte(value)
b64Bytenew Byte(value)
base64Bytenew Byte(value)

Networking

String FormatTypeScript TypeUsage Example
cidrCidrnew Cidr(value)
ipAddressIpAddressnew IpAddress(value)
ipIpAddressnew IpAddress(value)
ipv4IpAddressnew IpAddress(value)
ipv6IpAddressnew IpAddress(value)
macMacAddressnew MacAddress(value)
macaddrMacAddressnew MacAddress(value)
macAddressMacAddressnew MacAddress(value)
hostnameHostnamenew Hostname(value)

Date/Time

String FormatTypeScript TypeUsage Example
date-timeDatenew Date(value)
timeDatenew Date(value)
timestampDatenew Date(value)
dateDatenew Date(value)
durationDurationnew Duration(value)

Numeric

String FormatTypeScript TypeUsage Example
doublenumberNumber(value)
floatnumberNumber(value)
int32numberNumber(value)
int64numberNumber(value)
integernumberNumber(value)

Communication/Identity

String FormatTypeScript TypeUsage Example
emailEmailnew Email(value)
phoneNumberPhoneNumbernew PhoneNumber(value)
phonePhoneNumbernew PhoneNumber(value)
urlURLnew URL(value)
uriURLnew URL(value)

Identifiers

String FormatTypeScript TypeUsage Example
uuidUUIDnew UUID(value)
guidUUIDnew UUID(value)
objectIdObjectIdnew ObjectId(value)

Security

String FormatTypeScript TypeUsage Example
passwordstringDirect string usage
secretstringDirect string usage
tokenstringDirect string usage
apiKeystringDirect string usage

Geographic

String FormatTypeScript TypeUsage Example
latitudeLatitudenew Latitude(value)
longitudeLongitudenew Longitude(value)
geoPointGeoPointnew GeoPoint(lat, lon)
countryCountrytoEnum(Country, value)
countryCodeCountrytoEnum(Country, value)
languageLanguagetoEnum(Language, value)
languageCodeLanguagetoEnum(Language, value)
currencyCurrencytoEnum(Currency, value)
currencyCodeCurrencytoEnum(Currency, value)

File/Media

String FormatTypeScript TypeUsage Example
mimeTypeMimeTypetoEnum(MimeType, value)
fileExtensionFileExtensiontoEnum(FileExtension, value)
pathPathnew Path(value)
filePathPathnew Path(value)

Business/Domain

String FormatTypeScript TypeUsage Example
ssnSsnnew Ssn(value)
tinTinnew Tin(value)
ibanIbannew Iban(value)
creditCardCreditCardnew CreditCard(value)
postalCodePostalCodenew PostalCode(value)
zipCodePostalCodenew PostalCode(value)

Complete Type Mapping Reference Table

Consolidated Quick Reference

FormatPackageTypeConstructor Pattern
uuid@zerobias-org/types-core-jsUUIDmap(UUID, value)
email@zerobias-org/types-core-jsEmailmap(Email, value)
url@zerobias-org/types-core-jsURLmap(URL, value)
date-timeNativeDatemap(Date, value)
ipAddress@zerobias-org/types-core-jsIpAddressmap(IpAddress, value)
phoneNumber@zerobias-org/types-core-jsPhoneNumbermap(PhoneNumber, value)
arn@zerobias-org/types-amazon-jsArnmap(Arn, value)
cidr@zerobias-org/types-core-jsCidrmap(Cidr, value)
duration@zerobias-org/types-core-jsDurationmap(Duration, value)
base64@zerobias-org/types-core-jsBytemap(Byte, value)

Usage Patterns by Task

Task 5: OpenAPI Specification

yaml
# Use format field to specify type
properties:
  id:
    type: string
    format: uuid  # → Will generate UUID type
  email:
    type: string
    format: email  # → Will generate Email type
  createdAt:
    type: string
    format: date-time  # → Will generate Date type

Task 7: Implementation (Mappers)

typescript
import { map, toEnum } from '@zerobias-org/util-hub-module-utils';
import { UUID, Email, URL } from '@zerobias-org/types-core-js';  // NEVER from Node.js!

export function toUserInfo(raw: any): UserInfo {
  return {
    id: map(UUID, raw.id),
    email: map(Email, raw.email),
    website: map(URL, raw.website_url),
    createdAt: map(Date, raw.created_at),
    status: toEnum(StatusEnum, raw.status)
  };
}

Task 8 & 9: Testing

typescript
import { UUID, Email } from '@zerobias-org/types-core-js';

it('should return user with correct types', () => {
  const user = await getUser('123');

  expect(user.id).to.be.instanceof(UUID);
  expect(user.email).to.be.instanceof(Email);
  expect(user.createdAt).to.be.instanceof(Date);
});

String Conversion Support

All custom types support string conversion:

typescript
const email = new Email('user@example.com');

// Direct toString()
const emailString = email.toString();  // "user@example.com"

// Template literal (automatic conversion)
const message = `User email: ${email}`;  // "User email: user@example.com"

// JSON serialization
JSON.stringify({ email });  // {"email":"user@example.com"}

Package Import Requirements

Required Dependencies

json
{
  "dependencies": {
    "@zerobias-org/types-core-js": "*",
    "@zerobias-org/util-hub-module-utils": "*"
  },
  "devDependencies": {
    "@zerobias-org/types-amazon-js": "*",  // If using AWS
    "@zerobias-org/types-microsoft-js": "*",  // If using Azure
    "@zerobias-org/types-google-js": "*"  // If using GCP
  }
}

Common Mistakes to Avoid

❌ WRONG - Using Node.js built-ins

typescript
import { URL } from 'url';  // WRONG!
import { URL } from 'node:url';  // WRONG!

✅ CORRECT - Using core types

typescript
import { URL } from '@zerobias-org/types-core-js';  // CORRECT!

❌ WRONG - Direct enum instantiation

typescript
const status = new StatusEnum('active');  // WRONG - constructor is private!

✅ CORRECT - Using toEnum

typescript
const status = toEnum(StatusEnum, 'active');  // CORRECT!

❌ WRONG - Manual type conversion

typescript
const uuid = raw.id as UUID;  // WRONG - no validation!

✅ CORRECT - Using map function

typescript
const uuid = map(UUID, raw.id);  // CORRECT - validates and converts!

Priority Rules

  1. Always use core types over native JavaScript types when available
  2. Import from correct package - never from Node.js built-ins
  3. Use map() for type conversion - provides validation
  4. Use toEnum() for enums - never instantiate directly
  5. All types support .toString() - use for string conversion
String FormatTypeScript TypeUsage Example
emailEmailnew Email(value)
phoneNumberPhoneNumbernew PhoneNumber(value)
phonePhoneNumbernew PhoneNumber(value)

Web/Protocol

String FormatTypeScript TypeUsage Example
urlURLnew URL(value)
uriURLnew URL(value)
uuidUUIDnew UUID(value)
mimeTypeMimeTypenew MimeType(value)

Versioning

String FormatTypeScript TypeUsage Example
semverSemvernew Semver(value)
versionRangeVersionRangenew VersionRange(value)

Misc

String FormatTypeScript TypeUsage Example
nmtokenNmtokennew Nmtoken(value)
passwordstringString(value)

Usage Patterns

Task 5: OpenAPI Specification

yaml
properties:
  email_address:
    type: string
    format: email  # Maps to Email type
  website_url:
    type: string
    format: url    # Maps to URL type
  user_id:
    type: string
    format: uuid   # Maps to UUID type

Task 7: Data Transformation

typescript
import { Email, URL, UUID } from '@zerobias-org/types-core-js';
import { map } from '@zerobias-org/util-hub-module-utils';

function mapUser(raw: any): User {
  return {
    id: map(UUID, raw.user_id),
    email: map(Email, raw.email_address),
    website: map(URL, raw.website_url)
  };
}

Task 8 & 9: Test Assertions

typescript
import { Email, URL, UUID } from '@zerobias-org/types-core-js';

// Test assertions
expect(user.id).to.be.instanceof(UUID);
expect(user.email).to.be.instanceof(Email);
expect(user.website).to.be.instanceof(URL);

String Conversion Examples

typescript
// All types support toString() and template literals
const email = new Email('user@example.com');
const emailString = email.toString();
const message = `User email: ${email}`;

const uuid = new UUID('123e4567-e89b-12d3-a456-426614174000');
const uuidString = uuid.toString();
const log = `Processing user ${uuid}`;

Package Import Requirements

🚨 CRITICAL: Always import from the specified packages:

typescript
// Core types - ALWAYS import from @zerobias-org/types-core-js
import { URL, UUID, Email, IpAddress } from '@zerobias-org/types-core-js';

// AWS types
import { Arn, AwsService } from '@zerobias-org/types-amazon-js';

// Azure types  
import { AzureVmSize, AzureResource } from '@zerobias-org/types-microsoft-js';

// Google Cloud types
import { GcpAccessPolicy } from '@zerobias-org/types-google-js';

// NEVER import URL from Node.js built-ins
// ❌ import { URL } from 'url';  // WRONG
// ✅ import { URL } from '@zerobias-org/types-core-js';  // CORRECT

Validation and Error Handling

All typed values can be validated and will throw appropriate errors for invalid formats:

typescript
try {
  const email = new Email('invalid-email');  // Throws validation error
} catch (error) {
  // Handle validation error
}

// Safe validation with try-catch in mappers
function safeMapEmail(raw: string): Email | null {
  try {
    return new Email(raw);
  } catch {
    return null;  // Or handle as appropriate for your use case
  }
}