mcpField
D
deno-typescript

deno-typescript

github.com/mindrally開発287765 回インストール3 週間前に更新
リポジトリ

deno-typescript について

型、権限、モジュール構成、組み込みツールを扱う、DenoとTypeScript開発向けのスキルガイドです。DenoでWebサービスやアプリケーションを開発する人を対象としています。

主な機能

  1. 01TypeScriptの型と命名規則
  2. 02Denoの権限制御
  3. 03ESモジュールと依存関係の管理
  4. 04HTTPサーバーとフレームワークの例
  5. 05組み込みのテスト、整形、lint
  6. 06Deno KVと環境変数

活用シーン

  1. 01DenoのHTTPサーバーを構築
  2. 02必要な範囲にネットワークとファイル権限を制限
  3. 03TypeScriptプロジェクトの依存関係を整理
  4. 04組み込みツールでコードをテスト・検査

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mindrally/skills --skill deno-typescript

インストール後、Claude Code で/deno-typescriptを入力して読み込まれたか確認します。

詳細

Deno TypeScript 開発

Deno と TypeScript の開発に精通しており、Deno のネイティブ TypeScript サポートと組み込みツールを活用した、安全でモダンなアプリケーションの構築に関する深い知識があります。

TypeScript の一般的なガイドライン

基本原則
  • すべてのコードとドキュメントには英語を使用します
  • 変数と関数(パラメーターと戻り値)には必ず型を宣言します
  • any 型の使用は避け、必要な型を作成します
  • 公開クラスとメソッドは JSDoc でドキュメント化します
  • 簡潔で保守しやすく、技術的に正確なコードを書きます
  • 関数型および宣言型のプログラミングパターンを使用します
  • 設定は不要です。Deno は TypeScript をネイティブに実行します
命名規則
  • クラス、型、インターフェースには PascalCase を使用します
  • 変数、関数、メソッドには camelCase を使用します
  • ファイル名とディレクトリ名には kebab-case を使用します
  • 環境変数には UPPERCASE を使用します
  • 補助動詞を含む、説明的な変数名を使用します:isLoading、hasError、canDelete
  • 各関数名は動詞で始めます
関数
  • 1 つの目的を持つ短い関数を書きます
  • 単純な処理にはアロー関数を使用します
  • 非同期処理には async/await を使用します
  • 複数のパラメーターには RO-RO パターンを優先します
型とインターフェース
  • オブジェクトの形状には、型よりインターフェースを優先します
  • enum は避け、as const を使った const オブジェクトを使用します
  • 実行時の検証には Zod を使用し、型を推論させます
  • 不変のプロパティには readonly を使用します

Deno 固有のガイドライン

プロジェクト構成
src/
  routes/
    {resource}/
      mod.ts
      handlers.ts
      validators.ts
  middleware/
    auth.ts
    logger.ts
  services/
    {domain}_service.ts
  types/
    mod.ts
  utils/
    mod.ts
  deps.ts
  main.ts
deno.json
モジュールシステム
  • 明示的なファイル拡張子を付けた ES モジュールを使用します
  • 依存関係を一元管理するために deps.ts パターンを使用します
  • URL からインポートするか、deno.json のインポートマップを使用します
  • Deno ネイティブのパッケージには JSR(jsr.io)を使用します
// deps.ts - centralized dependencies
export { serve } from "https://deno.land/[email protected]/http/server.ts";
export { z } from "https://deno.land/x/[email protected]/mod.ts";

// Using import maps in deno.json
{
  "imports": {
    "std/": "https://deno.land/[email protected]/",
    "hono": "https://deno.land/x/[email protected]/mod.ts"
  }
}
セキュリティモデル

Deno はデフォルトで安全です。必要な権限のみを要求します:

# Run with specific permissions
deno run --allow-net --allow-read=./data --allow-env main.ts

# Permission flags
--allow-net=example.com    # Network access to specific domains
--allow-read=./path        # File read access
--allow-write=./path       # File write access
--allow-env=API_KEY        # Environment variable access
--allow-run=cmd            # Subprocess execution
// Programmatic permission requests
const status = await Deno.permissions.request({ name: "net", host: "api.example.com" });
if (status.state === "granted") {
  // Network access granted
}
Deno.serve を使用した HTTP サーバー
// Simple HTTP server
Deno.serve({ port: 8000 }, (req) => {
  const url = new URL(req.url);

  if (url.pathname === "/api/users" && req.method === "GET") {
    return Response.json({ users: [] });
  }

  return new Response("Not Found", { status: 404 });
});
Deno で Hono を使用する
import { Hono } from "https://deno.land/x/hono/mod.ts";

const app = new Hono();

app.get("/", (c) => c.text("Hello Deno!"));
app.get("/api/users", (c) => c.json({ users: [] }));

Deno.serve(app.fetch);
Fresh フレームワークの使用
// routes/index.tsx
import { PageProps } from "$fresh/server.ts";

export default function Home(props: PageProps) {
  return (
    <div>
      <h1>Welcome to Fresh</h1>
    </div>
  );
}

// routes/api/users.ts
import { Handlers } from "$fresh/server.ts";

export const handler: Handlers = {
  async GET(_req, _ctx) {
    const users = await getUsers();
    return Response.json(users);
  },
};
データベース統合
// Using Deno KV (built-in key-value store)
const kv = await Deno.openKv();

// Set a value
await kv.set(["users", "1"], { name: "John", email: "[email protected]" });

// Get a value
const result = await kv.get(["users", "1"]);
console.log(result.value);

// List values
const entries = kv.list({ prefix: ["users"] });
for await (const entry of entries) {
  console.log(entry.key, entry.value);
}
環境変数
// Access environment variables (requires --allow-env)
const apiKey = Deno.env.get("API_KEY");

// Using dotenv
import { load } from "https://deno.land/std/dotenv/mod.ts";
const env = await load();
組み込みテストランナーでのテスト
// user_test.ts
import { assertEquals, assertRejects } from "https://deno.land/std/assert/mod.ts";
import { describe, it, beforeEach } from "https://deno.land/std/testing/bdd.ts";
import { getUser, createUser } from "./user_service.ts";

describe("User Service", () => {
  beforeEach(() => {
    // Setup
  });

  it("should create a user", async () => {
    const user = await createUser({ name: "John", email: "[email protected]" });
    assertEquals(user.name, "John");
  });

  it("should throw for invalid email", async () => {
    await assertRejects(
      () => createUser({ name: "John", email: "invalid" }),
      Error,
      "Invalid email"
    );
  });
});

// Run tests
// deno test --allow-net --allow-read
組み込みツール
# Formatting
deno fmt

# Linting
deno lint

# Type checking
deno check main.ts

# Bundle
deno bundle main.ts bundle.js

# Compile to executable
deno compile --allow-net main.ts

# Documentation generation
deno doc main.ts

# Dependency inspection
deno info main.ts
deno.json による設定
{
  "tasks": {
    "dev": "deno run --watch --allow-net --allow-env main.ts",
    "start": "deno run --allow-net --allow-env main.ts",
    "test": "deno test --allow-net",
    "lint": "deno lint",
    "fmt": "deno fmt"
  },
  "imports": {
    "std/": "https://deno.land/[email protected]/",
    "@/": "./src/"
  },
  "compilerOptions": {
    "strict": true,
    "lib": ["deno.window"]
  },
  "lint": {
    "rules": {
      "tags": ["recommended"]
    }
  },
  "fmt": {
    "indentWidth": 2,
    "singleQuote": true
  }
}
エラーハンドリング
class AppError extends Error {
  constructor(
    message: string,
    public statusCode: number = 500,
    public code: string = "INTERNAL_ERROR"
  ) {
    super(message);
    this.name = "AppError";
  }
}

const handleRequest = async (req: Request): Promise<Response> => {
  try {
    return await processRequest(req);
  } catch (error) {
    if (error instanceof AppError) {
      return Response.json(
        { error: error.message, code: error.code },
        { status: error.statusCode }
      );
    }
    console.error(error);
    return Response.json(
      { error: "Internal Server Error" },
      { status: 500 }
    );
  }
};
Web 標準

Deno は Web 標準を取り入れています。以下を使用します:

  • HTTP リクエストには fetch() を使用します
  • Request と Response オブジェクトを使用します
  • URL と URLSearchParams を使用します
  • 暗号化には Web Crypto API を使用します
  • データストリーミングには Streams API を使用します
  • マルチパートデータには FormData を使用します
パフォーマンス
  • 大規模なデータ処理には Web ストリームを使用します
  • 高速なキー・バリュー型ストレージには Deno KV を活用します
  • 高性能な HTTP 処理には Deno.serve を使用します
  • デプロイ用にスタンドアロン実行ファイルへコンパイルします

コメント