gd

GDScript.
Beyond the scene.

GDScriptを、
もっと自由に。

From a quick script to a web service. Bring the language you know to your terminal, with tools for the work ahead.

ちょっとした自動化からWebサービスまで。使い慣れた言語と、必要な道具をターミナルへ。

hello.gdHTTP / JSON
var app := GD.web.app()

func hello(_req):
    return GD.web.json({"message": "Hello!"})

func main():
    app.route("GET", "/", hello)
    app.listen(8080, "127.0.0.1")!
    return 0
gd serve hello.gd
Installインストール
curl -fsSL https://gd.progsha.com/install.sh | sh
curl -fsSL https://gd.progsha.com/install.sh | sh
Invoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1

01 /

Make it a script.

日々の作業を、自動化。

Files, text, processes, and scheduled jobs. Turn repeated work into a command.

ファイル、文字列、プロセス、定期実行。繰り返す作業を、ひとつのコマンドに。

Explore the tools →道具を見る →
02 /

Put it on the web.

Webへ、つなげる。

Routes, JSON, templates, and middleware. Build an API with the web tools already included.

ルーティング、JSON、テンプレート、ミドルウェア。組み込みの道具でAPIを作る。

Build a web service →Webサービスを作る →
03 /

Work with your data.

データを、使える形に。

Read structured files, query a database, and add packages as your project grows.

構造化ファイルの読み書きから、データベースへのクエリまで。パッケージで広がる開発。

Connect a database →データベースを使う →

The documentation.

ドキュメント

gd 0.8.0 / REFERENCE

gd 公式マニュアル

English | 日本語

gdは何のための道具か

gdは、GDScriptでCLIツール、Webサイト、Web API、定期処理、データ処理を書くための単体コマンドです。 画面表示を使わない小さな実行環境をGodotから作っています。project.godotを用意せず、1つの.gdファイルを書くだけで実行できます。

PythonやNode.jsでスクリプトを書く感覚で始められます。必要に応じて型検査やテストを加え、パッケージ、データベース、Webサーバーも使えます。完成したスクリプトは、1つの実行ファイルにまとめて配布できます。ゲームの画面や描画を作る用途にはGodot本家を使ってください。

Godot本家とあわせれば、アプリもフロントもサーバーもCLIツールも、一つの言語GDScriptで書けます。 同じスクリプトがmacOS、Linux、Windowsで動き、通信とデータベースの待ちはほかの処理を止めません。 GDExtensionでC++と直接つながります。

速度も重視しています。HTTP/2に対応し、通信を待つ間もほかの処理が進みます。文字列とJSONの処理も高速です。

導入

配布バイナリはmacOS arm64/x86_64、Linux x86_64、Windows x86_64向けです。Linux arm64はソースからビルドできます。 ReleasesからOSに合うアーカイブを取得し、gdをPATHの通ったディレクトリへ置く方法も使えます。

macOS / Linux

curl -fsSL https://gd.progsha.com/install.sh | sh

~/.local/binへ導入します。PATHに未設定の場合だけy/Nで追加を確認します。yを選ぶと利用中のシェルに合う設定へ保存し、新しいターミナルから使えます。Linux配布バイナリにはx86_64とglibc 2.38以降が必要です。

Windows(PowerShell)

Invoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1

導入先がPATHに未設定の場合だけy/Nで確認し、yを選ぶとユーザーのPATHへ追加します。

Homebrew(macOS)

brew tap prog-sha/gd https://github.com/prog-sha/gd
brew install prog-sha/gd/gd

apt(Linux amd64)

Ubuntu 24.04、Debian 13など、glibc 2.38以降のapt対応環境で利用できます。

sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://gd.progsha.com/apt/gd.asc | sudo tee /etc/apt/keyrings/gd.asc >/dev/null
sudo chmod 0644 /etc/apt/keyrings/gd.asc
echo 'deb [arch=amd64 signed-by=/etc/apt/keyrings/gd.asc] https://gd.progsha.com/apt stable main' | sudo tee /etc/apt/sources.list.d/gd.list
sudo apt update
sudo apt install gd

更新

gd upgrade            # Move to the latest release.
gd upgrade 0.8.0      # Move to a chosen version.
gd upgrade --dry-run  # Show the version without installing it.

配布元のSHA-256と照合してから、実行中のgdを置き換えます。Homebrewやaptで入れたgdは、それぞれのbrew upgrade gd、apt upgrade gdで更新してください。

ソースからビルド

Python、uv、SCons、C/C++コンパイラーを用意します。実行ファイルはbin/に生成されます。

git clone --branch master https://github.com/prog-sha/gd.git
cd gd
scons platform=macos target=template_release -j8
# Linux ARM64: platform=linuxbsd arch=arm64
# Linux x86-64: platform=linuxbsd arch=x86_64
# Windows: platform=windows arch=x86_64 use_mingw=yes windows_subsystem=console

クイックスタート

hello.gdを1つ作ります。設定ファイルやパッケージは要りません。main()が入口で、返した整数がプロセスの終了コードになります。

func main():
	print("Hello, world")
	return 0
gd hello.gd

実行せずに型と構文を調べるにはcheckを使います。

gd check hello.gd

スクリプトの読み込みと共通定数

ローカルファイルは@import "./settings"、導入済みパッケージは@import hello。読み込んだ名前をそのまま使います。.gdやas settingsは省略できます。

共有する値をsettings.gdに置きます。

const TITLE = "Hello"
const USER = "world"

main.gdから使います。

@import "./settings"

func main():
	print(settings.TITLE, ", ", settings.USER, "!")
	return 0

これでHello, world!と表示します。共有が必要になったときの書き方です。

  • 1つのスクリプトでしか使わない値や処理は、そのスクリプトに置けば十分です。
  • asは、名前がぶつかるときだけ使います。
  • 組み込みのGD.webなどは、importなしで使えます。

パッケージの導入とバージョン固定はパッケージと配布を参照してください。

用途から選ぶ

標準APIはGDにまとまっています。ファイル操作はGD.file、WebサービスはGD.webのように、用途に合わせて選びます。

やりたいこと入口例
ファイル、文字、日時、HTTP クライアント、非同期処理GDGD.file.read_text("a.txt")
WebサイトとWeb APIGD.webGD.web.app()
SQLiteまたはPostgreSQLGD.databaseGD.database.client()
RedisGD.database.redisGD.database.redis.client()
TCP、UDP、TLSGD.netGD.net.listen_tcp("127.0.0.1", 8080)
メールの解析とSMTP送信GD.mailGD.mail.parse_address("me@example.com")

APIの調べ方

コマンドの使い方はgd --help、コマンドごとの引数とオプションはgd install --helpのように調べます。

APIはgd doc GD.file.read_textのように、調べたい関数や型の名前を渡します。関数名・引数・戻り値の情報は、実行プログラムから取得しています。

gd doc                     # Show a short guide and entry points.
gd doc manual              # Read the complete manual.
gd doc GD                  # List the standard modules.
gd doc GD.file             # file API
gd doc GD.http.fetch       # Inspect the returned HTTP response.
gd doc GD.web.app          # Web application
gd doc SceneTree           # Inspect a public engine class.
gd doc all                 # List public types.

戻り値に使われる型のErr、GDWebRequestは名前だけで引きます。Node、SceneTree、TimerなどGodot由来の型は Godotのクラスリファレンスも参照してください。 手引きの言語はLC_ALLまたはLANGがjaで始まるとき日本語、それ以外は英語です。 Web版はgd.progsha.comにあり、日本語と英語を切り替えられます。

GDScriptの基本

掲載例では型名を繰り返しません。:=で代入する変数は右辺から型を推論します。 注釈を省いた引数は動的型です。受け取る値や返す値の型を限定したい箇所には、型名を書けます。

引数とオプション

スクリプト名の後ろに置いた引数はmain(argv)で受け取ります。--name=gdのようにgd自身のオプションと紛らわしい引数は、 --の後ろへ置くとスクリプトへ渡ります。

func main(argv):
	for arg in argv:
		print(arg)
	return 0
gd main.gd apple orange
gd main.gd -- --name=gd

オプションとして解釈したいときはGD.cli.flags()を使います。--name gd、--name=gd、-name=gdのどの綴りも受けます。

func main(argv):
	var flags := GD.cli.flags()
	flags.flag_str("name", "world", "挨拶する相手")
	var _parsed, parse_err := flags.parse(argv)
	if parse_err:
		print(flags.usage())
		return 1
	print("Hello, " + flags.get_str("name"))
	return 0

外のコマンドを呼ぶ

外の道具はGD.cli.run()で呼びます。待つのは呼び出したGDScriptだけなので、gd serveのハンドラーの中から呼んでも他のリクエストは進みます。 --strictでは--allow-runが要ります。--allow-run=/usr/bin/gitのように相手を絞れます。

func main():
	var got, err := await GD.cli.run("git", ["rev-parse", "HEAD"])
	if err:
		return 1
	print("code=", got["code"], " out=", got["output"])
	return 0

子プロセスの終了コードが0以外ならErrを返します。終了コードはvalue.code、出力はvalue.outputで読めます。時間切れやキャンセルのときも、そこまでの出力は残ります。

第3引数のoptsで挙動を変えられます。

名前既定意味
timeout0完了を待つ秒数。0は無期限。時間を超えると子プロセスを終了し、Err.TIMED_OUTを返す
outputtrue出力を集める。falseなら親の標準入出力へ直結し、集めない

処理結果とエラー

失敗する可能性がある関数は、値とErrの2つを返します。 var 値, e :=で両方を受け取れます。型は関数の宣言から推論され、eがnullでなければ失敗です。 既存の変数には値, e = call()で代入できます。先に型なしで宣言した変数はVariantのままなので、静的に型を検査するならvar 値: Tとvar e: Errを宣言します。

func main():
	var text, e := GD.file.read_text("note.txt")
	if e:
		print(e.text())
		return 1
	print(text)
	return 0

エラー処理を短く書く

関数呼び出しの末尾に?を付けると、失敗時は値とErrを呼び出し元へ返します。成功時は値だけを使えます。 ?を使う関数は値とErrを返します。返却型を省くとreturnの値から第一結果を推論し、必要なら-> String, Errのように明示できます。正常時のreturn 値は、第二結果のnullを省略した形です。

func title(path) -> String, Err:
	var text := GD.file.read_text(path)?
	return text.strip_edges()

func main():
	var text, e := title("note.txt")
	if e:
		print(e.note("題名を読む").text())
		return 1
	print(text)
	return 0

自分でエラーを返す

ファイルを読めても、内容が空なら失敗にしたい場合は、自分でErrを作って返します。Err("説明", 種類, 追加情報)の形で、説明文、Err.INVALID_DATAなどの種類、必要な情報を指定します。次をread_message.gdに保存してください。

# Read a message and reject empty contents.
func read_message(path: String) -> String, Err:
    var text := GD.file.read_text(path)?
    if text.strip_edges().is_empty():
        return "", Err("Message is empty", Err.INVALID_DATA, {"path": path})
    return text, null

# Print the message or report the failure to the caller.
func main() -> int:
    var text, err := read_message("message.txt")
    if err != null:
        printerr(err)
        return 1
    print(text)
    return 0
printf 'Hello!\n' > message.txt
gd read_message.gd
printf '' > message.txt
gd read_message.gd

最初の実行はHello!を表示し、空ファイルにした後の実行はMessage is emptyというエラーを表示して終了コード1を返します。

  • -> String, Errは、文字列とエラーの2つを返すという宣言です。
  • 成功したらreturn text, null、失敗したらreturn "", Err(...)を返します。
  • 呼び出し側はvar text, err := read_message(...)で受け取り、errを確かめてからtextを使います。
  • ファイルを読めなかったときは、?がそのエラーをそのまま返します。

待つ処理と同時実行

HTTP、データベース、GD.net、ファイルなどの待つメソッドは、普通の関数呼び出しとして書けます。 待つのは呼び出したGDScriptだけで、ほかの通信やタイマーは進みます。

func main():
	var res := GD.http.fetch("https://example.com/")!
	print(res.status)
	return 0

複数の処理を同時に始めたいときは、末尾が_asyncの版とGD.async.all()を使います。

func main():
	var got = await GD.async.all([
		GD.http.fetch_async.bind("https://example.com/a"),
		GD.http.fetch_async.bind("https://example.com/b"),
	])
	for result: Array in got:
		var res: GDHTTPResponse = result[0]
		var e: Err = result[1]
		if e:
			print(e.text())
			return 1
		print(res.status)
	return 0
入口用途
名前_async()処理を始め、結果を保持するGDTaskをすぐ返す。ほかの処理を待った後でも、awaitすると通常名と同じ結果を受け取れる。cancel()で取り消せる
GD.async.all(list)複数の処理を同時に進め、結果を渡した順に返す
GD.async.spawn(fn)関数を裏で動かす。main()が返った後も動く
GD.async.sleep(sec)指定秒だけ待つ

1つだけ待つときはvar value, e := await GD.http.fetch_async(url)のように、通常名と同じ形で受け取れます。

先に始めた処理を、あとから順に受け取ることもできます。firstを待つ間にsecondが終わっても、結果はsecondが保持しています。

func main():
	var first := GD.http.fetch_async("https://example.com/a")
	var second := GD.http.fetch_async("https://example.com/b")
	var a, a_err := await first
	var b, b_err := await second
	if a_err or b_err:
		return 1
	print(a.status, " ", b.status)
	return 0

気を付ける点は3つです。

  • all()には、_async()が返したGDTaskか、上の例のように.bind()で作ったCallableを渡します。どちらも、先に終わった処理の結果を取りこぼしません。
  • spawn()は処理を別スレッドへ移しません。大きなデータを標準モジュールで処理するときは_asyncの版を使います。
  • 待つメソッドはmain()や自分で書いた関数の中で呼びます。Array.map()へ渡す関数、_init()、メンバー変数の初期化の中では待てないので、forかGD.async.all()で書きます。

チュートリアル: SQLiteを使うメモAPI

ここまでの知識で、JSONを受けてSQLiteへ保存する小さなAPIを1つのスクリプトで作ります。 できあがるのは、入力を検査し、SQL文と値を分けて渡す、権限を絞って起動する開発用サーバーです。

1. 作業ディレクトリを作る

mkdir notes-api
cd notes-api

2. APIを書く

次をmain.gdとして保存します。

# Store notes in an embedded database and expose a JSON API.
extends RefCounted


const PORT := 18080 # Development listener port on loopback.
const DB_PATH := "user://notes.sqlite3" # Writable storage isolated per user.

var app := GD.web.app()
var db := GD.database.client()


# Return notes as JSON in newest-first order.
func list_notes(req: GDWebRequest) -> GDWebResponse, Err:
	var got, query_err := await GD.async.with_context_pair(req.context, db.query_async("SELECT id, title FROM notes ORDER BY id DESC"))
	if query_err:
		return query_err
	return GD.web.json(got.rows)


# Save a validated title and return the created row.
func add_note(req: GDWebRequest) -> GDWebResponse, Err:
	var body := req.valid("body")
	var made, query_err := await GD.async.with_context_pair(req.context, db.query_async(
		"INSERT INTO notes(title) VALUES($1) RETURNING id, title",
		[body.title]
	))
	if query_err:
		return query_err
	return GD.web.json(made.rows[0], 201)


# Prepare the database and routes, then listen on loopback.
func main() -> int, Err:
	db.open({"driver": "sqlite", "path": DB_PATH})?
	db.query("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT NOT NULL)")?
	app.route("GET", "/notes", list_notes)
	app.route("POST", "/notes", add_note, [GD.web.json_body(GD.web.object_rule({
		"title": GD.web.text_rule({"min": 1, "max": 120}),
	}))])
	app.listen(PORT, "127.0.0.1")?
	print("listening on http://127.0.0.1:%d" % PORT)
	return 0

上から順に読みます。

  • appはルーター、dbはデータベース接続です。main()が返った後もサーバーが動き続けられるよう、両方ともスクリプトの変数として持ちます。
  • main()はまずSQLiteを開き、表を作ります。DB_PATHのuser://は、gdが利用者ごとに用意する書き込み領域です。
  • app.route()に、HTTP メソッド、パス、そのときに呼ぶ関数(ハンドラー)を登録します。
  • ハンドラーはGDWebRequestを受け取り、GD.web.json()で返事を作ります。途中の?は失敗をサーバーへ返し、ステータスコード500などになります。
  • POSTにはGD.web.json_body()を付けています。本文が検証ルールに合うときだけハンドラーが呼ばれ、通った値がreq.valid("body")に入ります。
  • SQLの$1に入れる値は、別の引数で渡します。文字列連結でSQLを組み立てません。

3. 権限を絞って起動する

未確認のスクリプトや外へ公開するサーバーは、権限を既定で拒否する--strictで実行します。ここでは待ち受け先をループバックの一つのポートに絞ります。 serveはmain()が返った後もプロセスを残すコマンドで、サーバーにはこれを使います。

gd check main.gd
gd --strict --allow-net=127.0.0.1:18080 serve main.gd

4. 別の端末から使う

curl -s -X POST http://127.0.0.1:18080/notes \
  -H 'Content-Type: application/json' \
  -d '{"title":"gdを試す"}'
curl -s http://127.0.0.1:18080/notes

最初はステータス 201と作成した一件、次は保存済みの配列が返ります。空の題名、120文字を超える題名、 JSONでない本文は400で拒否されます。止めるときは起動したターミナルでCtrl-Cを押します。

公開環境ではこのプロセスをループバックのままTLS リバースプロキシの後ろへ置き、異常終了耐性が必要な保存先は PostgreSQLへ切り替えます。接続情報はソースへ書かず、許可した環境変数から読みます。

権限

最初は通常実行を使います。--strictは、必要な権限を自分で設計・設定する上級者向けの実行方式です。

方式向く場面制限
通常実行信頼できるソースを開発中に動かすファイルもネットワークも制限しない
--strict未確認のスクリプト、公開サーバー起動ディレクトリ配下は読み取り専用で、外部の絶対パスは拒否。ネットワーク、環境変数、子プロセス、ネイティブ拡張機能、システム情報を既定で拒否

--strictでは、使うものを挙げて起動します。

gd --strict \
  --mount store=/srv/app:rw \
  --allow-net=db.example.com:5432 \
  --allow-env=DATABASE_URL \
  main.gd
指定許すもの
--mount name=path:r / --mount name=path:rw名前を付けたディレクトリの読み取り、または読み書き
--allow-net=host:port,...接続と待ち受け。値を省くと全て
--allow-env=name,...環境変数
--allow-run=command,...子プロセス
--allow-ext=path,...スクリプトが実行中に読むネイティブ拡張機能
--allow-sys=item,...機種とシステム情報
--deny-*対応するallowより優先する拒否
-Aファイル以外を全て許す。開発中の一時的な利用向け

--strictが効くのは、スクリプトを実行するrun、serve、test、task、eval、replです。checkやfmt、パッケージ操作のようにスクリプトを実行しないコマンドには影響しません。

ファイルの置き場

スクリプトから見えるファイルの置き場は次の4種類です。置き場の名前をパスの先頭に書くか、絶対パスをそのまま書きます。

書き方指す場所strictでの扱い
res://a.txtスクリプトを起動したディレクトリ読み取り専用
user://a.txt実行したスクリプトごとに、利用者のデータ領域に用意する書き込み領域。再起動しても残る読み書き可能
store://a.txt--mount store=/srv/app:rwで付けた名前指定した権限
/etc/hostsこのコンピューター上の指定した場所起動ディレクトリの外なら拒否

迷ったら、読むだけのファイルはres://、保存するファイルはuser://へ置きます。

  • strictで起動ディレクトリの外を使うときは--mountで名前を付けます。-Aを付けてもファイルの範囲は広がりません。
  • マウント名はstoreやuploadsのように、小文字の英数字と-で付けます。gdが使っている次の名前は選べません: res、user、uid、pipe、local、libgodot、tcp、unix、http、https、file、data、cache、pkg、global。
  • Windowsでは--mountと絶対パスを使えません。res://かuser://へ置いてください。

ネットワークと拡張機能の許可

  • --allow-netのlocalhost:8080は、同じポートのIPv4 ループバック 127.0.0.0/8とIPv6 ::1も表します。
  • *.example.com:443はその下位ホストを許します。
  • ネイティブ拡張機能は同じプロセスで動くため、信頼できるものに限ってください。

serveとSceneTree

gd serveはSceneTreeを作らない常駐用の実行方式です。通信、タイマー、await、自作Signal、GD.async.sleep()、 ツリー外Nodeのqueue_free()は動きます。仕事が無ければ次の期限か通信の通知まで眠るため、周期の調整は要りません。

やりたいこと方法
Webサーバーや定期処理を常駐させるgd serve main.gd
Nodeの_process()、_physics_process()、process_frame、SceneTreeTimer、高水準マルチプレイを使うserveを付けない通常実行
SceneTreeやMainLoopを継承したスクリプトを動かすserveを付けない通常実行
SceneTreeが紛れ込んでいないか開発中に調べるgd --no-scene-tree --allow-net serve app.gd
複数プロセスで待ち受ける--workers=<n>または--workers=auto。nは1以上の整数

serveではNodeを継承しただけのスクリプトはツリーへ追加されません。 --no-scene-treeはSceneTreeが作られた時点で診断を出し、終了コード 1で止まります。--watchと--workersの子にも引き継がれます。

TCPとUDP

低水準の通信にはGD.netを使います。Godot本家の低水準の型も使えますが、新しいコードはGD.netで書きます。

func echo() -> int, Err:
	var listener := GD.net.listen_tcp("127.0.0.1", 8080)?
	var conn := listener.accept()?
	var data := conn.read(65536)?
	conn.write(data)?
	conn.close()
	return 0
  • GDTCPConnは読み取りと書き込みを別々の順番待ちで処理するため、複数のGDScriptから同時に呼べます。
  • 期限メソッドは今からの秒数を設定し、0で解除します。
  • close()を呼ぶと、待っている読み書きはErr.INTERRUPTEDで終わります。リスナーの受付待ちも同じです。
  • 接続は名前解決で得たIPv4とIPv6の候補を順に試し、成功した一本だけを残します。全体のtimeoutは延びません。

TLS

TLSはGD.net.dial_tls(host, port, opts)で開きます。既定で証明書チェーンと接続先のホスト名を検証し、失敗しても平文へ戻りません。 戻り値はTCPと同じGDTCPConnです。

opts意味
timeout接続とTLSの初期通信が完了するまでの制限時間(秒)
ca_file私設CA。環境変数の設定より優先する
cert_file、key_fileクライアント認証。許可されたマウント内のファイルを対で指定する
server_name証明書を照合する宛名を接続先と別にする
next_protosALPN名の配列。1名は1–255 バイト、全体で65535バイトまで
insecure_skip_verify検証を省く。検証不要と判断できる試験時だけ使う

交渉結果はconnection_state()のnegotiated_protocolとversionで読めます。TLS1.2は771、TLS1.3は772です。

信頼するCAは、未指定ならmacOSとWindowsではOSの信頼設定、Linuxではシステム CA証明書の一覧です。 起動前にSSL_CERT_FILEまたはSSL_CERT_DIRを設定すると、どのOSでも指定したCAを使います。 ディレクトリの区切りはUnixで:、Windowsで;です。

サーバーがクライアント証明書を求めるときは、app.listen_tls(port, cert, key, host, opts)のoptsへclient_ca(信頼するCA証明書の一覧)とclient_authを渡します。 client_caが未指定ならシステムの信頼設定を使います。

client_auth動作
none証明書を要求しない
request任意提示。検証しない
require提示だけ必須。検証しない
verify_if_given提示された場合だけ検証する
require_and_verify検証済みの証明書を必須にする

UDPと名前解決

UDPはGD.net.listen_udp()で開きます。届いたパケットには送り主のhostとportが入っているので、そのまま返信できます。

func echo_udp() -> int, Err:
	var conn := GD.net.listen_udp("127.0.0.1", 9000)?
	var packet := conn.read_from()?
	conn.write_to(packet.data, packet.host, packet.port)?
	conn.close()
	return 0
  • write_to()の宛先はIPアドレスで渡します。ホスト名は先にGD.net.resolve(name)?でIPアドレスにします。
  • 1回のread_from()が1つのパケットです。受け取る大きさを超えた分は捨てられ、packet.truncatedがtrueになります。
  • このコンピューターのアドレスはGD.net.local_addresses()で調べます。

メール

GD.mailはメールアドレスやヘッダーを解析し、SMTPサーバーへメールを送ります。

  • send_mailには、ヘッダーと本文を含むメール全体をバイト列で渡します。
  • 成功は「SMTPサーバーが受け取った」という意味で、相手に届いたことまでは保証しません。
  • --strictでは、接続先に--allow-netが要ります。
func main() -> int, Err:
	var message := "From: me@example.com\r\nTo: you@example.com\r\nSubject: Hello\r\n\r\nHello\r\n".to_utf8_buffer()
	GD.mail.send_mail("smtp.example.com", 587, "me@example.com", PackedStringArray(["you@example.com"]), message, {
		"tls": "starttls", "timeout": 10.0,
		"auth": GD.mail.plain_auth("me@example.com", "secret"),
	})?
	return 0

ファイルとデータ

GD.fileでファイルの読み書きとパス操作をします。起動したディレクトリがres://で、絶対パスも書けます。 strictで外部ディレクトリへ書くときは--mount store=/srv/app:rwで付けた名前をstore://users.csvのように書きます。

func main() -> int, Err:
	var rows := GD.data.csv_objects(GD.file.read_text("store://users.csv")?)?
	GD.file.write_text("store://users.json", JSON.stringify(rows))?
	return 0

ファイルの操作は、通常名でも呼び出したGDScriptだけを待たせます。Webサーバーのハンドラーから読んでも他のリクエストは進みます。 複数の操作を同時に始めるときだけ、末尾が_asyncの版を使います。

func handler(_req) -> GDWebResponse:
	var body, read_err := GD.file.read_text("store://big.json")
	if read_err:
		return GD.web.text("読めません", 500)
	return GD.web.text(body)

compileで同梱したファイルも、同じAPIで読み取り、列挙、static配信ができます。

大きなファイルを読む

全体をメモリへ置かず読むときはGD.file.open(path, mode)でGDFileStreamを開きます。 modeはread、write、append、read_writeで、使い終えたらclose()を呼びます。

メソッド動作
read(max)最大max バイトを返す。少なく返ることがある。maxが正のとき、エラーがなく空ならファイルの末尾まで読み取り済み
write(bytes)全て書いてバイト数を返す。途中で失敗しても第一結果に書き込み済みバイト数が残る

同じストリームの操作は受付順、別のストリームは並列に進みます。appendはseekの後も常に末尾へ書きます。 read_bytes()も途中で失敗したときは取得済みのバイト列を第一結果に残します。 read_text()はStringに収まらない大きさの入力を切り詰めずエラーにするので、大きなファイルはバイト列かストリームで扱います。

同時に更新されるファイル

複数のプロセスが同じファイルを更新するときはGD.file.replace_text(path, old, body)を使います。 読み取ったoldと現在の内容が同じときだけ置き換えるため、並行編集を黙って上書きしません。新規作成ではoldにnullを渡します。

データ形式の入口

用途入口
CSV、TOML、YAML、JSONL、JSONC、XML、INI、TAR、front matter、.envのファイルを読むGD.file.read_csv(path)など
同じ形式のメモリ上の変換、JSON、エンコード・デコード、ハッシュ、HMAC、PBKDF2、HKDF、バイト列GD.data
UUIDとULIDGD.id
日時の変換と計算GD.time
文字の整形と比較GD.text
HTML エンティティ、タグ、gdhtml(Mustache構文のマイクロテンプレート)GD.html
オプションと環境変数GD.cli
配列と辞書の操作GD.collection
数学の特殊値とビット演算GD.math
バージョンの比較GD.version
ターミナルとファイルへのログGD.log
テストの検査GD.test

環境変数と.envは、読む対象で入口が分かれます。

読む対象入口
プロセスの環境変数GD.cli.env(name, fallback)、GD.cli.require_env(name)。strictでは--allow-envが要る
.env ファイルGD.file.read_env(path)。ファイルを読んで辞書にする
dotenv形式の文字列GD.data.env(src)とGD.data.to_env(data)。メモリ上で辞書と変換する

メモリ上の変換は通常名がその場で計算し、_asyncの版は別のスレッドで計算します。大きな入力には_asyncを使います。 正確な一覧はgd doc GD.fileとgd doc GD.dataで引けます。形式ごとの検査と上限は、APIリファレンスの各入口の説明にあります。

GD.collectionのCallableを使う操作は、約1 msごとにほかの処理へ実行権を譲ります。 GD.logの各呼び出しは書き込み完了まで待ち、本文を切り捨てません。失敗は第二結果のErrで確認でき、GD.log.flush()でそれ以前の出力完了を待てます。

JSONの規則

値はGD.data.json_encode(value)でJSONのバイト列にし、受け取ったバイト列はGD.data.json_decode(bytes)で読みます。 GDWebRequest.json()、GDHTTPResponse.json()、JSONLの各行も同じ規則です。

func main() -> int, Err:
	var bytes := GD.data.json_encode({"id": 1, "tags": ["a", "b"]})?
	var value := GD.data.json_decode(bytes)?
	print(value.id)
	return 0
  • 整数はintのまま戻ります。小数と指数表記はfloatになります。
  • 壊れた文字コードや同じ名前の重複など、あいまいなJSONは読まずに失敗にします。
  • 署名やキャッシュのキーのように、同じ値から毎回同じバイト列が要るときは{"deterministic": true}を渡します。

ハッシュと鍵導出

GD.dataはSHA-1、SHA-224/256/384/512、SHA3-224/256/384/512を返します。HMAC、PBKDF2、HKDFでは sha1、sha224、sha256、sha384、sha512、sha3-224、sha3-256、sha3-384、sha3-512から方式を選べます。 PBKDF2とHKDFは出力長を指定でき、不正な方式や表現範囲外の設定はErrとして返します。PBKDF2の繰り返す回数が1以下なら1回として計算します。

Webフレームワーク

同じディレクトリにmain.gdとindex.htmlを作ります。一方のルートでHTMLテンプレートに挨拶を埋め込み、もう一方で同じデータをJSONとして返します。

main.gd:

# Serve a greeting as an HTML page and a JSON response.
var app := GD.web.app()

# Build the shared response data from the requested name.
func greeting(req: GDWebRequest) -> Dictionary, Err:
	var name := req.query.get("name", "world")
	if not name is String:
		return {}, Err("name must be text", Err.INVALID_DATA)
	return {"name": name, "message": "Hello, " + name + "!"}

# Render the page with escaped template values.
func home(req: GDWebRequest) -> GDWebResponse, Err:
	return GD.web.view("index.html", greeting(req)?)

# Return the same data as JSON.
func hello(req: GDWebRequest) -> GDWebResponse, Err:
	return GD.web.json(greeting(req)?)

# Listen locally, using an optional port argument.
func main(args):
	var port := 8080 if args.is_empty() else int(args[0])
	app.route("GET", "/", home)
	app.route("GET", "/api/hello", hello)
	app.listen(port, "127.0.0.1")!
	print("http://127.0.0.1:", app.port())
	return 0

index.html:

<!doctype html>
<!-- Display a greeting and let visitors choose the name. -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{message}}</title>
  <style>
    body { max-width: 36rem; margin: 4rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; line-height: 1.6; }
    input, button { padding: .6rem; font: inherit; max-width: 100%; box-sizing: border-box; }
  </style>
</head>
<body>
  <h1>{{message}}</h1>
  <form action="/" method="get">
    <label>Your name <input name="name" value="{{name}}"></label>
    <button type="submit">Say hello</button>
  </form>
  <p><a href="/api/hello?name={{name}}">View the JSON response</a></p>
</body>
</html>

そのディレクトリで実行します。

gd serve main.gd

http://127.0.0.1:8080/?name=Aliceを開くと、{{message}}へ「Hello, Alice!」を埋め込みます。/api/hello?name=Aliceは{"name":"Alice","message":"Hello, Alice!"}を返します。テンプレートの値はHTMLの文脈に応じてエスケープされます。

serveはmain()が返ったあとも待ち受けを続けます。終了はCtrl+Cです。

ルートと返事

route(method, pattern, handler)でHTTP メソッドとパスをハンドラーへ結びます。patternの:nameはreq.params["name"]に入ります。 HEADの要求にはGETのルートで応えます。パスは合うのにメソッドが違う要求には405を返します。 ハンドラーはGDWebRequestを受け取ります。本文はreq.read()、bytes()、text()、json()、save()で必要な分だけ読みます。 HTMLのフォームから届く本文はGD.http.decode_query(req.text()?)で辞書にします。

ハンドラーが返した値が返事になります。return GD.web.json(data)のように、下の表の値をそのまま返します。

途中の操作が失敗したら、call()?でそのErrを返します。Errは表の最後の行のステータスコードになります。返事を自分で決めたいときはapp.on_error(handler)を登録します。

返した値返事
GD.web.html(body)、GD.web.view(path, data)HTML
GD.web.json(data)JSON
GD.web.text(body)、GD.web.bytes(body, type)テキスト、任意のメディアタイプ
GD.web.stream(producer)本文を少しずつ送信する。「Webの運用と高度な機能」を参照
GD.web.redirect(to)302。toは同じサイト内のパスに限り、他所へ送るときはawayをtrueにする
GD.web.not_found()404
文字列テキスト/plainの200
bodyを持つ辞書手書きの返事。status、type、headersも指定できる
bodyを持たない辞書JSONの200
null204
失敗のErr種類に応じたステータスコード。INVALID_DATA → 400、UNAUTHENTICATED → 401、PERMISSION_DENIED → 403、NOT_FOUND → 404、LIMITED → 429、UNSUPPORTED → 501、TIMED_OUT → 504、他は500(いずれもErrの定数)

返事は次のように調整できます。

  • ステータスコードはGD.web.text("見つかりません", 404)のように第2引数で変えます。bytesはメディアタイプの後ろに書きます。
  • GD.web.header(reply, name, value)で返事にヘッダーを足します。
  • GD.web.guard(reply)でContent-Security-Policyなどの防御ヘッダーをまとめて足します。
  • 失敗の理由は既定では本文に出しません。開発中はapp.show_errors(true)で表示できます。
  • req.queryの値は文字列とは限りません。上の例のようにis Stringで確かめてから使います。
  • req.pathは%20などを元の文字へ戻したパスです。届いたままの文字列はreq.targetで読めます。

ルーターには次も登録できます。

登録用途
app.static("/assets", "res://public")接頭辞以下のGETとHEADをディレクトリのファイルで返す。メディアタイプは拡張子から決め、ディレクトリの外は返さない。/のindexはrouteで書く
app.group("/api", [middleware])共通接頭辞とミドルウェアを持つルートグループ。戻り値にroute()とuse()がある
app.fallback(handler)どのルートにも一致しない要求。404ページをここで返す
app.on_error(handler)ハンドラーが失敗を返したときの返事
app.after(handler)返事を送る前の加工。func(req, reply)で受け、ヘッダーを足して返す

ミドルウェア

ミドルウェアは、ハンドラーの前に呼ばれる関数です。GDWebRequestを受け取り、nullを返すと次へ進み、返事を返すとそこで止まります。 handle(req)を持つオブジェクトも使えます。後段へ渡す値はreq.keep(name, value)で置き、req.kept(name)で読みます。

登録掛かる範囲
app.pre(mw)ルート選択の前。全要求
app.use(mw)ルート選択の後。全ルート。req.paramsを読める
group.use(mw)そのグループのルート
app.route(method, pattern, handler, [mw])そのルートだけ

入力検査もミドルウェアです。GD.web.json_body(rule)、GD.web.query(rule)、GD.web.params(rule)が本文、クエリ、パスの値を検査し、 通った値をreq.valid("body")、req.valid("query")、req.valid("params")に入れます。 検証ルールはGD.web.text_rule()、int_rule()、number_rule()、bool_rule()、list_rule()、object_rule()で組み、 GD.web.optional()とGD.web.one_of()で省略と選択肢を表します。クエリとparamsの値は文字列なのでtext_rule()で検査し、必要ならto_int()で変換します。

var app := GD.web.app()

func show(req) -> GDWebResponse, Err:
	var params := req.valid("params")
	return GD.web.json({"id": params.id})

func main():
	app.route("GET", "/posts/:id", show, [GD.web.params(GD.web.object_rule({"id": GD.web.text_rule({"min": 1, "max": 20})}))])
	app.listen(8080)!
	return 0

組み込みのミドルウェアはGD.web.sessions()、GD.web.csrf()、GD.web.jwt()、GD.web.rate()です。認証の節で使います。

HTMLテンプレート

ページが増えてきたらHTMLをテンプレートファイルへ出し、GD.web.view(path, data)で描画します。 テンプレートはgdhtml(Mustache構文のマイクロテンプレート)で、{{name}}、{{{html}}}、#if、#unless、#each、 #with、else、{{> header}}を扱います。views/page.htmlから{{> header}}を使うと、 同じ階層のviews/partials/header.htmlを読みます。

<!-- views/page.html -->
{{> header}}
<main><h1>{{title}}</h1></main>
<!-- views/partials/header.html -->
<header><a href="/">gd app</a></header>
func page(_req) -> GDWebResponse, Err:
	return GD.web.view("views/page.html", {"title": "Top"})

二重括弧の値は、置かれた位置から文脈を判定してエスケープします。テンプレートの作者を信頼し、差し込む値を信頼しない前提です。

文脈扱い
HTML本文、引用・未引用属性、属性名HTML エスケープ
href="{{url}}"相対URLとhttp、https、mailtoを通す。data-hrefも同じ
href="/work/{{path}}"、href="/?q={{query}}"パスは区切りを保って正規化、クエリはpercent エスケープ
onclick、script本文JSON化し、application/jsonでも</script>が構造を壊さない形にする
style安全な単独CSS値とCSS文字列・URLを通す
危険なURL、srcset、CSS値、属性名画面全体を失敗させず、#ZgdunsafeZまたはZgdunsafeZへ置き換える
  • 三重括弧{{{html}}}はエスケープしない唯一の入口で、HTML本文以外では使えません。固定HTMLか十分に検査済みの値だけを渡してください。
  • 「検査済み」の印を付けて二重括弧のエスケープを省く方法はありません。
  • 分岐の両側やeachの反復が異なる文脈で終わるテンプレート、閉じていないタグ、曖昧なURLやJavaScript文脈は描画の失敗になります。
  • テンプレートの大きさに固定上限はありません。再帰する部品の深さだけは100000までです。
  • 描画が終わるまで、渡した辞書を変更しないでください。

同じテンプレートを何度も描画するサーバーでは、起動時にGD.html.template(source, partials)?で一度だけ解析し、 返った値のexecute(data)?を各要求から呼びます。解析結果は不変で、複数の要求から同時に使えます。 execute_bytes(data)?はUTF-8のバイト列を直接作るので、GD.web.bytes(body, "text/html; charset=utf-8")でそのまま返せます。

認証とCSRF

ログインの状態はGD.web.sessions()で持ちます。issue(value)でセッション IDを作り、cookie(id)の値をSet-Cookieで返します。 同じstoreをミドルウェアとして付けたルートでは、CookieのIDに対応する値がreq.kept("user")に入り、無ければ401になります。 ミドルウェアの設定が不正なら生成関数はnullを返し、app.use()やルートに渡した場合はapp.listen()が設定エラーを返します。

var app := GD.web.app()
var sessions := GD.web.sessions()

func login(req: GDWebRequest) -> GDWebResponse, Err:
	var form := GD.http.decode_query(req.text()?)?
	var user := str(form.get("user", [""])[0])
	if user.is_empty():
		return GD.web.text("user is required", 400)
	var reply := GD.web.redirect("/me")
	return GD.web.header(reply, "Set-Cookie", sessions.cookie(sessions.issue(user)?))

func me(req) -> GDWebResponse, Err:
	return GD.web.text("hello, " + str(req.kept("user")))

func main():
	app.route("POST", "/login", login)
	app.route("GET", "/me", me, [sessions])
	app.listen(8080)!
	return 0

cookie(id)はSecureとHttpOnly付きで作ります。TLSなしの開発中に届かない場合はcookie(id, false)にします。 ログアウトはdrop(id)とclear_cookie()で行います。セッションはプロセス内で持つため、--workersで複数プロセスにするときはJWTか外部の保存先を使います。

Cookieで認証する書き込み経路にはGD.web.csrf()を付けます。GET、HEAD、OPTIONS以外はブラウザーの Sec-Fetch-Site: same-originが必要です。古いブラウザーやブラウザー以外のクライアントも受ける場合に GD.web.csrf({"allow_missing": true})を選び、別のトークン検証を組み合わせてください。

var app := GD.web.app()
var sessions := GD.web.sessions()

func save_email(_r):
	return "saved"

func main():
	app.route("POST", "/account/email", save_email, [GD.web.csrf(), sessions])
	app.listen(8080)!
	return 0

JWTをログインセッションに使う場合は、パスワード変更やログアウトで既発行トークンを失効させます。 checkは署名と標準クレームの検証後に呼ばれ、trueを返したときだけ認証を通します。 例えばトークンへ利用者のverを入れ、パスワード変更時に保存済みバージョンを増やします。 複数ワーカーでは各プロセスの辞書でなく、共有DBから同期したキャッシュなどで照合します。

func token_auth(key, versions):
	return GD.web.jwt(key, {"check": func(claims):
		return versions.get(claims.get("sub", ""), -1) == claims.get("ver", -2)
	})

リバースプロキシの後ろでIP単位に制限するときは、そのプロキシのIPまたはCIDRをtrusted_proxiesへ明示します。 gdはX-Forwarded-Forの右端から信頼済みプロキシを除き、最初の未信頼IPをkeyにします。 未指定のときと未信頼の接続元からのX-Forwarded-Forは無視するため、クライアント自身によるIP偽装を許しません。 IPv4とIPv4-mapped IPv6は別物として照合するので、mapped アドレスを信頼する場合はIPv6のCIDRを指定します。zone付きのプロキシ設定は拒否します。

var per_ip := GD.web.rate({"limit": 60, "trusted_proxies": ["127.0.0.1", "172.18.0.0/16"]})

制限を通過した応答と429応答にはX-RateLimit-LimitとX-RateLimit-Remainingが付きます。429応答には、再試行までの秒数を示すRetry-Afterも付きます。

停止

終了待ちはapp.shutdown(context)を使います。新規受付とkeep-aliveを止め、処理中リクエストの完了を待ちます。 期限を越えた場合はErr.TIMED_OUTを返しますが、処理中リクエストは強制終了しません。 直ちに全接続を閉じる必要がある場合にapp.stop()を使います。

func close(app: GDWebApp):
	var context := GD.async.context().with_timeout(10.0)
	var _stopped, stop_err := app.shutdown(context)
	if stop_err:
		app.stop()

ハンドラーではreq.contextからリクエストの完了と切断を受け取れます。 with_cancel()とwith_timeout()は親を変更せず子のコンテキストを返し、親の打ち切りは子へ伝わります。 HTTP、データベース、プロセスなどの二値の待ちを打ち切れるようにするには、コンテキストを先頭に渡してwith_context_pair()で包みます。一値の処理にはwith_context()を使います。 処理が先に終わればその結果を返し、コンテキストが先に終われば処理を取り消します。

func load(req: GDWebRequest, db: GDDatabaseClient) -> Variant, Err:
	return await GD.async.with_context_pair(req.context, db.query_async("SELECT * FROM posts"))
Webの運用と高度な機能

上限と大きなアップロード

大きな本文や長いハンドラーを扱うときは、待ち受け前にlimits()で上限を明示します。

func main():
	var limited_app := GD.web.app()
	limited_app.limits({"header_bytes": 1048576, "header_values": 500, "header_timeout": 15.0, "body_timeout": 10.0, "job_timeout": 30.0, "jobs": 128})
	return 0

1 GBのZIPを受ける場合は要求ごとの上限を置き、書き込み可能なマウントへ逐次保存します。

func main():
	var app := GD.web.app()
	app.limits({"body_timeout": 600.0})
	app.route("POST", "/upload", func(req: GDWebRequest) -> GDWebResponse, Err:
		req.limit(1000 * 1000 * 1000)?
		req.save("uploads://package.zip")?
		return GD.web.text("saved")
	)
	var _server, listen_err := app.listen(8080, "127.0.0.1")
	return 0 if listen_err == null else 1
gd --strict --allow-net=127.0.0.1:8080 --mount=uploads=/srv/uploads:rw serve main.gd

本文の読み方で、使うメモリが変わります。

読み方メモリの使い方
read()、save()少しずつ読む。save()は全体をメモリへ置かない
bytes()、text()、json()残りの本文全体をメモリへ読む。一度読んだ本文は保持するので、何度呼んでも同じ内容を返す。大きな本文にはsave()を使う
req.limit(bytes)その要求の本文の上限。超えると、読んだ操作が失敗する
  • 本文の大きさに既定の上限はありません。外へ公開するサーバーではreq.limit()を置きます。
  • リクエストヘッダーは既定で1 MiBまでです。limits()のheader_bytesで変えられます。
  • 遅い接続が待たせるのはその接続だけです。

本文を少しずつ送信する

GD.web.stream(producer, length=-1, type="application/octet-stream", status=200)は、producer(writer)がGDWebWriterへ書いた分だけ送ります。 全体をメモリに結合しません。本文を生成する関数の中でawaitでき、voidまたは二値を返して終わります。

GDWebWriter動作
write(data, offset=0, count=-1)バイト列の範囲を送り、受け付けたバイト数を返す。送信が詰まっていれば進むまで待つ
write_text(text, offset=0, count=-1)文字列の範囲をUTF-8で送る。offsetとcountの単位は文字、結果の単位はバイト
flush()それまでのwriteの送信完了を待つ。切断はここのエラーとreq.contextのキャンセルでわかる
  • ストリームは一回限りです。応答ごとに新しく作ります。受信本文はストリームを返す前に読み終えてください。
  • lengthは送るバイト数です。宣言と実際が合わないと接続を閉じます。不明長(-1)はHTTP/2でDATA フレーム、HTTP/1.1でchunked、HTTP/1.0で接続終了が終端になります。
  • HEADと本文を持てないステータスコードでは本文を生成する関数を呼びません。
  • 長く待つ本文を生成する関数ではreq.contextのキャンセルを確認してください。
  • 1回のwriteが1つのデータ片に対応するとは限りません。空の文字列や空のバイト列は終端になりません。

HTTPSとHTTP/2

HTTPSはapp.listen_tls(8443, "cert://chain.pem", "cert://key.pem", "127.0.0.1")で開始し、第二結果のErrを確認します。 証明書のディレクトリは--mount cert=/path/to/certs:rで読み取り専用にします。PEM形式の証明書チェーンと暗号化されていない秘密鍵を渡します。 鍵の検証に失敗したときはポートを開きません。

TLS 1.2と1.3に対応し、ALPNでHTTP/2とHTTP/1.1を選びます。HTTP/2の各ストリームは独立に進み、一つのキャンセルは他のストリームを閉じません。 header_timeoutは完了していないTLSの初期通信にも適用されます。クライアント証明書の要求は「TCPとUDP」のTLSの表を参照してください。

gzip圧縮

GD.data.gzip_writer(writer, level=-1)は、書いたバイト列をgzipにして出力先へ渡すGDGzipWriterを作ります。 出力先にはGDFileStream、TCP接続、GDWebWriterを使えます。全体をメモリに貯めません。

項目内容
メソッドwrite(bytes)、flush()、close()、reset(writer)。どれも値とErrを返す
level-2(Huffmanのみ)、-1(既定)、0..9
close()gzipの末尾を完成する。出力先は閉じない
reset(writer)エラーを消し、同じlevelで使い回す
headername、comment(NULを含まないLatin-1)、extra(65535 バイトまで)、mod_time(0〜4294967295のUnix秒)、os(既定255)。最初の書き込みより前に設定する

HTTPで返すときはGD.web.header(GD.web.stream(producer), "Content-Encoding", "gzip")を返し、本文を生成する関数の中で圧縮器を作って書き、close()の結果を返します。 Accept-Encodingの確認とVaryの設定は呼び出し側で行います。秘密情報と外部入力を一緒に圧縮せず、圧縮済みの本文や部分応答には使わないでください。

待ち受けアドレスとポート

IPv6のlocalhostだけで待ち受けるにはapp.listen(8080, "::1")!を指定します。strictでは--allow-net=[::1]:8080、接続先はhttp://[::1]:8080/です。 ::1と127.0.0.1は別の待ち受けで、全インターフェースを示す::とも異なります。

空きポートをOSに選ばせる場合はapp.listen(0)の直後にapp.port()を読みます。待ち受けを保持したまま番号を得るので、他のプロセスに取られません。 待受け開始後のソケット障害はapp.serve_error()で確認できます。一時的な資源不足では短く待って再試行し、継続できない障害では待受けを閉じます。 strictでは選ばれるポートを事前に限定できないため、--allow-net=127.0.0.1のようにホスト全体を許可します。 GD.net.free_port()とis_free()は診断用の瞬間的な確認で、その番号を確保する機能ではありません。

HTTP クライアントの接続

  • HTTPSではHTTP/2を使い、同じ宛先への並行要求は一本の接続を共有します。非対応の相手と平文HTTPにはHTTP/1.1を使います。
  • HTTP/1.1の接続は、本文を末尾まで読むと同じ宛先へ再利用します。空き接続は全体100本、宛先ごと2本、90秒まで保持します。
  • 再利用した直後に閉じられた場合、安全に再送できるメソッドだけ1度開き直します。
  • HTTP/2では、相手が未処理と明示した要求だけを最大7回、間隔を延ばしながら再送します。要求の期限とキャンセルは守ります。

Webの設定一覧

GD.http.fetch()とGD.webの各関数に辞書で渡す設定と、その既定値です。時間は秒、大きさはバイトです。

入口設定と既定意味
GD.http.fetchmethod="GET", headers={}, body=nullHTTP メソッド、送信ヘッダー、送信本文
同上timeout=0.0, max_body=0要求全体の秒と応答本文のバイト。0は上限なし。新規TCP接続は30秒、TLS初期通信は10秒が既定
同上save="", sha256=""2xx 本文をsaveへ逐次保存し、返却本文は空。sha256はsave必須の64桁16進数で、一致した完了ファイルだけを置く
同上authority="host:port"CONNECTだけのリクエストの送信先
GDWebApp.limitsjobs=0, job_timeout=0.0保持する非同期ハンドラー数と秒。0は無制限
同上header_timeout=0.0, body_timeout=0.0リクエストヘッダー/bodyを受け終える秒。0は無期限
同上header_bytes=1048576, header_values=2147483647リクエスト lineを含むヘッダー バイトと、ヘッダー行数
GD.web.jwt_signttl=900iat/expを補う秒。0は自動付与しない
GD.web.jwt / jwt_verifyleeway=0.0, require_exp=true時刻許容秒とexp必須化
同上iss="", aud="", keep="jwt"空でない場合のissuer/audience一致と保持名
同上check=Callable()署名検証後にクレームを受け取る失効判定。指定時は真だけを許可
GD.web.sessionstotal=1024, per_user=3プロセス内の全セッション数と同一ユーザー数
同上idle=1800, life=43200操作がない場合の有効期間と、セッション全体の有効期間(秒)
同上cookie="sid", keep="user"Cookie名とリクエスト内の保持名。Cookie名はASCIIのトークン文字
GD.web.ratelimit=60, window=60.0keyごとの最大連続回数と、その回数分を補充する時間(秒)
同上expires=180.0最後の要求からkeyを解放するまでの秒数
同上keys=0, key=Callable()プロセス内で保持するkey数とkey選択関数。0は無制限。明示した保持枠が満杯なら期限が最も早いkeyを追い出す
同上trusted_proxies=PackedStringArray()転送元IPを信頼するプロキシのIPまたはCIDR
GD.web.csrfallow_missing=false状態変更でFetch Metadataが無いクライアントを許すか
GD.web.text_rulemin=0, max=4096テキストの文字数
GD.web.int_rulemin=-9223372036854775808, max=922337203685477580764ビット整数の範囲
GD.web.number_rulemin=-1e308, max=1e308有限浮動小数の範囲
GD.web.list_rulemin=0, max=1024要素数
GD.web.object_ruleextra=false未定義フィールドを残すか

GDWebApp.limitsは表にある6つの設定名だけを受け、綴り違いやbody_limitを誤りとして拒否します。

範囲外の値は設定時に失敗します。受け付ける範囲は、APIリファレンスの各関数の説明にあります。

データベース

GD.database.client()が返すクライアントは、SQLiteとPostgreSQLを同じ書き方で扱います。 ローカル開発は組み込みSQLite、本番はPostgreSQLという切り替えは、open()に渡すdriverで行います。

func main() -> int, Err:
	var local := GD.cli.env("DB_DRIVER", "sqlite") == "sqlite"
	var db := GD.database.client()
	db.open({
		"driver": "sqlite" if local else "postgres",
		"path": "user://app.sqlite3",
		"host": "127.0.0.1",
		"database": "app",
		"user": "app",
		"password": GD.cli.env("PGPASSWORD", ""),
	})?
	db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")?
	db.query("INSERT INTO users (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", [1, "ada"])?
	var out := db.query("SELECT id, name FROM users WHERE id=$1", [1])?
	print(out.rows[0].name)
	db.close()
	return 0

表の作成もINSERTもSELECTもquery()一つで送ります。受け取るのはcolumns、rows、tagを持つ辞書で、 rowsは列名を鍵にした辞書の配列です。上の例ならout.rows[0].nameがadaになります。 SQLに入れる値は、$1、$2に対応する順番で渡します。両ドライバーで同じ書き方です。SQLは変換しないため、両方で通るSQLを使います。

メソッド用途
query(sql, args)結果を全部集めて返す
query_row(sql, args)先頭1行だけ返す。行が無ければErr.NOT_FOUND
query_rows(sql, args)GDDatabaseRowsを開き、1行ずつ読む。大量の結果向き
stats()接続数、使用中、空き、待ち回数、待ち時間、接続を閉じた理由別の累積数

query_rows()はwhile rows.next()で進め、scan()で列名付きの辞書、values()で列順の配列を得ます。 next()がfalseになったらerr()を調べます。途中で止める場合はclose()を呼びます。

func list_users(db: GDDatabaseClient) -> Variant, Err:
	var rows := db.query_rows("SELECT id, name FROM users ORDER BY id")?
	while rows.next():
		var user := rows.scan()?
		print(user.id, " ", user.name)
	if rows.err() != null:
		return null, rows.err()
	return null

制約違反では第二結果のe.infoにプログラムでの判定用の情報が入ります。violationはduplicate、not_null、foreign_keyのいずれか、 columnsは関係する列名です。PostgreSQLではcode、table、constraintもサーバーが返した場合に入ります。 値そのものはinfoへ残しません。SQLite自身が報告した失敗ではsource="sqlite"と拡張source_codeを保ちます。 SQLiteのforeign keyエラーメッセージには列名が無いため、その場合のcolumnsは空です。

func save(db: GDDatabaseClient) -> void:
	var _saved, e := db.query(
		"INSERT INTO users(id,name) VALUES($1,$2)",
		[1, "ada"])
	if e and e.info.get("violation") == "duplicate":
		var columns := e.info.get("columns", PackedStringArray())
		print("重複した列: ", columns)

トランザクションとマイグレーション

複数の更新をまとめて確定または取り消したいときはtransaction()を使います。渡した関数には、専用の接続を使う GDDatabaseTxが渡ります。コールバックの第二結果がnullならコミットし、Errならロールバックします。

func save(db: GDDatabaseClient, id: int, title: String) -> Variant, Err:
	return db.transaction(func(tx: GDDatabaseTx) -> int, Err:
		tx.query("INSERT INTO posts(id,title) VALUES($1,$2)", [id, title])?
		tx.query("UPDATE counters SET value=value+1 WHERE name='posts'")?
		return id
	)
  • コールバックの中では、渡されたtxだけでSQLを実行します。元のdb.query()はこのトランザクションに入りません。
  • コミットの失敗はそのまま失敗として返ります。
  • close()やキャンセルはCOMMITの開始前ならロールバックし、開始後なら結果が確定してから接続を閉じます。
  • コールバックが終わった後は、保存しておいたtxも新しいSQLを受け付けません。

PostgreSQLで、同時に走る別のトランザクションとぶつかって失敗する場合(SQLSTATE 40001)は、serialize()でやり直せます。

  • 渡す関数はtransaction()と同じ形で、やり直すたびに新しいトランザクションで呼ばれます。
  • やり直しは最大10回です。別のエラーやキャンセルではそこで止まります。
  • メール送信のように取り消せない処理は、関数の外で行ってください。
func increment(db: GDDatabaseClient, id: int) -> int, Err:
	var saved, e := db.serialize(func(tx: GDDatabaseTx) -> int, Err:
		tx.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")?
		tx.query("UPDATE counters SET value=value+1 WHERE id=$1", [id])?
		return id
	)
	return saved, e

テーブル構成を順番に適用するときは、SQLをセミコロンで分割せず、SQL文の配列をmigrate()へ渡します。 途中の一文が失敗すると全体をロールバックし、成功時は適用した文の数を返します。 バージョンとチェックサムはアプリケーション側で管理します。

func migrate(db):
	return db.migrate([
		"CREATE TABLE posts(id INTEGER PRIMARY KEY, title TEXT NOT NULL)",
		"CREATE INDEX posts_title ON posts(title)",
	])
データベースの高度な機能

ドライバーの違い

項目SQLitePostgreSQL
向く用途ローカル開発、単一プロセス本番、異常終了耐性、複数ワーカー
接続クライアントごとに一つ。変更履歴と一時表はメモリに置く必要な接続だけ作るプール。pool=25のように最大数を指定できる
追加の入口短い処理をその場で行うGD.database.sqlite.open()まとめ送り、配列、JSONBを使うGD.database.postgres
注意永続DBはrollback journalで未完了の書込みを回復する。既存の-wal、-shmは通常のSQLiteでチェックポイントしてから開くループバック以外のホストではTLS証明書とホスト名を既定で検証。ループバックはTLSなしが既定

GD.database.postgres.client()とGD.database.redis.client()のopen()はopen(host, port, opts)の形で、接続先を引数に取ります。

SQLiteの並行

同じクライアントのquery()は受付順に実行します。別のクライアントは並行に進みますが、同じデータベースファイルへの書き込みはSQLiteのロックに従います。 GD.database.sqlite.open()が返すGDSQLiteDBとGDSQLiteStatementは、呼び出し元でそのまま実行する同期APIです。 短い処理だけに使い、同時利用はしないでください。並行処理にはGDDatabaseClientを使います。

PostgreSQLの接続と型

接続はプールが必要な分だけ作り、使い終わると戻します。ふだんは接続を意識せずquery()を呼ぶだけです。空きが無いときは順番に待ちます。

やりたいこと方法
複数のSQLを1つのまとまりで実行するBEGINを自分で送らずtransaction()を使う
複数のSQLをまとめて送るquery_many、fetch_many、exec_many
重複登録を見分けるErr.ALREADY_EXISTS。細かい原因はe.info.codeのSQLSTATEで調べる
接続が足りているか調べるstats()のwait_count(接続待ちの回数)
認証方式を固定するauth="scram"。auth="md5"は古いサーバー用

列の値は次の型で届きます。

列の型受け取る値
real、double precisionfloat
numeric桁を失わないよう文字列
json、jsonb辞書や配列。整数はintのまま
int[]、text[]などの配列同じ要素型のArray。nullと入れ子も保つ

キャンセルや期限切れになった問い合わせは接続ごと閉じます。サーバー側のSQLがすぐ止まるとは限りません。文字コードはUTF-8です。

Redisの接続

RedisはGD.database.redis.client()で使います。コマンド名と引数を分けてquery()へ渡します。

func main() -> int, Err:
	var redis := GD.database.redis.client()
	redis.open("127.0.0.1", 6379)?
	redis.query("SET", ["greeting", "hello"])?
	print(redis.query("GET", ["greeting"])?)
	redis.close()
	return 0
やりたいこと方法
値が無いことを見分けるGETはErr.NOT_FOUNDを返す
複数のコマンドをまとめて送るpipeline(cmds)。結果は送った順のArray
多くの要求から同時に使うGD.database.redis.pool()。接続は最初のquery()で作る
MULTI、WATCH、SELECT、購読を使うプールではなく専用のGDRedisClientを使う
期限を決めるopen()のtimeout(秒)

TLSの選び方はPostgreSQLと同じです。

データベースの設定一覧

open()に辞書で渡す設定と、その既定値です。

入口設定と既定意味
GDDatabaseClient.opendriver="postgres", path=""ドライバーとSQLiteのパス。user://、--mountで書き込みを許可した名前、:memory:のどれか。--strictでなければres://も使える
同上host="127.0.0.1", port=5432PostgreSQLの接続先
同上pool=0PostgreSQL最大接続数。0は上限なし、SQLiteでは使わない
同上max_rows=0, max_bytes=0query()が集める1結果の行数とバイト。0は無制限。query_rows()には適用しない
GDPostgresClient.openuser="postgres", database="postgres", password=""認証とDB名
同上connect_timeout=0.0, timeout=0接続と問い合わせの秒。プールの接続待ちも問い合わせ時間に含む。0は無期限。必要なら各期限を設定する
同上auth="any", allow_cleartext_password=falseauth="scram"/"md5"で方式固定。平文パスワード応答は明示時のみ
同上tls=<hostで決定>, ca=""外部ホストはverify-full、ループバックはdisable。CA ファイルは明示時だけ
GD.database.sqlite.openbusy_ms=0, max_ms=0, foreign_keys=falseロック待ちと実行期限のミリ秒。busy_ms=0は競合を即時通知し、max_ms=0は実行期限なし。外部キー検査は明示して有効にする
同上max_rows=0, max_bytes=01結果の行数とバイト。0は無制限
GDRedisClient.openpassword="", dial_timeout=5, read_timeout=5, write_timeout=5パスワードと接続・読取り・書込み期限の秒。各期限の明示0は無期限。timeoutを指定すると三つをまとめて設定でき、個別指定が優先される
同上tls=<hostで決定>, ca=""PostgreSQLと同じTLS選択
GD.database.postgres.poolsize既定0、0または1..21474836470は上限なし。接続は必要になった分だけ作る
GDPostgresPool.openmax_idle=2仕事を終えた後に保持する接続数。0は保持せず、最大接続数を超えない
GD.database.redis.poolsize既定0、0..2147483647最大接続数。0はCPU数の10倍。同時に作る接続は最大接続数まで
GDRedisPool.openpool_timeout=read_timeout+1.0(読取り期限が0なら30秒)、conn_max_idle_time=1800接続の空きを待つ期限と、返却後に再利用できる期間。各設定の明示0は無期限。期限を過ぎたidle接続は次の貸出時に閉じる

長いRedis問い合わせが必要な場合は、read_timeoutを明示して期限を延ばせます。

max_rowsまたはmax_bytesを越えたquery()は、その問い合わせだけを失敗にします。 期限切れや壊れた応答で順序を失った場合は接続全体を閉じます。

範囲外の値は設定時に失敗します。受け付ける範囲は、APIリファレンスの各関数の説明にあります。

定期処理

決まった時刻に一度だけ動かす仕事は、普通のスクリプトとして書き、OSのcronやsystemd タイマーから呼びます。 gd側に常駐の仕組みは要りません。

func collect() -> int, Err:
	var now := GD.time.to_iso(GD.time.now())
	GD.file.append_text("store://log.txt", now + "\n")?
	return 0

func main() -> int, Err:
	collect()?
	return 0
gd --strict --mount store=/var/lib/app:rw collect.gd

自分で間隔を持って回り続ける仕事は、GD.async.spawn()へ渡してgd serveで常駐させます。 spawn()へ渡した処理はmain()が返った後も動き続けます。

func every(sec, fn):
	while true:
		await GD.async.sleep(sec)
		fn.call()

func collect():
	print(GD.time.to_iso(GD.time.now()))

func main():
	var _job := GD.async.spawn(every.bind(60.0, collect))
	return 0
gd serve schedule.gd

止めるときはプロセスを終わらせます。Webサーバーと同じ常駐なので、ここでもserveが必要です。

公式拡張モジュール

本体を小さく保ち、外部サービス固有の機能は必要なプロジェクトだけへGDScript パッケージまたはGDExtensionとして加えます。

入口用途導入
DiscordDiscordのGatewayとRESTを使う、GDScriptだけで書かれたテキストBotgd add @gd/discord
GDSupabaseDatabaseとAuthのクライアントgd add ext:@gd/supabase

公開中のパッケージはパッケージ一覧で探せます。任意で導入するため、本体から生成するAPIリファレンスには含まれません。

  • gd addで入れた拡張は起動時に信頼して読み込むため、読み込み許可のオプションは要りません。--strictでは接続先の--allow-netが必要です。
  • --allow-extと--deny-extが効くのは、スクリプトが実行中にGDExtensionManager.load_extension()で読む場合です。
  • 入れた拡張はプロセスと同じ権限で動くので、信頼する版をgd.lockで固定してコミットしてください。

パッケージと配布

他の人が公開したパッケージを使うときは、gd initでgd.jsonを作ってから追加します。公開中のパッケージはパッケージ一覧かgd searchで探せます。

gd init
gd add hello
やりたいことコマンド
探すgd search discord
追加するgd add hello(gd install helloも同じ)
スコープや版の範囲を指定するgd add @gd/hello@^0.8.0
呼び名を決めて追加するgd add greet @gd/hello
ネイティブ拡張を追加するgd add ext:@gd/supabase
URLや手元のディレクトリから追加するgd add util https://example.com/util.gd、gd add ../mylib
別の環境で同じ版を復元するgd install --frozen
新しい版を調べる、上げるgd outdated、gd update
外すgd uninstall hello
入れたものを一覧するgd info

依存はgd.json(何を使うか)とgd.lock(どの版を使うか)に記録されます。両方をコミットしてください。引数なしのgd installはgd.jsonの依存を復元します。--frozen・--cached-only・--syncはこの復元で使います。

パッケージを使う

入れたパッケージは、スクリプトの先頭で@import 呼び名と書いて読み込みます。

@import hello
  • パッケージの実体は利用者ごとの共有キャッシュ(pkg://<呼び名>/)に置かれ、プロジェクトへは複製しません。
  • gd.jsonに書いた依存がキャッシュに無ければ、最初の実行で取得します。--strictでは登録所への--allow-netが要ります。
  • gd add helloのような短い名前は登録所で探します。同じ名前が2つ以上あるときは、どれにするか尋ねます。
  • gd addの既定の呼び名は、パッケージ名の-と.を_にした識別子です。エンジンクラスやキーワードと同じ呼び名は断ります。
  • コミットするのはgd.jsonとgd.lockです。gd initはpkg/を.gitignoreへ書きます。
  • --frozenはロックを変更しません。オフラインの配布先では、ネットワークのある環境で先に取得し、--cached-onlyを併用します。
  • install、add、updateが途中で失敗したときは、プロジェクトの配置とロックを元へ戻します。
  • ロックは登録所に結び付いています。別の登録所へ切り替えるには明示的なロック移行が必要です。

コマンドとして導入する

gd install -gは、パッケージやスクリプトをmy-toolのようなコマンドとして導入します。作業中のプロジェクトのgd.jsonとgd.lockは変更しません。

gd install -g tool                      # Install a published package by its short name.
gd install -g @scope/tool@1.0.0         # Choose the scope and version.
gd install -g --name my-tool ./tool.gd  # Install a local script.
gd uninstall -g my-tool
指定意味
-n / --nameコマンド名。省略するとパッケージ名かスクリプト名(main.gdやmod.gdなら親ディレクトリ名)
--root <dir>導入先。省略するとGD_INSTALL_ROOT、それも無ければ既定のキャッシュ。その中のbin/をPATHへ追加する
-f / --force導入済みのコマンドを更新する
-- 引数起動のたびに先頭へ渡す固定引数
  • toolのような短い名前は登録所で探します。同じ名前のパッケージが2つ以上あるときは、候補を並べてどれにするか尋ねます。@scope/toolと書けば尋ねません。
  • 入口はmain(args)を持つスクリプトです。公開パッケージはmod.gd、ローカルのディレクトリはgd.jsonのmainを使います。
  • 導入時に付けた--allow-*と--mountは、起動のたびに同じ設定で使われます。
  • 更新に失敗したときは、導入済みのコマンドをそのまま残します。
  • --rootを付けて導入したコマンドは、同じ--rootを付けて削除します。

importの短い書き方

@importはconst 名 = preload(...)の短い書き方です。

外部依存がなくても使えます。実際の登録所の依存とロックファイルを含むsamples/packagesを用意しています。

@import greet
@import "./util"
@import greet/style as theme
  • 引用符の無い名前は、gd.jsonのimportsに宣言した呼び名だけを解決します。同名のファイルを探しに行きません。
  • 相対ファイルは引用符で./または../から書きます。 .gdは省略できます。同名のファイルとディレクトリが両方あるときは"./util.gd"のように指定します。
  • 識別子はasが無ければ最後の要素そのままで、mod.gdを持つディレクトリはディレクトリ名です。
  • gd fmtは@importをそのまま残します。
  • 本家Godotは@importを知らないので、Godotと共有するファイルではconstとpreloadを書いてください。

パッケージを作る

パッケージはgd.jsonを根に持つ一つのプロジェクトです。gd init @scope/nameがmod.gdとテストのテンプレートを作り、 gd testで回し、gd publishで公開します。

{"name":"@scope/hello","version":"1.0.0","main":"src/mod.gd","include":["src"]}

パッケージの本体は、作者のGitHub Releaseから配ります。登録所が持つのは、ファイルの場所と指紋(SHA-256)だけです。

gd publish                         # Write the release files to tmp/release/scope-hello-1.0.0/.
gh release create 1.0.0 tmp/release/scope-hello-1.0.0/*
gd publish https://github.com/OWNER/REPO/releases/download/1.0.0
gd add hello gd:@scope/hello@^1.0.0

1. 引数なしのgd publishは、公開するファイルをtmp/release/<scope>-<name>-<版>/へ書き出します。ファイル名は中身のSHA-256です。 2. それらをGitHub Releaseのアセットとして上げます。同じReleaseに複数のパッケージや版のファイルを置いても、名前は衝突しません。 3. ReleaseのダウンロードURLを付けてgd publishを実行します。gdはURLから各ファイルを取得し、手元と一致することを確かめてから登録所へ登録します。

公式の登録所へ投稿したパッケージは、審査で承認されると検索・インストールできます。gd publishが審査番号を表示した場合は、承認されるまで公開されません。承認の直前にも、登録所がReleaseのファイルを照合します。

  • 利用者のgdは、ファイルをGitHubから直接取得し、登録所の指紋と照合します。Releaseのファイルを差し替えると、照合に失敗してインストールできなくなります。
  • 入口はmod.gdです。複数ファイルならincludeへファイルまたはディレクトリを明示します。
  • mainのディレクトリがパッケージの根になるので、パッケージ内の相対preloadはそのまま動きます。
  • パッケージは自分のgd.jsonのimportsで他の登録所パッケージを使えます。gd publishがそのimportsを登録所へ載せます。
  • class_nameは公開できます。installは同名クラスの衝突を検査し、衝突すれば全体を元へ戻します。
  • gd.jsonのgodotをtrueにすると、gd固有のAPIを使わず本家Godotでも動くという作者の宣言になり、gd searchが[godot]と示します。

開発中のパッケージはgd add ../pathでローカルから足します。呼び名は先のgd.jsonのnameから取ります。 チェックアウトをpkg/<呼び名>/へ複製し、内容を比較するハッシュ値が変われば次の実行で複製し直します。 .で始まるファイル、pkg/、tmp/、gd.jsonを持つ下位ディレクトリ、tokenは複製しません。 gd publishは、ローカル importの先にnameとversionのあるgd.jsonがあれば登録所の範囲に変換し、無ければ拒みます。

ローカル開発チャンネル

リポジトリで、実際の登録所をループバックで起動できます。登録所の情報はtmp/dev-channel/dataへ保存されます。

export GD_TOKEN='開発用のトークン'
uv run --no-project python -B devtools/channel.py serve --scope dev --port 8787

別のターミナルでGD_REGISTRY=http://127.0.0.1:8787と同じGD_TOKENを設定し、@dev/nameのパッケージからgd publish --dry-run、gd publishを実行します。書き出したファイルは、python3 -m http.server 8788 --bind 127.0.0.1 --directory tmp/releaseなどでループバックから配り、gd publish http://127.0.0.1:8788/dev-name-1.0.0で登録します。開発用の登録所に限り、ループバックのHTTPを受け付けます。利用側もGD_REGISTRYを設定すれば、gd search、gd add、gd install、gd install -g、gd compileがその登録所を使います。プロジェクトのgd.jsonにregistryがある場合は、そのURLが優先します。

依存の解決

gd installは依存グラフ全体を解決します。版は、gd.lockが固定した版、今回すでに選んだ版のうち範囲を満たすもの、 登録所の最新一致の順で選びます。

gd.lockは解決したimportsの設定も保持します。設定が変わった実行では同じ依存関係の解決処理で再解決し、要求外の古い版を使いません。 --frozenは設定の不一致を拒否します。同じパッケージに複数の別名がある場合、辞書順で最初の別名を配置先に使います。

  • GDScriptだけで書かれたパッケージは、版ごとに別のものとして共存できます。
  • ネイティブ拡張はプロセスに一つしか読めないため、一つの版に揃えます。範囲が両立しなければ取得前に止まります。
  • 複数のプラグインで同じ依存パッケージを共有するためのpeer依存には対応していません。
  • 登録所パッケージの正式なパスはpkg://@scope/name@版/です。pkg://<呼び名>/は、書いたスクリプトが属するパッケージのimportsで正式パスへ展開されます。同じ呼び名でもパッケージごとに違う版を指せ、同じ版はどこから辿っても一つのスクリプトです。
  • gd.lockには各パッケージのimportsの解決先も記録され、gd infoが一覧します。
  • gd uninstallとgd updateは、どのパッケージも使わなくなったものをgd.lockとpkg/から外します。
  • 検索の順位が変わっても、既知のパッケージのinstallとロックの検証には影響しません。

Godotと共有する置き場

本家Godotなどres://しか読めない環境と共有するときは、gd.jsonへ"place": "project"を書きます。 パッケージをpkg/<呼び名>/へ複製し、pkg://もres://pkg/もそこを指します。 他のパッケージだけが使うものはpkg/@scope/name@版/へ置きます。

  • gd install --godotは、パッケージをaddons/<呼び名>/へ複製します。add、update、uninstall、infoでも--godotを指定します。パッケージ内にaddons/があっても、その部分だけを取り出すことはありません。
  • project.godotのあるディレクトリではplaceの既定がprojectになり、.gitignoreは書きません。gdの無い同僚が開けるようpkg/をコミットします。
  • installはpreload、load、extendsに書かれたres://参照を配置先へ書き換えます。文字列、コメント、実行時に組み立てるパスは書き換えません。
  • placeはファイルの置き場を決めるだけで、gd固有のAPIや構文をGodot向けに変換する機能ではありません。共有するソースは標準構文と相対preloadで書きます。

ネイティブ拡張のパッケージ

  • ネイティブ拡張は読み込みに実ファイルが要るため、placeに関わらずpkg/<呼び名>/へ置きます。
  • スクリプトから名指せるのは、自分のパッケージがext:で取り込んだ拡張のクラスだけです。プロジェクトのスクリプトならgd.json、パッケージのスクリプトならそのパッケージのimportsが基準です。
  • 登録所の外にある拡張はプロジェクトのスクリプトだけが使えます。
  • 登録所のパッケージの拡張が、設定ファイルの[classes]に無いクラスを登録すると起動時に止まります。
  • 配布先のOSで取得するか、gd compileを配布先のOSで実行してください。

設定と環境変数

gd.jsonの設定は次の11件です。

名前gd initの生成値 / 未指定時意味
namemy-tool / 必須プロジェクト名。publishは@scope/nameが必要
version0.1.0 / 必須パッケージのバージョン
tasksrun/testの2件 / 無しgd taskから呼ぶコマンド
imports{} / {}呼び名と依存先。publishするパッケージでは登録所パッケージだけ
registry未指定 / 環境または公開登録所プロジェクト固定の登録所URL
main未指定 / mod.gdpublishするmod.gdまたは.gdextension入口
include未指定 / mainだけGDScriptだけで書かれたパッケージへ含めるmain ディレクトリ内のファイルまたはディレクトリ
place未指定 / cache(project.godotがあればproject)パッケージの置き場。projectでpkg/へ複製する
godot未指定 / falsegd固有のAPIを使わず本家Godotでも動くパッケージの宣言
description未指定 / 空登録所に出す説明
assets未指定 / 無しGodotアセットの管理用の呼び名とチャンネル:作者/名前[@版]。addons/へ配置する

gdが読む環境変数は次の通りです。スクリプトから環境を読む実行では--allow-envで名前を許可します。

環境変数用途
GD_CACHE_HOMEパッケージのキャッシュ根。未指定はWindowsのLocalAppData内gd。macOS/Linuxは絶対パスのXDG_CACHE_HOME/gd、それがなければホームディレクトリ内.gd。HOME未設定時はOSの利用者情報を使う
GD_INSTALL_ROOTgd install -gで入れるコマンドの置き場。--rootが優先
GD_USER_HOMEuser://の保存先。絶対パスを指定する。未指定ではOSの利用者データ領域(macOSは~/Library/Application Support/gd/user、Linuxは~/.local/share/gd/user、Windowsは%APPDATA%/gd/user)に、実行したスクリプトのディレクトリごとに作る
GD_REGISTRY登録所。未指定はhttps://gd.progsha.com/pkg。gd.jsonのregistryが優先
GD_RELEASESgd upgradeが読む配布元。未指定はhttps://github.com/prog-sha/gd/releases
GD_TOKENpublishのトークン。設定ファイルへ書かず、publishするプロセスだけへ渡す
LC_ALL、LANGgd docの手引きの言語
GD_WORKER--workersが作る内部印。利用者が設定する値ではない

遠隔パッケージと登録所はHTTPSを使います。ループバックの開発用登録所に限りHTTPも使えます。 取得したパッケージとネイティブライブラリは登録所索引のSHA-256と照合します。 パッケージの全ファイル合計は500 MiBまでです。

1つの実行ファイルにまとめて配布する

compileで、スクリプト、HTMLテンプレート、静的ファイル、マイグレーション、依存パッケージ、対象OSのGDExtensionを1つの実行ファイルへまとめます。配布先にキャッシュは要りません。

gd compile -o app main.gd
./app
  • gd.jsonが名指すパッケージと、それらが取り込むパッケージを全部同梱します。
  • 同梱したWebアプリも./app serve --no-scene-tree --allow-netで常駐できます。
  • ローカルパスのパッケージからは、.envなど.で始まるファイルとgd.jsonのtokenを除きます。
  • 秘密情報をソースへ埋め込まないでください。compileは.envを除外しますが、ソースに書いた値は実行ファイルに残ります。

アセットチャンネル

gd searchはパッケージに加え、Godotの公開アセットカタログとgdの審査済みカタログを検索します。独自の登録所を設定している場合は、その登録所だけを検索します。

チャンネル用途
officialGodot Asset Storeのアセット
gdgdの審査済みアセット

検索結果のasset:チャンネル:作者/名前を、そのままgd addに渡します。

gd search dialog
gd add asset:official:publisher/dialog
gd add ui asset:gd:publisher/dialog@1.2.0
gd install --frozen --cached-only
gd update ui
gd uninstall ui
  • バージョン名が重複する場合は、版の一覧にあるIDをasset:official:publisher/dialog@#123のように指定します。名前に空白を含む場合は引数全体を引用符で囲みます。
  • チャンネルを省略するとofficialになります。取得に失敗しても別のチャンネルへ切り替えません。
  • gd.jsonのassetsに依存先を記録し、gd.lockに取得元・選んだ版・SHA-256を固定します。両方をコミットしてください。
  • asset:で指定するGodotアセットは、ZIP内のaddons/以下をプロジェクトのaddons/へ配置します。assetsの呼び名は管理用です。通常のパッケージはimportsに記録し、@importで読み込みます。
  • 最初の取得では対応するエンジンのバージョンを確認し、安定版を優先します。以後のinstallはロックした版を使い、updateで再選択します。@1.2.0のように指定した版はupdateでも変わりません。
  • --frozenではロックを変更せず、--cached-onlyでは通信しません。キャッシュのない版をオフラインで取得することはできません。
  • 手作業で置いたアドオンや利用者が編集したファイルは上書きしません。処理が失敗したら、パッケージ・アドオン・設定・ロックを元へ戻します。
  • gdチャンネルはアセットの説明、配布URL、SHA-256を審査して登録します。アーカイブは作者の配布先から取得し、gdがSHA-256を照合します。Godotエディタはこの追加のハッシュ値を使わないため、同じ照合は行いません。

アセットの詳細や版の一覧を調べるには、ソース配布に含むクライアントも使えます。

gd tools/store.gd channels
gd tools/store.gd search official 4.7 dialog
gd tools/store.gd show gd publisher dialog
gd tools/store.gd releases gd publisher dialog

対応範囲と報告

gdはAPIが固まる前の公開版です。後方互換は前提にしないでください。変更した点と基準にしたGodotの版は CHANGELOGに書きます。 gdはGodot FoundationまたはGodot Engine プロジェクトの公式製品ではありません。

不具合はIssuesへ、公開すべきでない脆弱性は GitHubの非公開報告から知らせてください。

開発中の機能(参考)

ここにある機能は開発中です。使い方や仕様は予告なく変わります。参考程度にご覧ください。

エディタ(gd-godot)

gd editorでエディタを開きます。初回は画面用の実行ファイルgd-godotを自動で導入します。

やりたいことコマンド
エディタを開くgd editor
プロジェクトを指定して開くgd editor <プロジェクトディレクトリ>
プロジェクトを画面付きで実行するgd run-game <プロジェクトディレクトリ>

詳しくはgd-godot マニュアルを参照してください。

オンラインゲーム

GD.online.match()は、オンラインゲームの対戦相手を探すサーバーを作ります。部屋は自分のアドレスと人数を知らせ、 参加する側は空きのある部屋を1つ受け取ります。状態はプロセスのメモリ、または複数のプロセスで共有するキー値サーバーに置きます。 変数に@onlineを付けてサーバーとクライアントで状態を同期する仕組みも準備中です。

gd Manual

English | 日本語

What gd is for

gd is a single command for writing command-line tools, websites, Web APIs, scheduled jobs, and data processing in GDScript. It is Godot built small without a display, and it runs a single .gd file without a project.godot.

You start the way you would with a Python or Node.js script. When you need them, type checking, tests, packages, databases, a Web server, and a standalone executable are available in the same GDScript. For game screens and rendering, use upstream Godot.

Together with Godot itself, apps, frontends, servers, and CLI tools can all be written in one language, GDScript. The same script runs on macOS, Linux, and Windows, and waits on networking and databases do not stop other work. It links directly with C++ through GDExtension.

Speed matters too. gd supports HTTP/2, other work proceeds while a connection waits, and text and JSON processing is fast.

Install

Prebuilt downloads are available for macOS arm64/x86_64, Linux x86_64, and Windows x86_64. Linux arm64 can be built from source. You can also download an archive from Releases and put gd on your PATH.

macOS / Linux

curl -fsSL https://gd.progsha.com/install.sh | sh

Installs to ~/.local/bin. If the directory is missing from PATH, a y/N prompt offers to save it in your shell settings. Choose y, then open a new terminal to use it. Linux downloads require x86_64 and glibc 2.38 or newer.

Windows (PowerShell)

Invoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1

If the installation directory is missing from PATH, a y/N prompt offers to add it to your user PATH.

Homebrew (macOS)

brew tap prog-sha/gd https://github.com/prog-sha/gd
brew install prog-sha/gd/gd

apt (Linux amd64)

Use an apt-based distribution with glibc 2.38 or newer, such as Ubuntu 24.04 or Debian 13.

sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://gd.progsha.com/apt/gd.asc | sudo tee /etc/apt/keyrings/gd.asc >/dev/null
sudo chmod 0644 /etc/apt/keyrings/gd.asc
echo 'deb [arch=amd64 signed-by=/etc/apt/keyrings/gd.asc] https://gd.progsha.com/apt stable main' | sudo tee /etc/apt/sources.list.d/gd.list
sudo apt update
sudo apt install gd

Upgrading

gd upgrade            # Move to the latest release.
gd upgrade 0.8.0      # Move to a chosen version.
gd upgrade --dry-run  # Show the version without installing it.

The download is checked against the release's SHA-256 before the running gd is replaced. A gd installed through Homebrew or apt is upgraded with brew upgrade gd or apt upgrade gd instead.

Build from source

Install Python, uv, SCons, and a C/C++ compiler. Executables are written to bin/.

git clone --branch master https://github.com/prog-sha/gd.git
cd gd
scons platform=macos target=template_release -j8
# Linux ARM64: platform=linuxbsd arch=arm64
# Linux x86-64: platform=linuxbsd arch=x86_64
# Windows: platform=windows arch=x86_64 use_mingw=yes windows_subsystem=console

Quick start

Create one file, hello.gd. No config file or package is needed. main() is the entry point, and the integer it returns becomes the process exit code.

func main():
	print("Hello, world")
	return 0
gd hello.gd

To check types and syntax without running, use check.

gd check hello.gd

Import scripts and shared constants

Use @import "./settings" for a local file and @import hello for an installed package. Use the imported name directly; .gd and as settings can be omitted.

Put shared values in settings.gd:

const TITLE = "Hello"
const USER = "world"

Use them from main.gd:

@import "./settings"

func main():
	print(settings.TITLE, ", ", settings.USER, "!")
	return 0

This prints Hello, world!. Use this pattern when values need to be shared.

  • Keep values and functions used by only one script in that script.
  • Use as only when a name conflicts.
  • Built-in APIs such as GD.web need no import.

See Packages and distribution for installation and version locking.

Pick by purpose

The standard API has one entry point, GD, with a child per purpose. Scripts write these names as they are.

What you wantEntryExample
Files, text, time, HTTP client, asyncGDGD.file.read_text("a.txt")
Websites and Web APIsGD.webGD.web.app()
SQLite or PostgreSQLGD.databaseGD.database.client()
RedisGD.database.redisGD.database.redis.client()
TCP, UDP, TLSGD.netGD.net.listen_tcp("127.0.0.1", 8080)
Mail parsing and SMTP submissionGD.mailGD.mail.parse_address("me@example.com")

GD.database.postgres and GD.database.redis are advanced entries for features specific to one backend.

Looking up the API

gd --help lists the commands, and gd install --help describes one command's arguments and options.

Pass the same spelling you write in a script to gd doc. Signatures come from the executable, so they match the implementation.

gd doc                     # short guide and entry points
gd doc manual              # the full manual
gd doc GD                  # the children of GD
gd doc GD.file             # file API
gd doc GD.http.fetch       # the returned HTTP response
gd doc GD.web.app          # Web application
gd doc SceneTree           # Inspect a public engine class.
gd doc all                 # every public class

Return types such as Err and GDWebRequest are looked up by name alone. For Godot classes such as Node, SceneTree, and Timer, see the Godot class reference as well. The manual is shown in Japanese when LC_ALL or LANG starts with ja, and in English otherwise. The web version at gd.progsha.com switches between Japanese and English.

GDScript basics

The examples avoid repeating type names. Variables assigned with := infer their types from the right-hand side. Parameters without annotations remain dynamic. Add annotations only where you want to fix a type boundary.

Arguments and flags

Arguments placed after the script name arrive in main(argv). An argument that could be mistaken for gd's own flag, such as --name=gd, reaches the script when placed after --.

func main(argv):
	for arg in argv:
		print(arg)
	return 0
gd main.gd apple orange
gd main.gd -- --name=gd

To interpret them as flags, use GD.cli.flags(). It accepts --name gd, --name=gd, and -name=gd alike.

func main(argv):
	var flags := GD.cli.flags()
	flags.flag_str("name", "world", "who to greet")
	var _parsed, parse_err := flags.parse(argv)
	if parse_err:
		print(flags.usage())
		return 1
	print("Hello, " + flags.get_str("name"))
	return 0

Calling external commands

Call external tools with GD.cli.run(). Only the calling GDScript waits, so other requests proceed even when it is called from a gd serve handler. Under --strict it needs --allow-run. You can narrow the target, as in --allow-run=/usr/bin/git.

func main():
	var got, err := await GD.cli.run("git", ["rev-parse", "HEAD"])
	if err:
		return 1
	print("code=", got["code"], " out=", got["output"])
	return 0

A nonzero child exit returns an Err. Read the exit code from value.code and the output from value.output. A timeout or cancellation keeps the output captured so far.

The third argument, opts, changes the behavior.

NameDefaultMeaning
timeout0Seconds before giving up. 0 is unlimited. Past it, the child is shut down and Err.TIMED_OUT is returned
outputtrueCollect the output. With false, the child uses the parent's standard I/O directly and nothing is collected

Values and failures

A function that can fail returns two values: a value and an Err. Receive both with var value, e :=. Their types come from the function declaration; a non-null e means failure. Assign them to existing variables with value, e = call(). Variables declared without types remain Variant; declare var value: T and var e: Err when you want static checks.

func main():
	var text, e := GD.file.read_text("note.txt")
	if e:
		print(e.text())
		return 1
	print(text)
	return 0

Shorter failure handling

Append ? to a call to return its value and Err to the caller on failure. On success, use the value alone. A function using ? returns a value and Err. Without a return annotation, its first result is inferred from its return values; you can specify it as -> String, Err. On success, return value omits the null second result.

func title(path) -> String, Err:
	var text := GD.file.read_text(path)?
	return text.strip_edges()

func main():
	var text, e := title("note.txt")
	if e:
		print(e.note("read the title").text())
		return 1
	print(text)
	return 0

Return your own error

A readable file can still be invalid for your application. Create an Err when the message is empty. Err("message", kind, details) takes a description, a kind such as Err.INVALID_DATA, and optional details. Save this as read_message.gd:

# Read a message and reject empty contents.
func read_message(path: String) -> String, Err:
    var text := GD.file.read_text(path)?
    if text.strip_edges().is_empty():
        return "", Err("Message is empty", Err.INVALID_DATA, {"path": path})
    return text, null

# Print the message or report the failure to the caller.
func main() -> int:
    var text, err := read_message("message.txt")
    if err != null:
        printerr(err)
        return 1
    print(text)
    return 0
printf 'Hello!\n' > message.txt
gd read_message.gd
printf '' > message.txt
gd read_message.gd

The first run prints Hello!. After emptying the file, the second run reports Message is empty and exits with status 1.

  • -> String, Err declares two return values: a string and an error.
  • Return text, null on success and "", Err(...) on failure.
  • The caller receives them with var text, err := read_message(...) and checks err before using text.
  • If reading the file fails, ? returns that error as it is.

Waiting and concurrency

Waiting methods in HTTP, databases, GD.net, files, and others are written as ordinary function calls. Only the calling GDScript waits; other networking and timers keep running.

func main():
	var res := GD.http.fetch("https://example.com/")!
	print(res.status)
	return 0

To start several operations together, use the variants ending in _async with GD.async.all().

func main():
	var got = await GD.async.all([
		GD.http.fetch_async.bind("https://example.com/a"),
		GD.http.fetch_async.bind("https://example.com/b"),
	])
	for result: Array in got:
		var res: GDHTTPResponse = result[0]
		var e: Err = result[1]
		if e:
			print(e.text())
			return 1
		print(res.status)
	return 0
EntryPurpose
name_async()Start the operation and return a GDTask that keeps its result. await it later, even after other waits, for the same result as the regular name. cancel() stops it
GD.async.all(list)Run several operations together and return the results in the order given
GD.async.spawn(fn)Run a function in the background. It keeps running after main() returns
GD.async.sleep(sec)Wait the given number of seconds

To wait for a single one, receive it in the same shape as the regular name: var value, e := await GD.http.fetch_async(url).

Started operations can also be received one after another. If second finishes while first is awaited, second keeps its result.

func main():
	var first := GD.http.fetch_async("https://example.com/a")
	var second := GD.http.fetch_async("https://example.com/b")
	var a, a_err := await first
	var b, b_err := await second
	if a_err or b_err:
		return 1
	print(a.status, " ", b.status)
	return 0

Keep three points in mind.

  • Pass all() the GDTasks returned by _async(), or Callables made with .bind() as in the example above. Either way, a result that finishes early is not lost.
  • spawn() does not move work to another thread. Use the _async variant when a standard module processes large data.
  • Call waiting methods from main() or a function you wrote. A function passed to Array.map(), _init(), and member initializers cannot wait, so write a for loop or use GD.async.all().

Tutorial: a notes API on SQLite

With what you have read so far, this builds a small API that accepts JSON and stores it in SQLite, in one script. The result is a development server with input validation and SQL parameter binding, started with narrowed permissions.

1. Create a working directory

mkdir notes-api
cd notes-api

2. Write the API

Save the following as main.gd.

# Store notes in an embedded database and expose a JSON API.
extends RefCounted


const PORT := 18080 # development port listening on loopback
const DB_PATH := "user://notes.sqlite3" # per-user writable area provided by gd

var app := GD.web.app()
var db := GD.database.client()


# Return notes as JSON, newest first.
func list_notes(req: GDWebRequest) -> GDWebResponse, Err:
	var got, query_err := await GD.async.with_context_pair(req.context, db.query_async("SELECT id, title FROM notes ORDER BY id DESC"))
	if query_err:
		return query_err
	return GD.web.json(got.rows)


# Store a validated title and return the created row.
func add_note(req: GDWebRequest) -> GDWebResponse, Err:
	var body := req.valid("body")
	var made, query_err := await GD.async.with_context_pair(req.context, db.query_async(
		"INSERT INTO notes(title) VALUES($1) RETURNING id, title",
		[body.title]
	))
	if query_err:
		return query_err
	return GD.web.json(made.rows[0], 201)


# Prepare the database and routes, then listen on loopback.
func main() -> int, Err:
	db.open({"driver": "sqlite", "path": DB_PATH})?
	db.query("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT NOT NULL)")?
	app.route("GET", "/notes", list_notes)
	app.route("POST", "/notes", add_note, [GD.web.json_body(GD.web.object_rule({
		"title": GD.web.text_rule({"min": 1, "max": 120}),
	}))])
	app.listen(PORT, "127.0.0.1")?
	print("listening on http://127.0.0.1:%d" % PORT)
	return 0

Read it from the top.

  • app is the router and db is the database connection. Both are script variables so the server can keep running after main() returns.
  • main() first opens SQLite and creates the table. user:// in DB_PATH is a per-user writable area provided by gd.
  • app.route() registers an HTTP method, a path, and the function to call for it (the handler).
  • A handler receives a GDWebRequest and builds the reply with GD.web.json(). A ? in the middle returns the failure to the server, which becomes a status such as 500.
  • The POST route carries GD.web.json_body(). The handler is called only when the body matches the rule, and the value that passed arrives in req.valid("body").
  • SQL values are bound to $1. SQL is never built by string concatenation.

3. Start with narrowed permissions

Run unverified scripts and servers exposed to the outside with --strict, which denies permissions by default. Here the listener is limited to one loopback port. serve keeps the process alive after main() returns, and it is the command to use for servers.

gd check main.gd
gd --strict --allow-net=127.0.0.1:18080 serve main.gd

4. Use it from another terminal

curl -s -X POST http://127.0.0.1:18080/notes \
  -H 'Content-Type: application/json' \
  -d '{"title":"try gd"}'
curl -s http://127.0.0.1:18080/notes

The first call returns status 201 with the created row, the second the stored array. An empty title, a title over 120 characters, or a non-JSON body is rejected with 400. Press Ctrl-C in the terminal that started it to stop.

In production, keep this process on loopback behind a TLS reverse proxy, and switch storage that must survive crashes to PostgreSQL. Keep connection details out of the source and read them from allowed environment variables.

Permissions

Start with normal execution. --strict is an advanced mode for explicitly designing and configuring the permissions a script needs.

ModeSuited toRestrictions
Normal executionRunning trusted source during developmentNeither files nor the network are restricted
--strictUnverified scripts, public serversThe startup directory is read-only; absolute paths outside it are denied. Network, environment variables, child processes, native extensions, and system information are denied by default

Under --strict, start by listing what the script uses.

gd --strict \
  --mount store=/srv/app:rw \
  --allow-net=db.example.com:5432 \
  --allow-env=DATABASE_URL \
  main.gd
FlagGrants
--mount name=path:r / --mount name=path:rwRead or read/write on a named directory
--allow-net=host:port,...Connecting and listening. Without a value, everything
--allow-env=name,...Environment variables
--allow-run=command,...Child processes
--allow-ext=path,...Native extensions a script loads while running
--allow-sys=item,...Machine and system information
--deny-*A denial that wins over the matching allow
-AAllow everything except files. For temporary use during development

--strict applies to the commands that run a script: run, serve, test, task, eval, and repl. Commands that do not run a script, such as check, fmt, and package operations, are unaffected.

File locations

A script sees files through four kinds of location. Write the name of the location at the start of the path, or write an absolute path as it is.

SpellingLocationUnder strict
res://a.txtThe directory the script was started fromRead-only
user://a.txtWritable area gd keeps for each script in the user's data folder. It survives restartsRead/write
store://a.txtThe name given by --mount store=/srv/app:rwAs specified
/etc/hostsThat location on the machineDenied unless it is inside the startup directory

When in doubt, put files you only read under res:// and files you save under user://.

  • Under strict, name a directory outside the startup directory with --mount. -A does not widen file access.
  • Name a mount with lowercase letters, digits, and -, such as store or uploads. These names are used by gd and cannot be chosen: res, user, uid, pipe, local, libgodot, tcp, unix, http, https, file, data, cache, pkg, and global.
  • Windows does not support --mount or absolute paths. Put files under res:// or user:// there.

Network and extension permissions

  • In --allow-net, localhost:8080 also covers IPv4 loopback 127.0.0.0/8 and IPv6 ::1 on the same port.
  • *.example.com:443 allows its subdomains.
  • Native extensions run in the same process, so allow only ones you trust.

serve and SceneTree

gd serve is the resident way to run, and it creates no SceneTree. Networking, timers, await, custom Signals, GD.async.sleep(), and queue_free() on nodes outside a tree all work. With no work to do, it sleeps until the next deadline or network notification, so there is no cycle to tune.

What you wantHow
Keep a Web server or scheduled job residentgd serve main.gd
Use Node _process(), _physics_process(), process_frame, SceneTreeTimer, or high-level multiplayerNormal execution without serve
Run a script extending SceneTree or MainLoopNormal execution without serve
Check during development that no SceneTree slips ingd --no-scene-tree --allow-net serve app.gd
Listen with several processes--workers=<n> or --workers=auto. n is an integer of 1 or more

Under serve, a script that only extends Node is not added to a tree. --no-scene-tree reports a diagnostic as soon as a SceneTree is created and exits with code 1. It is inherited by --watch and --workers children.

TCP and UDP

Use GD.net for low-level networking. Godot's low-level types remain for compatibility, but new code should use GD.net.

func echo() -> int, Err:
	var listener := GD.net.listen_tcp("127.0.0.1", 8080)?
	var conn := listener.accept()?
	var data := conn.read(65536)?
	conn.write(data)?
	conn.close()
	return 0
  • GDTCPConn keeps reads and writes in separate queues, so several GDScripts may call it concurrently.
  • Deadline methods set durations from now; zero clears them.
  • After close(), waiting reads and writes end with Err.INTERRUPTED. A listener waiting to accept does the same.
  • A connection tries the IPv4 and IPv6 candidates from name resolution in order and keeps only the one that succeeds. The overall timeout is never extended.

TLS

Open TLS with GD.net.dial_tls(host, port, opts). It verifies the certificate chain and host name by default, and a failure never falls back to plaintext. The result is the same GDTCPConn used for TCP.

optsMeaning
timeoutOne deadline in seconds covering both connect and handshake
ca_fileA private CA. It takes precedence over the environment settings
cert_file, key_fileClient authentication. Provide both, as files inside permitted mounts
server_nameCheck the certificate against a name different from the dial address
next_protosAn array of ALPN names. One name is 1–255 bytes, and the whole list is up to 65535 bytes
insecure_skip_verifySkip verification. Use only for tests where verification is deliberately unnecessary

Read the negotiated result from negotiated_protocol and version in connection_state(). TLS 1.2 is 771 and TLS 1.3 is 772.

Without other settings, the trusted CAs are the OS trust settings on macOS and Windows, and the system CA bundle on Linux. Set SSL_CERT_FILE or SSL_CERT_DIR before starting the process to use the given CAs on any OS. Directory lists use : on Unix and ; on Windows.

When a server requires client certificates, pass client_ca (a trusted CA bundle) and client_auth in the opts of app.listen_tls(port, cert, key, host, opts). A missing client_ca uses the system trust settings.

client_authBehavior
noneDoes not request a certificate
requestA certificate is optional. It is not verified
requireA certificate must be presented. It is not verified
verify_if_givenVerifies a certificate only when one is presented
require_and_verifyRequires a verified certificate

UDP and name resolution

Open UDP with GD.net.listen_udp(). A received packet carries the sender's host and port, so you can reply to it directly.

func echo_udp() -> int, Err:
	var conn := GD.net.listen_udp("127.0.0.1", 9000)?
	var packet := conn.read_from()?
	conn.write_to(packet.data, packet.host, packet.port)?
	conn.close()
	return 0
  • Pass write_to() an IP address. Turn a host name into one first with GD.net.resolve(name)?.
  • One read_from() returns one packet. Bytes beyond the requested size are dropped and packet.truncated becomes true.
  • GD.net.local_addresses() lists this machine's addresses.

Mail

GD.mail parses addresses and headers and sends mail through an SMTP server.

  • Pass send_mail the whole message, headers and body, as bytes.
  • Success means the SMTP server accepted the message. It does not guarantee delivery to the recipient.
  • Under --strict, the server needs --allow-net.
func main() -> int, Err:
	var message := "From: me@example.com\r\nTo: you@example.com\r\nSubject: Hello\r\n\r\nHello\r\n".to_utf8_buffer()
	GD.mail.send_mail("smtp.example.com", 587, "me@example.com", PackedStringArray(["you@example.com"]), message, {
		"tls": "starttls", "timeout": 10.0,
		"auth": GD.mail.plain_auth("me@example.com", "secret"),
	})?
	return 0

Files and data

GD.file reads and writes files and handles paths. The directory you started from is res://, and absolute paths work as written. To write to an outside directory under strict, write the name given by --mount store=/srv/app:rw as in store://users.csv.

func main() -> int, Err:
	var rows := GD.data.csv_objects(GD.file.read_text("store://users.csv")?)?
	GD.file.write_text("store://users.json", JSON.stringify(rows))?
	return 0

File operations suspend only the calling GDScript, even under their regular names. Other requests proceed while a Web server handler reads a file. Use the variants ending in _async only to start several operations together.

func handler(_req) -> GDWebResponse:
	var body, read_err := GD.file.read_text("store://big.json")
	if read_err:
		return GD.web.text("cannot read", 500)
	return GD.web.text(body)

Files embedded by compile can be read, listed, and served statically through the same API.

Reading large files

To read without holding the whole file in memory, open a GDFileStream with GD.file.open(path, mode). Modes are read, write, append, and read_write. Call close() when done.

MethodBehavior
read(max)Returns up to max bytes. It may return fewer. An empty successful value is EOF
write(bytes)Writes all bytes and returns the count. On a failure partway, the first result retains the number already written

Operations on one stream run in arrival order, and separate streams proceed in parallel. Append always writes at the end, even after a seek. read_bytes() also retains the bytes already read in the first result when it fails partway. read_text() rejects input too large for a String instead of truncating it, so handle large files as bytes or a stream.

Files updated concurrently

When several processes update the same file, use GD.file.replace_text(path, old, body). It replaces the content only when the old you read still matches the current content, so a concurrent edit is never silently overwritten. Pass null as old to create a new file.

Entry points by data format

PurposeEntry
Reading CSV, TOML, YAML, JSONL, JSONC, XML, INI, TAR, front matter, and .env filesGD.file.read_csv(path) and similar
In-memory conversion of the same formats, JSON, codecs, hashes, HMAC, PBKDF2, HKDF, byte sequencesGD.data
UUID and ULIDGD.id
Time conversion and arithmeticGD.time
Text formatting and comparisonGD.text
HTML entities, tags, and gdhtml (a micro template with Mustache syntax)GD.html
Flags and environment variablesGD.cli
Array and dictionary operationsGD.collection
Special math values and bit operationsGD.math
Version comparisonGD.version
Logging to the terminal and filesGD.log
Test assertionsGD.test

Environment variables and .env have separate entries by what you read.

What you readEntry
Process environment variablesGD.cli.env(name, fallback) and GD.cli.require_env(name). Strict mode needs --allow-env
A .env fileGD.file.read_env(path). Reads the file into a dictionary
A dotenv stringGD.data.env(src) and GD.data.to_env(data). Convert to and from a dictionary in memory

In-memory conversions compute in place under their regular names, and their _async variants compute on another thread. Use _async for large inputs. Run gd doc GD.file and gd doc GD.data for the exact lists. Checks and limits per format are in the description of each entry in the API reference.

GD.collection operations that take a Callable yield to other work about every 1 ms. Each GD.log call waits until the write completes and never truncates the message. Check failures through the second Err result; GD.log.flush() waits for all earlier output.

JSON rules

Use GD.data.json_encode(value) to produce JSON bytes and GD.data.json_decode(bytes) to read received bytes. GDWebRequest.json(), GDHTTPResponse.json(), and each JSONL line follow the same rules.

func main() -> int, Err:
	var bytes := GD.data.json_encode({"id": 1, "tags": ["a", "b"]})?
	var value := GD.data.json_decode(bytes)?
	print(value.id)
	return 0
  • Integers come back as int. Fractions and exponents become float.
  • Ambiguous JSON, such as broken text encoding or a repeated name, fails instead of being read.
  • Pass {"deterministic": true} when the same value must always give the same bytes, as for signatures or cache keys.

Hashes and key derivation

GD.data returns SHA-1, SHA-224/256/384/512, and SHA3-224/256/384/512 digests. HMAC, PBKDF2, and HKDF accept sha1, sha224, sha256, sha384, sha512, sha3-224, sha3-256, sha3-384, or sha3-512 as the hash name. PBKDF2 and HKDF accept an output length and return an Err for an invalid hash or settings outside the supported range. PBKDF2 iteration counts of one or less perform one iteration.

Web framework

Create main.gd and index.html in the same directory. One route renders a greeting through an HTML template; another returns the same data as JSON.

main.gd:

# Serve a greeting as an HTML page and a JSON response.
var app := GD.web.app()

# Build the shared response data from the requested name.
func greeting(req: GDWebRequest) -> Dictionary, Err:
	var name := req.query.get("name", "world")
	if not name is String:
		return {}, Err("name must be text", Err.INVALID_DATA)
	return {"name": name, "message": "Hello, " + name + "!"}

# Render the page with escaped template values.
func home(req: GDWebRequest) -> GDWebResponse, Err:
	return GD.web.view("index.html", greeting(req)?)

# Return the same data as JSON.
func hello(req: GDWebRequest) -> GDWebResponse, Err:
	return GD.web.json(greeting(req)?)

# Listen locally, using an optional port argument.
func main(args):
	var port := 8080 if args.is_empty() else int(args[0])
	app.route("GET", "/", home)
	app.route("GET", "/api/hello", hello)
	app.listen(port, "127.0.0.1")!
	print("http://127.0.0.1:", app.port())
	return 0

index.html:

<!doctype html>
<!-- Display a greeting and let visitors choose the name. -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{message}}</title>
  <style>
    body { max-width: 36rem; margin: 4rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; line-height: 1.6; }
    input, button { padding: .6rem; font: inherit; max-width: 100%; box-sizing: border-box; }
  </style>
</head>
<body>
  <h1>{{message}}</h1>
  <form action="/" method="get">
    <label>Your name <input name="name" value="{{name}}"></label>
    <button type="submit">Say hello</button>
  </form>
  <p><a href="/api/hello?name={{name}}">View the JSON response</a></p>
</body>
</html>

Run from that directory:

gd serve main.gd

Open http://127.0.0.1:8080/?name=Alice to insert “Hello, Alice!” into {{message}}. /api/hello?name=Alice returns {"name":"Alice","message":"Hello, Alice!"}. Template values are escaped for their HTML context.

serve keeps listening after main() returns. Stop with Ctrl+C.

Routes and replies

route(method, pattern, handler) binds an HTTP method and a path to a handler. :name in the pattern arrives in req.params["name"]. A HEAD request is answered by the GET route. A request whose path matches but whose method does not gets a 405. A handler receives a GDWebRequest. It reads only the needed body through req.read(), bytes(), text(), json(), or save(). A body sent by an HTML form becomes a dictionary with GD.http.decode_query(req.text()?).

The value a handler returns becomes the reply. Return one of the values in the table below as it is, such as return GD.web.json(data).

When a step fails, return its Err with call()?. The Err becomes the status code in the last row of the table. Register app.on_error(handler) to decide that reply yourself.

Returned valueReply
GD.web.html(body), GD.web.view(path, data)HTML
GD.web.json(data)JSON
GD.web.text(body), GD.web.bytes(body, type)Text, or any media type
GD.web.stream(producer)A body written a little at a time. See "Web operations and advanced features"
GD.web.redirect(to)302. to is limited to a path on the same site. Set away to true to send elsewhere
GD.web.not_found()404
A string200 as text/plain
A dictionary with bodyA handwritten reply. status, type, and headers are optional
A dictionary without body200 as JSON
null204
An ErrStatus by kind. INVALID_DATA → 400, UNAUTHENTICATED → 401, PERMISSION_DENIED → 403, NOT_FOUND → 404, LIMITED → 429, UNSUPPORTED → 501, TIMED_OUT → 504; other kinds → 500 (all are Err constants)

A reply can be adjusted as follows.

  • Change the status code with the second argument, as in GD.web.text("Not found", 404). bytes takes it after the media type.
  • GD.web.header(reply, name, value) adds a header to a reply.
  • GD.web.guard(reply) adds defensive headers such as Content-Security-Policy at once.
  • The reason for a failure is not written to the body by default. Show it during development with app.show_errors(true).
  • A value in req.query is not always text. Check it with is String before use, as in the example above.
  • req.path is the path with escapes such as %20 turned back into characters. req.target holds the text as it arrived.

The router also accepts the following.

RegistrationPurpose
app.static("/assets", "res://public")Answer GET and HEAD under the prefix with files from the directory. The media type comes from the extension, and nothing outside the directory is served. Write the index of / as a route
app.group("/api", [middleware])A route group with a shared prefix and middleware. The result has route() and use()
app.fallback(handler)Requests matching no route. Return the 404 page here
app.on_error(handler)The reply when a handler returns a failure
app.after(handler)Reshape the reply before sending. Receives func(req, reply) and returns it with headers added

Middleware

Middleware is a function called before the handler. It receives a GDWebRequest, returns null to continue, or returns a reply to stop there. An object with handle(req) also works. Pass values to later stages with req.keep(name, value) and read them with req.kept(name).

RegistrationScope
app.pre(mw)Before route selection. Every request
app.use(mw)After route selection. Every route. Can read req.params
group.use(mw)Routes in that group
app.route(method, pattern, handler, [mw])That route only

Input validation is middleware too. GD.web.json_body(rule), GD.web.query(rule), and GD.web.params(rule) check the body, query, and path values, and put the values that pass into req.valid("body"), req.valid("query"), and req.valid("params"). Rules are built from GD.web.text_rule(), int_rule(), number_rule(), bool_rule(), list_rule(), and object_rule(), with GD.web.optional() and GD.web.one_of() for omission and choices. Query and path values are strings, so check them with text_rule() and convert with to_int() when needed.

var app := GD.web.app()

func show(req) -> GDWebResponse, Err:
	var params := req.valid("params")
	return GD.web.json({"id": params.id})

func main():
	app.route("GET", "/posts/:id", show, [GD.web.params(GD.web.object_rule({"id": GD.web.text_rule({"min": 1, "max": 20})}))])
	app.listen(8080)!
	return 0

The built-in middleware are GD.web.sessions(), GD.web.csrf(), GD.web.jwt(), and GD.web.rate(). The authentication section uses them.

HTML templates

As pages grow, move the HTML into template files and render them with GD.web.view(path, data). The template language is gdhtml, a micro template with Mustache syntax. It handles {{name}}, {{{html}}}, #if, #unless, #each, #with, else, and {{> header}}. Using {{> header}} from views/page.html reads views/partials/header.html at the same level.

<!-- views/page.html -->
{{> header}}
<main><h1>{{title}}</h1></main>
<!-- views/partials/header.html -->
<header><a href="/">gd app</a></header>
func page(_req) -> GDWebResponse, Err:
	return GD.web.view("views/page.html", {"title": "Top"})

Double-brace values are escaped by the context they appear in. The template author is trusted, the values inserted are not.

ContextHandling
HTML body, quoted and unquoted attributes, attribute namesHTML escape
href="{{url}}"Relative URLs and http, https, mailto pass. data-href is treated the same
href="/work/{{path}}", href="/?q={{query}}"Paths are normalized keeping separators, query values are percent-escaped
onclick, script bodyEncoded as JSON in a form where </script> cannot break the structure, even for application/json
styleSafe single CSS values and CSS strings and URLs pass
Dangerous URLs, srcset, CSS values, attribute namesReplaced with #ZgdunsafeZ or ZgdunsafeZ without failing the whole page
  • Triple braces {{{html}}} are the only unescaped entry, and they work only in the HTML body. Pass only fixed HTML or a sufficiently checked value.
  • A double brace cannot be marked "checked" to skip escaping.
  • A template whose branches or each iterations end in different contexts, an unclosed tag, or an ambiguous URL or JavaScript context fails to render.
  • Template size has no fixed limit. Only the depth of recursive partials is limited, to 100000.
  • Do not modify the dictionary you passed until rendering finishes.

For a server that renders the same template repeatedly, parse it once at startup with GD.html.template(source, partials)?, then call execute(data)? on the returned value from each request. The parsed value is immutable and can be used by several requests at once. execute_bytes(data)? produces UTF-8 bytes directly, so they can be returned as is with GD.web.bytes(body, "text/html; charset=utf-8").

Authentication and CSRF

Login state is held by GD.web.sessions(). issue(value) creates a session ID, and the value of cookie(id) is returned as Set-Cookie. On routes that carry the same store as middleware, the value behind the cookie's ID arrives in req.kept("user"), and a missing session is a 401. An invalid middleware configuration returns null from its factory; passing it to app.use() or a route makes app.listen() report a configuration error.

var app := GD.web.app()
var sessions := GD.web.sessions()

func login(req: GDWebRequest) -> GDWebResponse, Err:
	var form := GD.http.decode_query(req.text()?)?
	var user := str(form.get("user", [""])[0])
	if user.is_empty():
		return GD.web.text("user is required", 400)
	var reply := GD.web.redirect("/me")
	return GD.web.header(reply, "Set-Cookie", sessions.cookie(sessions.issue(user)?))

func me(req) -> GDWebResponse, Err:
	return GD.web.text("hello, " + str(req.kept("user")))

func main():
	app.route("POST", "/login", login)
	app.route("GET", "/me", me, [sessions])
	app.listen(8080)!
	return 0

cookie(id) sets Secure and HttpOnly. If the cookie does not arrive during development without TLS, use cookie(id, false). Log out with drop(id) and clear_cookie(). Sessions live in one process, so with several processes under --workers use JWT or an external store.

Attach GD.web.csrf() to write paths that authenticate with cookies. Requests other than GET, HEAD, and OPTIONS need the browser's Sec-Fetch-Site: same-origin. When old browsers or non-browser clients must be accepted, choose GD.web.csrf({"allow_missing": true}) and combine it with separate token verification.

var app := GD.web.app()
var sessions := GD.web.sessions()

func save_email(_r):
	return "saved"

func main():
	app.route("POST", "/account/email", save_email, [GD.web.csrf(), sessions])
	app.listen(8080)!
	return 0

When JWT is used as a login session, revoke issued tokens on password change and logout. check is called after the signature and standard claims are verified, and authentication passes only when it returns true. For example, put the user's ver in the token and increment the stored version on password change. With several workers, compare against something like a cache synced from a shared DB, not a per-process dictionary.

func token_auth(key, versions):
	return GD.web.jwt(key, {"check": func(claims):
		return versions.get(claims.get("sub", ""), -1) == claims.get("ver", -2)
	})

To limit per IP behind a reverse proxy, list the proxy's IPs or CIDRs in trusted_proxies. gd strips trusted proxies from the right end of X-Forwarded-For and uses the first untrusted IP as the key. X-Forwarded-For is ignored when trusted_proxies is unset and when it comes from an untrusted peer, so a client cannot forge its own IP. IPv4 and IPv4-mapped IPv6 are matched as different things, so use an IPv6 CIDR to trust mapped addresses. Proxy settings with zones are rejected.

var per_ip := GD.web.rate({"limit": 60, "trusted_proxies": ["127.0.0.1", "172.18.0.0/16"]})

Allowed and 429 responses include X-RateLimit-Limit and X-RateLimit-Remaining. A 429 response also includes Retry-After in seconds.

Shutdown

Wait for shutdown with app.shutdown(context). It stops accepting new connections and keep-alive, then waits for in-flight requests. Past the deadline it returns Err.TIMED_OUT but does not kill in-flight requests. Use app.stop() when every connection must close immediately.

func close(app: GDWebApp):
	var context := GD.async.context().with_timeout(10.0)
	var _stopped, stop_err := app.shutdown(context)
	if stop_err:
		app.stop()

A handler can observe request completion and disconnection through req.context. with_cancel() and with_timeout() return a child context without changing the parent, and the parent's cancellation reaches the child. To cancel HTTP, database, process, and other two-result waits, wrap them with with_context_pair(), passing the context first. Use with_context() for single-value operations. The operation result is returned when it finishes first; when the context finishes first, the operation is canceled.

func load(req: GDWebRequest, db: GDDatabaseClient) -> Variant, Err:
	return await GD.async.with_context_pair(req.context, db.query_async("SELECT * FROM posts"))
Web operations and advanced features

Limits and large uploads

When handling large bodies or long handlers, set the limits explicitly with limits() before listening.

func main():
	var limited_app := GD.web.app()
	limited_app.limits({"header_bytes": 1048576, "header_values": 500, "header_timeout": 15.0, "body_timeout": 10.0, "job_timeout": 30.0, "jobs": 128})
	return 0

To accept a 1 GB ZIP, put a per-request limit on it and stream it to a writable mount.

func main():
	var app := GD.web.app()
	app.limits({"body_timeout": 600.0})
	app.route("POST", "/upload", func(req: GDWebRequest) -> GDWebResponse, Err:
		req.limit(1000 * 1000 * 1000)?
		req.save("uploads://package.zip")?
		return GD.web.text("saved")
	)
	var _server, listen_err := app.listen(8080, "127.0.0.1")
	return 0 if listen_err == null else 1
gd --strict --allow-net=127.0.0.1:8080 --mount=uploads=/srv/uploads:rw serve main.gd

How you read the body decides how much memory it uses.

ReadingMemory use
read(), save()Read a little at a time. save() never holds the whole body in memory
bytes(), text(), json()Read the whole remaining body into memory. The body is kept after the first read, so every call returns the same content. Use save() for large bodies
req.limit(bytes)Body limit for that request. Past it, the reading operation fails
  • The body has no default size limit. Set req.limit() on a public server.
  • The request header is limited to 1 MiB by default. Change it with header_bytes in limits().
  • A slow connection makes only that connection wait.

Streaming bodies

GD.web.stream(producer, length=-1, type="application/octet-stream", status=200) sends only what producer(writer) writes to the GDWebWriter. It never joins the whole body in memory. The producer may await, and it finishes by returning void or a value and Err.

GDWebWriterBehavior
write(data, offset=0, count=-1)Sends a range of a byte array and returns the accepted bytes. When sending is backed up, it waits until it progresses
write_text(text, offset=0, count=-1)Sends a range of a string as UTF-8. Offset and count are in characters; the result is in bytes
flush()Waits for preceding writes to be sent. A disconnect shows up as an error here and as req.context cancellation
  • A stream is single-use. Create a new one for each response. Finish reading the incoming body before returning the stream.
  • length is the number of bytes to send. If the declared and actual lengths differ, the connection is closed. Unknown length (-1) uses DATA frames on HTTP/2, chunked framing on HTTP/1.1, and connection close as the end on HTTP/1.0.
  • HEAD and statuses that cannot carry a body never call the producer.
  • Long-waiting producers should observe req.context cancellation.
  • One write does not necessarily correspond to one chunk. An empty string or empty byte array does not end the body.

HTTPS and HTTP/2

Start HTTPS with app.listen_tls(8443, "cert://chain.pem", "cert://key.pem", "127.0.0.1") and check the second Err result. Mount the certificate directory read-only with --mount cert=/path/to/certs:r. Pass a PEM chain and an unencrypted private key. When key validation fails, no port is opened.

TLS 1.2 and 1.3 are supported, and ALPN selects HTTP/2 or HTTP/1.1. Each HTTP/2 stream proceeds independently, and canceling one does not close the others. header_timeout also applies to an incomplete handshake. For requiring client certificates, see the TLS tables in "TCP and UDP".

gzip compression

GD.data.gzip_writer(writer, level=-1) creates a GDGzipWriter that gzips the bytes written to it and passes them to the writer below. The writer below can be a GDFileStream, a TCP connection, or a GDWebWriter. The whole body is never held in memory.

ItemDetails
Methodswrite(bytes), flush(), close(), and reset(writer). Each returns a value and Err
level-2 (Huffman only), -1 (default), and 0..9
close()Finishes the gzip trailer. It does not close the writer below
reset(writer)Clears errors and reuses the compressor at the same level
headername and comment (non-NUL Latin-1), extra (up to 65535 bytes), mod_time (Unix seconds from 0 to 4294967295), and os (default 255). Set it before the first write

For HTTP, return GD.web.header(GD.web.stream(producer), "Content-Encoding", "gzip"); the producer creates the compressor, writes, and returns the result of close(). Checking Accept-Encoding and setting Vary are up to the caller. Do not compress secrets together with external input, and do not apply it to an already compressed body or a partial response.

Listen address and port

For an IPv6-only localhost listener, use app.listen(8080, "::1")!. Under strict use --allow-net=[::1]:8080, and connect to http://[::1]:8080/. ::1 and 127.0.0.1 are separate listeners, and both differ from ::, which means every interface.

To let the OS pick a free port, read app.port() right after app.listen(0). The number is obtained while holding the listener, so no other process can take it. Check app.serve_error() for a listener failure after startup. Temporary resource shortages cause a short retry; a permanent failure closes the listener. Under strict the chosen port cannot be limited ahead of time, so allow the whole host, as in --allow-net=127.0.0.1. GD.net.free_port() and is_free() are momentary diagnostics, not a way to reserve that number.

HTTP client connections

  • HTTPS uses HTTP/2, and concurrent requests to the same origin share one connection. Peers without HTTP/2 and plain HTTP use HTTP/1.1.
  • An HTTP/1.1 connection is reused for the same origin after its body is read to the end. Idle connections are kept up to 100 overall, 2 per origin, for 90 seconds.
  • If a reused connection closes just after reuse, only a safely replayable method is retried once on a fresh connection.
  • On HTTP/2, only requests the peer marks as unprocessed are replayed, up to seven times with growing intervals. The request deadline and cancellation still apply.

Web settings

The settings passed as a dictionary to GD.http.fetch() and the GD.web functions, with their defaults. Times are seconds and sizes are bytes.

EntrySetting and defaultMeaning
GD.http.fetchmethod="GET", headers={}, body=nullHTTP method, request headers, request body
sametimeout=0.0, max_body=0Seconds for the whole request and bytes of the response body. 0 is unlimited. New TCP connections default to 30 seconds and TLS handshakes to 10 seconds
samesave="", sha256=""Stream a 2xx body to save, returning an empty body. sha256 requires save, is 64 hex digits, and only a matching completed file is placed
sameauthority="host:port"Request target for CONNECT only
GDWebApp.limitsjobs=0, job_timeout=0.0Number of async handlers kept and seconds. 0 is unlimited
sameheader_timeout=0.0, body_timeout=0.0Seconds to finish receiving request header/body. 0 is unlimited
sameheader_bytes=1048576, header_values=2147483647Header bytes including the request line, and the header line count
GD.web.jwt_signttl=900Seconds used to fill iat/exp. 0 does not add them
GD.web.jwt / jwt_verifyleeway=0.0, require_exp=trueClock tolerance in seconds, and whether exp is required
sameiss="", aud="", keep="jwt"Issuer/audience match when non-empty, and the name kept on the request
samecheck=Callable()Revocation check receiving claims after signature verification. When set, only true passes
GD.web.sessionstotal=1024, per_user=3Sessions per process, and per user
sameidle=1800, life=43200Idle and maximum lifetime in seconds
samecookie="sid", keep="user"Cookie name and the name kept on the request. The cookie name uses ASCII token characters
GD.web.ratelimit=60, window=60.0Largest burst per key, and the seconds that refill that many requests
sameexpires=180.0Seconds after the last request before a key is released
samekeys=0, key=Callable()Keys kept per process and the key selector. Zero is unlimited. A full explicit store evicts the earliest expiring key
sametrusted_proxies=PackedStringArray()IPs or CIDRs of proxies whose forwarded IP is trusted
GD.web.csrfallow_missing=falseWhether to allow state changes from clients without Fetch Metadata
GD.web.text_rulemin=0, max=4096Text length in characters
GD.web.int_rulemin=-9223372036854775808, max=922337203685477580764-bit integer range
GD.web.number_rulemin=-1e308, max=1e308Finite float range
GD.web.list_rulemin=0, max=1024Element count
GD.web.object_ruleextra=falseWhether to keep undeclared fields

GDWebApp.limits accepts only the six listed setting names and rejects misspellings and body_limit.

A value outside the accepted range fails when set. The ranges are listed with each function in the API reference.

Database

The client returned by GD.database.client() handles SQLite and PostgreSQL with the same code. Switching from the embedded SQLite in local development to PostgreSQL in production is done through the driver passed to open().

func main() -> int, Err:
	var local := GD.cli.env("DB_DRIVER", "sqlite") == "sqlite"
	var db := GD.database.client()
	db.open({
		"driver": "sqlite" if local else "postgres",
		"path": "user://app.sqlite3",
		"host": "127.0.0.1",
		"database": "app",
		"user": "app",
		"password": GD.cli.env("PGPASSWORD", ""),
	})?
	db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")?
	db.query("INSERT INTO users (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", [1, "ada"])?
	var out := db.query("SELECT id, name FROM users WHERE id=$1", [1])?
	print(out.rows[0].name)
	db.close()
	return 0

Table creation, INSERT, and SELECT all go through the one query(). It yields a dictionary with columns, rows, and tag, where rows is an array of dictionaries keyed by column name. In the example, out.rows[0].name is ada. SQL values are bound in order as $1, $2, and the spelling is the same on both drivers. SQL is not translated, so use SQL that works on both.

MethodPurpose
query(sql, args)Collect and return the whole result
query_row(sql, args)Return only the first row. Err.NOT_FOUND when there is no row
query_rows(sql, args)Open GDDatabaseRows and read one row at a time. For large results
stats()Connection count, in use, idle, wait count, wait duration, and cumulative close counts by reason

Advance query_rows() with while rows.next(). scan() returns a dictionary keyed by column name and values() returns an array in column order. After next() returns false, inspect err(). Call close() when stopping early.

func list_users(db: GDDatabaseClient) -> Variant, Err:
	var rows := db.query_rows("SELECT id, name FROM users ORDER BY id")?
	while rows.next():
		var user := rows.scan()?
		print(user.id, " ", user.name)
	if rows.err() != null:
		return null, rows.err()
	return null

On a constraint violation, the second result e.info carries machine-readable details. violation is one of duplicate, not_null, or foreign_key, and columns lists the related column names. On PostgreSQL, code, table, and constraint are included when the server returns them. Values themselves are never kept in info. A failure reported by SQLite itself keeps source="sqlite" and its extended source_code. SQLite's foreign key message has no column names, so columns is empty there.

func save(db: GDDatabaseClient) -> void:
	var _saved, e := db.query(
		"INSERT INTO users(id,name) VALUES($1,$2)",
		[1, "ada"])
	if e and e.info.get("violation") == "duplicate":
		var columns := e.info.get("columns", PackedStringArray())
		print("duplicate columns: ", columns)

Transactions and migrations

To make several updates one success or failure, use transaction(). The callback receives a GDDatabaseTx pinned to one connection. A null second result commits, while an Err rolls back.

func save(db: GDDatabaseClient, id: int, title: String) -> Variant, Err:
	return db.transaction(func(tx: GDDatabaseTx) -> int, Err:
		tx.query("INSERT INTO posts(id,title) VALUES($1,$2)", [id, title])?
		tx.query("UPDATE counters SET value=value+1 WHERE name='posts'")?
		return id
	)
  • Inside the callback, run SQL only through the given tx. The original db.query() is not part of this transaction.
  • A commit failure is returned as a failure.
  • Close or cancel before COMMIT begins rolls back; after it begins, the connection closes once the result is settled.
  • After the callback finishes, a retained tx no longer accepts new SQL.

When a PostgreSQL transaction fails because it collided with another one running at the same time (SQLSTATE 40001), serialize() retries it.

  • The function has the same shape as for transaction() and is called in a new transaction on every attempt.
  • It retries up to ten times. Another error or a cancellation stops it.
  • Keep effects that cannot be undone, such as sending mail, outside the function.
func increment(db: GDDatabaseClient, id: int) -> int, Err:
	var saved, e := db.serialize(func(tx: GDDatabaseTx) -> int, Err:
		tx.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")?
		tx.query("UPDATE counters SET value=value+1 WHERE id=$1", [id])?
		return id
	)
	return saved, e

To apply a schema in order, pass an array of statements to migrate() instead of splitting SQL on semicolons. If one statement fails, everything rolls back. On success it returns the number of statements applied. Versions and checksums are managed by the application.

func migrate(db):
	return db.migrate([
		"CREATE TABLE posts(id INTEGER PRIMARY KEY, title TEXT NOT NULL)",
		"CREATE INDEX posts_title ON posts(title)",
	])
Advanced database features

Driver differences

ItemSQLitePostgreSQL
Suited toLocal development, a single processProduction, crash resilience, several workers
ConnectionOne per client. Journal and temporary tables live in memoryA pool that opens only the connections it needs. Set a maximum as in pool=25
Extra entriesGD.database.sqlite.open() for short work done in placeGD.database.postgres for batched sends, arrays, and JSONB
NotesPersistent databases recover unfinished writes with a rollback journal. Checkpoint existing -wal and -shm files with regular SQLite before openingHosts other than loopback verify the TLS certificate and host name by default. Loopback defaults to no TLS

open() on GD.database.postgres.client() and GD.database.redis.client() takes the target as arguments, in the form open(host, port, opts).

SQLite concurrency

query() calls on one client run in arrival order. Separate clients proceed concurrently, while writes to the same database file follow SQLite locking. The GDSQLiteDB and GDSQLiteStatement returned by GD.database.sqlite.open() are a synchronous API that runs directly on the caller. Use them only for short work and never concurrently. Use GDDatabaseClient for concurrent work.

PostgreSQL connections and types

The pool opens connections as they are needed and takes them back after use. Normally you just call query() without thinking about connections. When none is free, queries wait in turn.

GoalHow
Run several SQL statements as one unitUse transaction() instead of sending BEGIN yourself
Send several SQL statements togetherquery_many, fetch_many, exec_many
Detect a duplicate insertErr.ALREADY_EXISTS. Read the SQLSTATE in e.info.code for the exact cause
See whether there are enough connectionswait_count in stats() (times a query waited for a connection)
Pin the authentication methodauth="scram". auth="md5" is for older servers

Column values arrive as these types.

Column typeReceived value
real, double precisionfloat
numericText, so no digits are lost
json, jsonbDictionaries and arrays. Integers stay int
Arrays such as int[] and text[]An Array of the same element type. Nulls and nesting are kept

A query that is cancelled or times out closes its connection. The SQL on the server may not stop at once. The character encoding is UTF-8.

Redis connections

Use Redis through GD.database.redis.client(). Pass the command name and its arguments separately to query().

func main() -> int, Err:
	var redis := GD.database.redis.client()
	redis.open("127.0.0.1", 6379)?
	redis.query("SET", ["greeting", "hello"])?
	print(redis.query("GET", ["greeting"])?)
	redis.close()
	return 0
GoalHow
Tell that a value is missingGET returns Err.NOT_FOUND
Send several commands togetherpipeline(cmds). Results come back as an Array in the order sent
Use it from many requests at onceGD.database.redis.pool(). Connections open on the first query()
Use MULTI, WATCH, SELECT, or subscriptionsA dedicated GDRedisClient, not the pool
Set a deadlinetimeout in open() (seconds)

The TLS choice is the same as PostgreSQL.

Database settings

The settings passed as a dictionary to open(), with their defaults.

EntrySetting and defaultMeaning
GDDatabaseClient.opendriver="postgres", path=""Driver and SQLite path: user://, a name mounted writable with --mount, or :memory:. res:// also works without --strict
samehost="127.0.0.1", port=5432PostgreSQL target
samepool=0PostgreSQL maximum connections. 0 is unlimited. Unused by SQLite
samemax_rows=0, max_bytes=0Rows and bytes per result collected by query(). 0 is unlimited. Not applied to query_rows()
GDPostgresClient.openuser="postgres", database="postgres", password=""Credentials and database name
sameconnect_timeout=0.0, timeout=0Connect and query seconds. Waiting for a pool connection counts toward the query time. Zero has no deadline; set either deadline when needed
sameauth="any", allow_cleartext_password=falsePin the method with auth="scram"/"md5". A cleartext password reply only when explicit
sametls=<decided by host>, ca=""External hosts use verify-full, loopback disable. A CA file only when explicit
GD.database.sqlite.openbusy_ms=0, max_ms=0, foreign_keys=falseLock wait and execution deadline in milliseconds. busy_ms=0 reports contention immediately; max_ms=0 has no execution deadline. Enable foreign-key checks explicitly
samemax_rows=0, max_bytes=0Rows and bytes per result. 0 is unlimited
GDRedisClient.openpassword="", dial_timeout=5, read_timeout=5, write_timeout=5Password, and connect, read, and write deadlines in seconds. An explicit 0 is unlimited. timeout sets all three, and an individual setting wins
sametls=<decided by host>, ca=""The same TLS choice as PostgreSQL
GD.database.postgres.poolsize default 0; 0 or 1..21474836470 is unlimited. Connections open only as needed
GDPostgresPool.openmax_idle=2Connections kept after work ends. 0 keeps none. Never exceeds the maximum
GD.database.redis.poolsize default 0; 0..2147483647Maximum connections. 0 selects ten times the CPU count. Simultaneous dials do not exceed the maximum
GDRedisPool.openpool_timeout=read_timeout+1.0 (30 seconds when the read deadline is 0), conn_max_idle_time=1800Deadline for waiting for a free connection, and how long a returned connection stays reusable. An explicit 0 is unlimited. An expired idle connection is closed at the next borrow

Set read_timeout explicitly to extend the deadline for a long Redis query.

A query() over max_rows or max_bytes fails only that query. The whole connection is closed when ordering is lost through a deadline or a corrupt reply.

A value outside the accepted range fails when set. The ranges are listed with each function in the API reference.

Scheduled jobs

A job that runs once at a fixed time is an ordinary script, called from the OS's cron or a systemd timer. gd needs no resident scheduler for it.

func collect() -> int, Err:
	var now := GD.time.to_iso(GD.time.now())
	GD.file.append_text("store://log.txt", now + "\n")?
	return 0

func main() -> int, Err:
	collect()?
	return 0
gd --strict --mount store=/var/lib/app:rw collect.gd

A job that loops on its own interval is passed to GD.async.spawn() and kept resident with gd serve. Work passed to spawn() keeps running after main() returns.

func every(sec, fn):
	while true:
		await GD.async.sleep(sec)
		fn.call()

func collect():
	print(GD.time.to_iso(GD.time.now()))

func main():
	var _job := GD.async.spawn(every.bind(60.0, collect))
	return 0
gd serve schedule.gd

Stop it by ending the process. It is resident like a Web server, so serve is needed here too.

Official extension modules

The core stays small. Features specific to an external service are added as GDScript packages or GDExtensions only to projects that need them.

EntryPurposeSetup
DiscordPure-GDScript text bots on the Discord Gateway and RESTgd add @gd/discord
GDSupabaseDatabase and Auth clientgd add ext:@gd/supabase

Browse published packages in the package list. Because they are optional, they are not part of the API reference generated from the core.

  • Extensions added with gd add are trusted and loaded at startup, so no flag is needed. Under --strict, their target needs --allow-net.
  • --allow-ext and --deny-ext apply when a script loads one while running with GDExtensionManager.load_extension().
  • An added extension runs with the same privileges as the process, so pin the versions you trust in gd.lock and commit it.

Packages and distribution

To use a package someone else published, create gd.json with gd init and then add the package. Find published packages in the package list or with gd search.

gd init
gd add hello
GoalCommand
Searchgd search discord
Addgd add hello (gd install hello does the same)
Choose the scope or a version rangegd add @gd/hello@^0.8.0
Add under a name you choosegd add greet @gd/hello
Add a native extensiongd add ext:@gd/supabase
Add from a URL or a local directorygd add util https://example.com/util.gd, gd add ../mylib
Restore the same versions elsewheregd install --frozen
Check for and move to newer versionsgd outdated, gd update
Removegd uninstall hello
List what is installedgd info

Dependencies are recorded in gd.json (what you use) and gd.lock (which versions). Commit both. gd install without arguments restores the dependencies in gd.json; --frozen, --cached-only, and --sync apply to that restore.

Using packages

Read an installed package by writing @import alias at the top of a script.

@import hello
  • The package itself lives in the per-user shared cache (pkg://<alias>/); nothing is copied into the project.
  • A dependency named in gd.json but absent from the cache is fetched on the first run. Under --strict the registry needs --allow-net.
  • A short name such as gd add hello is looked up in the registry. When two or more packages share the name, gd asks which one to use.
  • The default alias of gd add is the package name with - and . turned into _, so it is an identifier. Aliases that are engine classes or keywords are refused.
  • Commit gd.json and gd.lock. gd init writes pkg/ into .gitignore.
  • --frozen does not change the lock. For an offline target, fetch first where a network is available, and add --cached-only.
  • When install, add, or update fails partway, project files and the lock are restored.
  • The lock is bound to its registry. Switching to another registry requires explicit lock migration.

Installing as a command

gd install -g installs a package or script as a command such as my-tool. It leaves the gd.json and gd.lock of the project you are in untouched.

gd install -g tool                      # Install a published package by its short name.
gd install -g @scope/tool@1.0.0         # Choose the scope and version.
gd install -g --name my-tool ./tool.gd  # Install a local script.
gd uninstall -g my-tool
FlagMeaning
-n / --nameCommand name. Defaults to the package or script name (the parent directory name for main.gd or mod.gd)
--root <dir>Install location. Defaults to GD_INSTALL_ROOT, then the default cache. Add its bin/ to PATH
-f / --forceUpdate an installed command
-- argsFixed arguments passed first on every launch
  • A short name such as tool is looked up in the registry. When two or more packages share the name, gd lists them and asks which one to use. Writing @scope/tool skips the question.
  • The entry is a script with main(args). A published package uses mod.gd; a local directory uses main in its gd.json.
  • --allow-* and --mount given at install time apply on every launch.
  • A failed update leaves the installed command as it was.
  • Remove a command installed with --root by passing the same --root.

Short import syntax

@import is the short form of const Name = preload(...).

It is useful even without external dependencies: see samples/packages for a real registry dependency and its lockfile.

@import greet
@import "./util"
@import greet/style as theme
  • Unquoted names resolve only aliases declared in the imports of gd.json. Files with the same name are not searched.
  • Quote relative files, starting with ./ or ../. The .gd extension is optional. If a file and directory share a name, specify the file as "./util.gd".
  • Without as, the identifier is the last segment as written, and a directory holding mod.gd binds its directory name.
  • gd fmt keeps @import as it is.
  • Upstream Godot does not know @import, so files shared with Godot should spell out const and preload.

Creating a package

A package is one project rooted at its gd.json. gd init @scope/name seeds mod.gd and a test, gd test runs it, and gd publish releases it.

{"name":"@scope/hello","version":"1.0.0","main":"src/mod.gd","include":["src"]}

Package files are distributed from the author's GitHub Release. The registry keeps only where the files are and their fingerprints (SHA-256).

gd publish                         # Write the release files to tmp/release/scope-hello-1.0.0/.
gh release create 1.0.0 tmp/release/scope-hello-1.0.0/*
gd publish https://github.com/OWNER/REPO/releases/download/1.0.0
gd add hello gd:@scope/hello@^1.0.0

1. gd publish without an argument writes the files to publish to tmp/release/<scope>-<name>-<version>/. Each file is named by the SHA-256 of its contents. 2. Upload them as assets of a GitHub Release. Files of several packages or versions can share one release without name clashes. 3. Run gd publish with the release's download URL. gd fetches each file from the URL, confirms it matches the local one, and then lists the version in the registry.

Packages submitted to the public registry become searchable and installable after review. When gd publish prints a review ID, the version remains private until accepted. The registry checks the release files again just before acceptance.

  • Users' gd fetches the files straight from GitHub and checks them against the registry's fingerprints. Replacing a release file makes the check fail and the package uninstallable.
  • The entry is mod.gd. For multiple files, list files or directories in include.
  • The main file's directory becomes the package root, so relative preloads inside the package keep working.
  • A package may use other registry packages through the imports of its own gd.json. gd publish records those imports in the registry.
  • class_name may be published. Installation checks for conflicts between classes of the same name and rolls everything back on a conflict.
  • Setting godot to true in gd.json is the author's declaration that the package runs on upstream Godot without gd's own API, and gd search marks it [godot].

A package under development is added from a local path with gd add ../path. Its alias comes from the name in its gd.json. The checkout is copied under pkg/<alias>/ and copied again on the next run whenever its content fingerprint changes. Files starting with ., pkg/, tmp/, subdirectories holding a gd.json, and token are not copied. gd publish turns a local import into its registry range when the target's gd.json has name and version, and refuses it otherwise.

Local development channel

Start the real registry on loopback from the repository. It saves the registry's records under tmp/dev-channel/data.

export GD_TOKEN='development token'
uv run --no-project python -B devtools/channel.py serve --scope dev --port 8787

In another terminal, set GD_REGISTRY=http://127.0.0.1:8787 and the same GD_TOKEN. Run gd publish --dry-run and gd publish from an @dev/name package. Serve the written files from loopback, for example with python3 -m http.server 8788 --bind 127.0.0.1 --directory tmp/release, and list them with gd publish http://127.0.0.1:8788/dev-name-1.0.0. Only development registries accept loopback HTTP. Consumers using that GD_REGISTRY can run gd search, gd add, gd install, gd install -g, and gd compile. A project's registry in gd.json takes precedence over the environment.

Dependency resolution

gd install resolves the whole dependency graph. It picks a version in this order: the version gd.lock pins, a version already chosen this time that satisfies the range, then the newest match in the registry.

gd.lock also records the resolved imports configuration. A run after a configuration change uses the same resolver instead of silently loading an outdated version. --frozen rejects mismatched requests. When multiple aliases name one package, the lexicographically first alias selects its copy directory.

  • Pure GDScript packages coexist as distinct versions.
  • A native extension loads only once per process, so it is unified to one version. If the ranges cannot agree, it stops before anything is fetched.
  • There is no mechanism for plugins that share one host instance (peer dependencies).
  • The canonical path of a registry package is pkg://@scope/name@version/. pkg://<alias>/ expands to it through the imports of the package the script belongs to. The same alias may name different versions in different packages, and one version is one script however it is reached.
  • gd.lock also records each package's resolved imports, and gd info lists them.
  • gd uninstall and gd update drop what no package uses any more from gd.lock and pkg/.
  • A change in search ranking does not affect installation or lock verification for a known package.

Sharing a location with Godot

To share a project with tools that only read res://, such as upstream Godot, set "place": "project" in gd.json. Packages are copied under pkg/<alias>/, and both pkg:// and res://pkg/ point there. A package that only other packages use goes under pkg/@scope/name@version/.

  • gd install --godot copies packages under addons/<alias>/. Also pass --godot to add, update, uninstall, and info. An addons/ directory inside a package does not cause the rest of the package to be excluded.
  • Where project.godot exists, place defaults to project and no .gitignore is written. Commit pkg/ so teammates without gd can open the project.
  • Installation rewrites res:// references written in preload, load, and extends to the placement. Strings, comments, and paths built at run time are not rewritten.
  • place only selects where files live. It does not convert gd's own API or syntax for Godot. Shared source should use standard syntax and relative preloads.

Native extension packages

  • A native extension needs real files to load, so it lives under pkg/<alias>/ whatever place is.
  • A script may only name classes of the extensions its own package imports with ext:: the project's gd.json for project scripts, the package's own imports for package scripts.
  • An extension outside the registry is usable by project scripts only.
  • A registry package's extension that registers a class missing from its manifest's [classes] stops startup.
  • Fetch on the target OS, or run gd compile on the target OS.

Settings and environment variables

gd.json has these eleven settings.

NameWritten by gd init / when omittedMeaning
namemy-tool / requiredProject name. Publishing needs @scope/name
version0.1.0 / requiredPackage version
tasksrun and test / noneCommands invoked by gd task
imports{} / {}Alias and dependency source. A published package may name registry packages only
registryomitted / environment or the public registryRegistry URL pinned to the project
mainomitted / mod.gdmod.gd or .gdextension entry published
includeomitted / main onlyFiles or directories inside the main directory included in a pure GDScript package
placeomitted / cache, or project beside project.godotWhere packages live. project copies them under pkg/
godotomitted / falseDeclares a package that runs on upstream Godot without gd's own API
descriptionomitted / emptyDescription shown in the registry
assetsomitted / noneGodot asset management alias and channel:publisher/slug[@version]; installed into addons/

gd reads these environment variables. A script that reads the environment needs the names allowed with --allow-env.

VariablePurpose
GD_CACHE_HOMEPackage cache root. Defaults to gd in Windows LocalAppData. On macOS/Linux, uses an absolute XDG_CACHE_HOME plus /gd, or .gd under the home directory. The OS account directory is used when HOME is unset
GD_INSTALL_ROOTWhere gd install -g places commands. --root wins
GD_USER_HOMEAbsolute path for user://. By default it is created per script directory in the OS user data folder (~/Library/Application Support/gd/user on macOS, ~/.local/share/gd/user on Linux, %APPDATA%/gd/user on Windows)
GD_REGISTRYRegistry. Defaults to https://gd.progsha.com/pkg. registry in gd.json wins
GD_RELEASESRelease source read by gd upgrade. Defaults to https://github.com/prog-sha/gd/releases
GD_TOKENPublish token. Keep it out of config files and pass it only to the publishing process
LC_ALL, LANGLanguage of the manual shown by gd doc
GD_WORKERInternal mark set by --workers. Not a user setting

Remote packages and registries use HTTPS. A development registry on loopback may also use HTTP. Fetched packages and native libraries are checked against the SHA-256 in the registry index. All files in a package are limited to 500 MiB in total.

Distributing a single executable

compile collects scripts, views, static files, migrations, dependency packages, and the target OS's GDExtensions into one executable. The target needs no cache.

gd compile -o app main.gd
./app
  • Every package gd.json names, and every package those import, is embedded.
  • An embedded Web app can also stay resident with ./app serve --no-scene-tree --allow-net.
  • From a local path package, files starting with . such as .env and the token in gd.json are left out.
  • Do not embed secrets in source. compile excludes .env, but values written in source remain in the executable.

Asset channels

gd search includes packages, the public Godot asset catalog, and the reviewed gd catalog. A project using a custom registry searches only that registry.

ChannelSource
officialGodot Asset Store
gdReviewed gd assets

Copy an asset:channel:publisher/name result directly into gd add.

gd search dialog
gd add asset:official:publisher/dialog
gd add ui asset:gd:publisher/dialog@1.2.0
gd install --frozen --cached-only
gd update ui
gd uninstall ui
  • Duplicate version labels require a release ID, such as asset:official:publisher/dialog@#123. Quote the complete argument when a label contains spaces.
  • Omitting the channel selects official. Failure never redirects resolution to another catalog.
  • gd.json records requests under assets; gd.lock pins the origin, version and SHA-256. Commit both files.
  • Godot assets specified with asset: copy the ZIP's addons/ tree into the project's addons/. Asset aliases are management names. Ordinary packages are recorded under imports and loaded with @import.
  • Initial selection checks engine compatibility and prefers stable releases. Later installs reuse the lock; update selects again. An explicit version such as @1.2.0 remains fixed during update.
  • --frozen preserves the lock; --cached-only performs no network requests. Fetch archives before moving offline.
  • Unmanaged or locally edited addon directories are not overwritten. A failed operation restores packages, addons, configuration and the lock together.
  • The gd catalog reviews descriptions, download URLs and SHA-256 values. Archives remain hosted by their authors; gd verifies their digests. The Godot editor does not use this additional digest field and does not provide the same verification.

The source distribution also includes a catalog inspection client:

gd tools/store.gd channels
gd tools/store.gd search official 4.7 dialog
gd tools/store.gd show gd publisher dialog
gd tools/store.gd releases gd publisher dialog

Scope and reporting

gd is a public release before the API has settled. Do not assume backward compatibility. Changes and the Godot version used as the base are recorded in the CHANGELOG. gd is not an official product of the Godot Foundation or the Godot Engine project.

Report bugs in Issues. Report vulnerabilities that should not be public through GitHub private reporting.

Features in development (for reference)

The features below are still in development. Their usage and behavior may change without notice. Treat this section as a preview.

Editor (gd-godot)

gd editor opens the editor. The first run installs gd-godot, the executable that provides the window.

GoalCommand
Open the editorgd editor
Open a chosen projectgd editor <project directory>
Run a project in a windowgd run-game <project directory>

See the gd-godot manual for details.

Online games

GD.online.match() creates a server that finds opponents for online games. Rooms announce their address and player count, and joining players receive one room with free seats. State lives in process memory, or in a key-value server shared by several processes. Marking variables with @online to synchronize state between server and clients is also in preparation.

APIリファレンスAPI reference

gdの関数やオブジェクトについて、引数と戻り値を一覧にしています。Godot由来の型はGodotのクラスリファレンスを参照してください。

Signatures of gd's own entry points and of the objects they return. For Godot classes, see the Godot class reference.

一致するAPIがありません。No matching API.

GD

ファイル、データ変換、非同期処理、日時など、コマンドラインのプログラムで使う標準機能をまとめています。

Entry to the standard features of a command-line program: files, data, async, time, and more.

Properties

async: GD.async
非同期処理を開始したり、複数の処理の完了を待ったり、タイムアウトやキャンセルを扱ったりします。最初に完了した処理の結果を受け取ることもできます。spawnは関数をメインスレッド上で開始します。大きなデータの計算には、各標準モジュールの_async付き関数を使います。
Entry for async work: waiting, concurrency, racing, timeouts, and cancellation. spawn starts a main-thread coroutine; CPU work belongs in each standard module's _async entry points.
log: GD.log
重要度、時刻、出力先を指定してログを記録します。1行ずつ順番に書き込み、各呼び出しは完了を待って値とErrを返します。flushで、それまでの出力が終わるのを待てます。
Entry for ordered I/O of one line at a time with a consistent level, time, and destination. flush waits for earlier output.
net: GD.net
TCP・TLSの接続、接続の待ち受け、UDP通信、名前解決、アドレスの検査を行います。TLSでは既定で証明書チェーンと接続先のホスト名を検証します。完了を待つのは、呼び出した処理だけです。
Network entry for TCP and TLS streams, listeners, UDP packets, name resolution, and address checks. TLS verifies the certificate chain and server name by default; waiting operations suspend only their caller.
mail: GD.mail
メールアドレス、日付、ヘッダーを解析し、SMTPサーバーへメールを送ります。STARTTLSは既存接続を暗号化し、失敗時は平文へ戻りません。MIMEの機能はGD.mail.mimeにあります。
Parse mail addresses, dates, and headers, and submit messages over SMTP. STARTTLS upgrades the existing connection without falling back to plaintext. MIME helpers are under GD.mail.mime.
http: GD.http
HTTPリクエストの送信、URL・クエリ文字列・メディアタイプの組み立てと解析を行います。fetchは呼び出した処理だけを待たせ、fetch_asyncはGDTaskを返します。
Entry for HTTP requests plus URL, query, and media-type handling. fetch suspends only its caller; fetch_async returns a GDTask for composition.
web: GD.web
WebサイトやWeb APIを作るための機能です。URLと処理の対応付け、静的ファイル配信、HTMLテンプレート、セッション、CSRF対策、JWT認証、リクエスト数の制限、入力検査を利用できます。
Entry for building websites and Web APIs, with routes, static files, gdhtml templates, sessions, CSRF, JWT, rate limiting, and input validation.
file: GD.file
ファイルの読み書き、パスの操作、各種データ形式の読み取りを行います。ファイル全体を扱う場合も少しずつ読み書きする場合も、呼び出した処理だけが完了を待ちます。_async付きの関数はGDTaskを返します。
Whole-file operations and streaming file I/O suspend only their caller. This entry also provides path operations and file-format readers; *_async returns a GDTask for concurrent starts.
collection: GD.collection
配列や辞書の変換、ヒープ、キュー、キャッシュを扱います。時間のかかる処理は別スレッド、またはほかの処理と交代しながら進めます。Callableを使う操作も、SceneTreeのフレームを待たずにほかのタスクへ実行を譲ります。
Reshape Arrays and Dictionaries and create heaps, queues, and caches. Awaitable operations use CPU workers or the runtime ready queue; callable work cooperates with other tasks without requiring SceneTree frames.
data: GD.data
バイト列、データ形式の変換、ハッシュ、鍵の生成を扱います。CSV・INI・TOML・YAML・JSON・XMLなどをメモリ上で変換できます。不正な入力や設定はエラーとして返します。
Data conversion for bytes, binary codecs, hashes, key derivation, and in-memory CSV, INI, TOML, YAML, JSON, XML, and related formats. Invalid input and settings return failures.
id: GD.id
UUIDと、時刻順に並べられるULIDを生成・検査します。ULID時刻の-1は現在時刻を選び、その他の48ビット範囲外は空文字を返します。範囲外の符号化文字列は拒否します。
Entry for generating and checking UUIDs and time-ordered ULIDs. Timestamp -1 selects the current time; other values outside the 48-bit range return an empty string. Encoded overflow is rejected.
text: GD.text
文字列の整形と比較を行います。
Entry for formatting and comparing text.
html: GD.html
HTMLの文字参照、タグ、テンプレートを扱います。テンプレートへ埋め込む値は、本文、属性、URL、スタイル、スクリプトのどこに使うかに応じてエスケープします。
Entry for HTML entities, tags, and templates with context-sensitive escaping for text, attributes, URLs, styles, and scripts.
math: GD.math
数学関数、IEEE 754の特殊な値、浮動小数点数とビット列の変換を扱います。
Entry for standard mathematical functions, IEEE 754 special values, and bit conversions.
version: GD.version
セマンティックバージョンを解析・比較し、指定したバージョン範囲に含まれるか調べます。
Entry for parsing, comparing, and range-matching Semantic Versions.
time: GD.time
Unix時刻、ISO 8601、HTTPの日付を変換・計算します。parse_isoはRFC 3339形式を受け取ります。加算や差分が64ビット整数の範囲を超える場合は、最大値または最小値になります。
Entry for converting and computing Unix time, ISO 8601, and HTTP dates. parse_iso accepts RFC 3339, and add and diff clamp at the 64-bit integer ends.
cli: GD.cli
gdのバージョンや文書の表示、コマンドライン引数、環境変数、システム情報の取得に使います。アクセス権限の設定に従います。
Entry for gd's version and docs, flags, and allowed environment and system information.
test: GD.test
期待した結果と実際の結果を比較する、テスト用の機能です。
Entry for small test helpers that collect asserts.
database: GD.database
SQLiteとPostgreSQLを共通のAPIで扱います。処理の完了を待つ間も、ほかのGDScriptは動き続けます。_async付きの関数はGDTaskを返し、あとからawaitで結果を受け取れます。
Database entry shared by SQLite and PostgreSQL. Synchronous-looking calls suspend only their GDScript; *_async returns a GDTask for composition.
online: GD.online
オンラインゲームのマッチング先を管理します。ゲームの同期とゲスト認証はgd-godotのOnlineとSecretで行います。
Manage matchmaking destinations for online games. Online and Secret in gd-godot handle game synchronization and guest authentication.
標準モジュールStandard modules

GD.async

非同期処理を開始したり、複数の処理の完了を待ったり、タイムアウトやキャンセルを扱ったりします。最初に完了した処理の結果を受け取ることもできます。spawnは関数をメインスレッド上で開始します。大きなデータの計算には、各標準モジュールの_async付き関数を使います。

Entry for async work: waiting, concurrency, racing, timeouts, and cancellation. spawn starts a main-thread coroutine; CPU work belongs in each standard module's _async entry points.

Methods
set_max_threads(max: int) -> int
sleep(sec: float) -> GDTask (await Variant)
spawn(fn: Callable) -> GDTask (await Variant)
spawn_pair(fn: Callable) -> GDTask (await Variant, Err)
call_pair(fn: Callable) -> Variant, Err
動的に選んだCallableを呼び、値とErrを二つの結果として受け取ります。
Call a dynamically selected Callable and receive its value and Err as two results.
all(tasks: Array) -> GDTask (await Array)
race(tasks: Array) -> GDTask (await int)
with_timeout(task: Variant, sec: float) -> GDTask (await int)
with_context(context: GDAsyncContext, task: Variant) -> GDTask (await Variant)
with_context_pair(context: GDAsyncContext, task: Variant) -> GDTask (await Variant, Err)
context() -> GDAsyncContext

GD.log

重要度、時刻、出力先を指定してログを記録します。1行ずつ順番に書き込み、各呼び出しは完了を待って値とErrを返します。flushで、それまでの出力が終わるのを待てます。

Entry for ordered I/O of one line at a time with a consistent level, time, and destination. flush waits for earlier output.

Methods
setup(name: String = "", level: String = "info") -> void
set_file(path: String) -> void
set_time(on: bool) -> void
set_color(on: bool) -> void
write(level: String, msg: String, extra: Variant = null) -> Variant, Err
debug(msg: String, extra: Variant = null) -> Variant, Err
info(msg: String, extra: Variant = null) -> Variant, Err
warn(msg: String, extra: Variant = null) -> Variant, Err
error(msg: String, extra: Variant = null) -> Variant, Err
result(error: Err, msg: String) -> Variant, Err
write_async(level: String, msg: String, extra: Variant = null) -> GDTask (await Variant, Err)
debug_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)
info_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)
warn_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)
error_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)
result_async(error: Err, msg: String) -> GDTask (await Variant, Err)
format(level: String, msg: String, extra: Variant = null) -> String
flush() -> Variant, Err
flush_async() -> GDTask (await Variant, Err)

GD.net

TCP・TLSの接続、接続の待ち受け、UDP通信、名前解決、アドレスの検査を行います。TLSでは既定で証明書チェーンと接続先のホスト名を検証します。完了を待つのは、呼び出した処理だけです。

Network entry for TCP and TLS streams, listeners, UDP packets, name resolution, and address checks. TLS verifies the certificate chain and server name by default; waiting operations suspend only their caller.

Methods
is_free(port: int, host: String = "127.0.0.1") -> bool
free_port(from: int = 0, host: String = "127.0.0.1") -> int, Err
resolve(host: String) -> String, Err
resolve_async(host: String) -> GDTask (await String, Err)
dial_tcp(host: String, port: int, opts: Dictionary = { }) -> GDTCPConn, Err
dial_tcp_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)
dial_tls(host: String, port: int, opts: Dictionary = { }) -> GDTCPConn, Err
証明書を検証してTLS接続を開きます。optsにはtimeout、server_name、insecure_skip_verify、ca_file、クライアント認証用のcert_file/key_file、ALPNの候補を並べたnext_protosを指定できます。証明書ファイルのアクセス権限は別スレッドで確認します。認証に失敗しても暗号化なしの接続には切り替えません。
Dial a verified TLS connection. Options include timeout, server_name, insecure_skip_verify, ca_file, paired cert_file/key_file for client authentication, and next_protos as an array of ALPN strings. File access is permission checked on a worker. Failed authentication never falls back to plaintext.
dial_tls_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)
listen_tcp(host: String = "127.0.0.1", port: int = 0) -> GDTCPListener, Err
listen_udp(host: String = "127.0.0.1", port: int = 0, buffer: int = 0) -> GDUDPPacketConn, Err
is_free_async(port: int, host: String = "127.0.0.1") -> GDTask (await bool)
free_port_async(from: int = 0, host: String = "127.0.0.1") -> GDTask (await int, Err)
local_addresses() -> PackedStringArray, Err
local_addresses_async() -> GDTask (await PackedStringArray, Err)
is_ip(text: String) -> bool
split_host(text: String, default_port: int = 80) -> Dictionary

GD.mail

メールアドレス、日付、ヘッダーを解析し、SMTPサーバーへメールを送ります。STARTTLSは既存接続を暗号化し、失敗時は平文へ戻りません。MIMEの機能はGD.mail.mimeにあります。

Parse mail addresses, dates, and headers, and submit messages over SMTP. STARTTLS upgrades the existing connection without falling back to plaintext. MIME helpers are under GD.mail.mime.

Properties

mime: GD.mail.mime
MIMEメディアタイプ、encoded-word、quoted-printable、multipartの読書きを扱います。
Parse and format MIME media types, encoded words, quoted-printable bytes, and multipart bodies.
Methods
parse_address(text: String) -> Dictionary, Err
parse_address_list(text: String) -> Array, Err
parse_date(text: String) -> Dictionary, Err
read_message(data: PackedByteArray) -> GDMailMessage, Err
read_message_async(source: Variant) -> GDTask (await GDMailMessage, Err)
plain_auth(user: String, password: String, identity: String = "") -> Dictionary
cram_md5_auth(user: String, secret: String) -> Dictionary
cram_md5(key: PackedByteArray, challenge: PackedByteArray) -> String, Err
dial_smtp(host: String, port: int, opts: Dictionary = { }) -> GDSMTPClient, Err
dial_smtp_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDSMTPClient, Err)
send_mail(host: String, port: int, from: String, to: PackedStringArray, message: PackedByteArray, opts: Dictionary = { }) -> Variant, Err
send_mail_async(host: String, port: int, from: String, to: PackedStringArray, message: PackedByteArray, opts: Dictionary = { }) -> GDTask (await Variant, Err)

GD.http

HTTPリクエストの送信、URL・クエリ文字列・メディアタイプの組み立てと解析を行います。fetchは呼び出した処理だけを待たせ、fetch_asyncはGDTaskを返します。

Entry for HTTP requests plus URL, query, and media-type handling. fetch suspends only its caller; fetch_async returns a GDTask for composition.

設定Settings: timeout max_body method authority headers body save sha256

Methods
fetch(url: String, opts: Dictionary = { }) -> GDHTTPResponse, Err
レスポンスとErrを返します。通信に失敗した場合も、受信済みの内容が残ることがあります。HTTPの4xx・5xxは通信エラーではなく、レスポンスのステータスコードで確認します。
Return response, Err. Transport failures retain a partial response; HTTP 4xx/5xx are valid responses.
fetch_async(url: String, opts: Dictionary = { }) -> GDTask (await GDHTTPResponse, Err)
parse_url(raw: String) -> Dictionary, Err
URLを解析します。raw_queryには元のクエリ文字列、queryには解析できた項目が入ります。クエリ文字列の解析エラーはdecode_queryで確認してください。
Parse URL structure, retaining the original raw_query and valid entries in query. Use decode_query to inspect query errors.
parse_url_async(raw: String) -> GDTask (await Dictionary, Err)
build_url(url: Dictionary) -> String
URLを組み立てます。raw_queryがあれば優先します。queryの内容を変更してURLを作り直す場合は、raw_queryを削除してください。
Build a URL, preferring raw_query when present. Remove raw_query after editing query to regenerate its encoded representation.
build_url_async(url: Dictionary) -> GDTask (await String)
request_target(url: Dictionary) -> String
request_target_async(url: Dictionary) -> GDTask (await String)
default_port(scheme: String) -> int
decode_query(raw: String) -> Dictionary, Err
キーごとの値をすべてArrayに入れた辞書と、最初のErrを返します。読み取れた項目は残します。不正なUTF-8やNULを含むキーと値はPackedByteArrayで保持します。
Return all values per key as Arrays and the first Err, retaining valid pairs. Non-UTF-8 or NUL-containing keys and values remain PackedByteArray.
decode_query_async(raw: String) -> GDTask (await Dictionary, Err)
encode_query(query: Dictionary) -> String
クエリ文字列を作ります。値がArrayなら同じキーを繰り返し、キーのバイト順に並べます。単一の値とPackedByteArrayにも対応し、空白は+に変換します。
Encode scalar or Array values, repeating keys in byte-sorted order. PackedByteArray preserves arbitrary bytes; spaces become +.
encode_query_async(query: Dictionary) -> GDTask (await String)
media_type(path: String) -> String
media_type_for_extension(ext: String) -> String
is_textual(kind: String) -> bool
extension_for_media_type(kind: String) -> String

GD.web

WebサイトやWeb APIを作るための機能です。URLと処理の対応付け、静的ファイル配信、HTMLテンプレート、セッション、CSRF対策、JWT認証、リクエスト数の制限、入力検査を利用できます。

Entry for building websites and Web APIs, with routes, static files, gdhtml templates, sessions, CSRF, JWT, rate limiting, and input validation.

設定Settings: ttl leeway require_exp iss aud keep total per_user idle life cookie limit keys window key allow_missing min max extra

Application
app() -> GDWebApp
server() -> GDWebServer
Replies
text(body: String, status: int = 200) -> GDWebResponse
html(body: String, status: int = 200) -> GDWebResponse
json(data: Variant, status: int = 200) -> GDWebResponse, Err
レスポンスとErrを返します。JSONへの変換に失敗した場合は、そのエラーを返します。
Return response, Err and preserve encoding failures for the caller.
bytes(body: PackedByteArray, type: String = "application/octet-stream", status: int = 200) -> GDWebResponse
stream(producer: Callable, length: int = -1, type: String = "application/octet-stream", status: int = 200) -> GDWebResponse
本文を少しずつ送信するレスポンスを作ります。本文を生成する関数には、GDWebWriterが一度だけ渡されます。この関数はPackedByteArrayを書き込み、終了時にvoidまたは値とErrを返します。length=-1は長さが未定の場合です。関数内でawaitを使えますが、長く待つ場合はリクエストのキャンセルも確認してください。HEADや本文を送らないステータスコードでは、この関数を呼びません。
Create a lazy response producer called once with a GDWebWriter. Write PackedByteArray chunks and return void or a value and Err when finished. length=-1 selects unknown-length framing. The producer may await and should observe request-context cancellation; HEAD and bodyless statuses do not invoke it.
redirect(to: String, status: int = 302, away: bool = false) -> GDWebResponse
guard(reply: GDWebResponse) -> GDWebResponse
not_found(msg: String = "Not Found") -> GDWebResponse
header(reply: GDWebResponse, name: String, value: Variant) -> GDWebResponse
add_header(reply: GDWebResponse, name: String, value: Variant) -> GDWebResponse
view(path: String, data: Dictionary = { }, status: int = 200, renderer: Callable = null) -> GDWebResponse, Err
レスポンスとErrを返します。ファイルの読み取り、テンプレートの解析、HTMLの生成、キャンセルによるエラーを確認できます。
Return response, Err and preserve file, parsing, rendering, and cancellation failures.
view_async(path: String, data: Dictionary = { }, status: int = 200, renderer: Callable = null) -> GDTask (await GDWebResponse, Err)
json_async(data: Variant, status: int = 200) -> GDTask (await GDWebResponse, Err)
error_status(error: Err) -> int
Middleware
jwt(key: Variant, opts: Dictionary = { }) -> GDWebMiddleware
jwt_sign(claims: Dictionary, key: Variant, opts: Dictionary = { }) -> String, Err
jwt_verify(token: String, key: Variant, opts: Dictionary = { }) -> Dictionary, Err
jwt_sign_async(claims: Dictionary, key: Variant, opts: Dictionary = { }) -> GDTask (await String, Err)
jwt_verify_async(token: String, key: Variant, opts: Dictionary = { }) -> GDTask (await Dictionary, Err)
csrf(opts: Dictionary = { }) -> GDWebMiddleware
sessions(opts: Dictionary = { }) -> GDWebSessionStore
rate(opts: Dictionary = { }) -> GDWebMiddleware
Validation
text_rule(opts: Dictionary = { }) -> Dictionary
int_rule(opts: Dictionary = { }) -> Dictionary
number_rule(opts: Dictionary = { }) -> Dictionary
bool_rule() -> Dictionary
list_rule(item: Dictionary = { }, opts: Dictionary = { }) -> Dictionary
object_rule(fields: Dictionary, opts: Dictionary = { }) -> Dictionary
optional(rule: Dictionary, fallback: Variant = null) -> Dictionary
one_of(values: Array) -> Dictionary
validate(value: Variant, rule: Dictionary) -> Variant, Err
validate_async(value: Variant, rule: Dictionary) -> GDTask (await Variant, Err)
json_body(rule: Dictionary, name: String = "body") -> GDWebMiddleware
query(rule: Dictionary, name: String = "query") -> GDWebMiddleware
params(rule: Dictionary, name: String = "params") -> GDWebMiddleware

GD.file

ファイルの読み書き、パスの操作、各種データ形式の読み取りを行います。ファイル全体を扱う場合も少しずつ読み書きする場合も、呼び出した処理だけが完了を待ちます。_async付きの関数はGDTaskを返します。

Whole-file operations and streaming file I/O suspend only their caller. This entry also provides path operations and file-format readers; *_async returns a GDTask for concurrent starts.

File I/O
open(path: String, mode: String = "read") -> GDFileStream, Err
open_async(path: String, mode: String = "read") -> GDTask (await GDFileStream, Err)
read_text(path: String) -> String, Err
read_bytes(path: String, offset: int = 0, max: int = 0) -> PackedByteArray, Err
write_text(path: String, body: String) -> Variant, Err
replace_text(path: String, old: Variant, body: String) -> Variant, Err
write_bytes(path: String, body: PackedByteArray) -> Variant, Err
append_bytes(path: String, body: PackedByteArray) -> Variant, Err
append_text(path: String, body: String) -> Variant, Err
exists(path: String) -> bool
remove(path: String) -> Variant, Err
size_of(path: String) -> int, Err
copy(src: String, dst: String) -> Variant, Err
rename(src: String, dst: String) -> Variant, Err
list_dir(path: String) -> Array, Err
make_dir(path: String) -> Variant, Err
ensure_dir(path: String) -> Variant, Err
walk(path: String, want_dirs: bool = false, hidden: bool = false) -> Array, Err
glob(path: String, pattern: String, hidden: bool = false) -> Array, Err
remove_all(path: String) -> Variant, Err
can_read(path: String) -> bool
read_text_async(path: String) -> GDTask (await String, Err)
read_bytes_async(path: String, offset: int = 0, max: int = 0) -> GDTask (await PackedByteArray, Err)
write_text_async(path: String, body: String) -> GDTask (await Variant, Err)
write_bytes_async(path: String, body: PackedByteArray) -> GDTask (await Variant, Err)
append_text_async(path: String, body: String) -> GDTask (await Variant, Err)
append_bytes_async(path: String, body: PackedByteArray) -> GDTask (await Variant, Err)
copy_async(src: String, dst: String) -> GDTask (await Variant, Err)
replace_text_async(path: String, old: Variant, body: String) -> GDTask (await Variant, Err)
exists_async(path: String) -> GDTask (await bool)
remove_async(path: String) -> GDTask (await Variant, Err)
size_of_async(path: String) -> GDTask (await int, Err)
rename_async(src: String, dst: String) -> GDTask (await Variant, Err)
list_dir_async(path: String) -> GDTask (await Array, Err)
make_dir_async(path: String) -> GDTask (await Variant, Err)
ensure_dir_async(path: String) -> GDTask (await Variant, Err)
walk_async(path: String, want_dirs: bool = false, hidden: bool = false) -> GDTask (await Array, Err)
glob_async(path: String, pattern: String, hidden: bool = false) -> GDTask (await Array, Err)
remove_all_async(path: String) -> GDTask (await Variant, Err)
can_read_async(path: String) -> GDTask (await bool)
Paths
parse_path(path: String) -> Dictionary
format_path(parts: Dictionary) -> String
join(parts: PackedStringArray) -> String
dirname(path: String) -> String
basename(path: String, suffix: String = "") -> String
extname(path: String) -> String
is_absolute(path: String) -> bool
normalize(path: String) -> String
relative(from: String, to: String) -> String
under(dir: String, name: String) -> String
File formats
create_tar(root: String) -> PackedByteArray, Err
extract_tar(data: PackedByteArray, root: String) -> int, Err
read_csv(path: String, sep: String = ",") -> Array, Err
read_ini(path: String) -> Dictionary, Err
read_toml(path: String) -> Dictionary, Err
read_yaml(path: String) -> Variant, Err
read_jsonc(path: String) -> Variant, Err
read_jsonl(path: String) -> Array, Err
read_front_matter(path: String) -> Dictionary, Err
read_xml(path: String) -> Dictionary, Err
read_env(path: String = ".env") -> Dictionary, Err
read_tar(path: String) -> Array, Err
read_csv_async(path: String, sep: String = ",") -> GDTask (await Array, Err)
read_ini_async(path: String) -> GDTask (await Dictionary, Err)
read_toml_async(path: String) -> GDTask (await Dictionary, Err)
read_yaml_async(path: String) -> GDTask (await Variant, Err)
read_jsonc_async(path: String) -> GDTask (await Variant, Err)
read_jsonl_async(path: String) -> GDTask (await Array, Err)
read_front_matter_async(path: String) -> GDTask (await Dictionary, Err)
read_xml_async(path: String) -> GDTask (await Dictionary, Err)
read_env_async(path: String = ".env") -> GDTask (await Dictionary, Err)
read_tar_async(path: String) -> GDTask (await Array, Err)
create_tar_async(root: String) -> GDTask (await PackedByteArray, Err)
extract_tar_async(data: PackedByteArray, root: String) -> GDTask (await int, Err)

GD.collection

配列や辞書の変換、ヒープ、キュー、キャッシュを扱います。時間のかかる処理は別スレッド、またはほかの処理と交代しながら進めます。Callableを使う操作も、SceneTreeのフレームを待たずにほかのタスクへ実行を譲ります。

Reshape Arrays and Dictionaries and create heaps, queues, and caches. Awaitable operations use CPU workers or the runtime ready queue; callable work cooperates with other tasks without requiring SceneTree frames.

Methods
group_by(items: Array, key: Callable) -> Dictionary
map_values(src: Dictionary, fn: Callable) -> Dictionary
filter_keys(src: Dictionary, pred: Callable) -> Dictionary
partition(items: Array, pred: Callable) -> Array
chunk(items: Array, size: int) -> Array
unique_by(items: Array, key: Callable) -> Array
unique(items: Array) -> Array
sort_by(items: Array, pick: Callable) -> Array
sort_key(items: Array, key: String) -> Array
zip(a: Array, b: Array) -> Array
sum_of(items: Array, pick: Callable) -> float
max_by(items: Array, pick: Callable) -> Variant
min_by(items: Array, pick: Callable) -> Variant
index_by(items: Array, key: Callable) -> Dictionary
deep_merge(base: Dictionary, over: Dictionary) -> Dictionary
binary_heap(pick: Callable = null) -> GDBinaryHeap
priority_queue() -> GDPriorityQueue
lru_cache(limit: int = 128, ttl_ms: int = 0) -> GDLRUCache
memo(fn: Callable, limit: int = 128) -> GDMemoizedCallable
group_by_async(items: Array, key: Callable) -> GDTask (await Dictionary)
map_values_async(src: Dictionary, fn: Callable) -> GDTask (await Dictionary)
filter_keys_async(src: Dictionary, pred: Callable) -> GDTask (await Dictionary)
partition_async(items: Array, pred: Callable) -> GDTask (await Array)
unique_by_async(items: Array, key: Callable) -> GDTask (await Array)
sort_by_async(items: Array, pick: Callable) -> GDTask (await Array)
sum_of_async(items: Array, pick: Callable) -> GDTask (await float)
max_by_async(items: Array, pick: Callable) -> GDTask (await Variant)
min_by_async(items: Array, pick: Callable) -> GDTask (await Variant)
index_by_async(items: Array, key: Callable) -> GDTask (await Dictionary)
chunk_async(items: Array, size: int) -> GDTask (await Array)
unique_async(items: Array) -> GDTask (await Array)
sort_key_async(items: Array, key: String) -> GDTask (await Array)
zip_async(a: Array, b: Array) -> GDTask (await Array)
deep_merge_async(base: Dictionary, over: Dictionary) -> GDTask (await Dictionary)

GD.data

バイト列、データ形式の変換、ハッシュ、鍵の生成を扱います。CSV・INI・TOML・YAML・JSON・XMLなどをメモリ上で変換できます。不正な入力や設定はエラーとして返します。

Data conversion for bytes, binary codecs, hashes, key derivation, and in-memory CSV, INI, TOML, YAML, JSON, XML, and related formats. Invalid input and settings return failures.

Hash
gzip_writer(writer: RefCounted, level: int = -1) -> GDGzipWriter, Err
バイト列の出力先に書き込むGDGzipWriterを作ります。圧縮は別スレッドで行い、出力先が受け取れる量に合わせて待ちます。levelは-2(Huffmanのみ)、-1(既定値)、0〜9を指定できます。closeはgzipデータを完成させますが、出力先は閉じません。resetで同じ圧縮レベルのまま再利用できます。
Create a GDGzipWriter over a byte Writer. Compression runs on CPU workers and preserves downstream backpressure. Levels: -2 Huffman only, -1 default, 0..9. Close finishes the gzip member but leaves the destination open; reset reuses the compressor at the same level.
sha224(msg: PackedByteArray) -> PackedByteArray
sha256(msg: PackedByteArray) -> PackedByteArray
sha384(msg: PackedByteArray) -> PackedByteArray
sha512(msg: PackedByteArray) -> PackedByteArray
sha3_224(msg: PackedByteArray) -> PackedByteArray
sha3_256(msg: PackedByteArray) -> PackedByteArray
sha3_384(msg: PackedByteArray) -> PackedByteArray
sha3_512(msg: PackedByteArray) -> PackedByteArray
sha1(msg: PackedByteArray) -> PackedByteArray
hmac(hash: String, key: PackedByteArray, msg: PackedByteArray) -> PackedByteArray, Err
hmac_sha256(key: PackedByteArray, msg: PackedByteArray) -> PackedByteArray
equal_ct(a: PackedByteArray, b: PackedByteArray) -> bool
pbkdf2_sha256(password: PackedByteArray, salt: PackedByteArray, rounds: int) -> PackedByteArray, Err
生成した32バイトの鍵とErrを返します。反復回数が1以下の場合は、1回として計算します。
Return a 32-byte derived key and Err. Iteration counts of one or less perform one iteration.
pbkdf2(hash: String, password: PackedByteArray, salt: PackedByteArray, rounds: int, size: int) -> PackedByteArray, Err
hkdf(hash: String, secret: PackedByteArray, salt: PackedByteArray, info: PackedByteArray, size: int) -> PackedByteArray, Err
hkdf_extract(hash: String, secret: PackedByteArray, salt: PackedByteArray) -> PackedByteArray, Err
hkdf_expand(hash: String, key: PackedByteArray, info: PackedByteArray, size: int) -> PackedByteArray, Err
pbkdf2_sha256_async(password: PackedByteArray, salt: PackedByteArray, rounds: int) -> GDTask (await PackedByteArray, Err)
pbkdf2_async(hash: String, password: PackedByteArray, salt: PackedByteArray, rounds: int, size: int) -> GDTask (await PackedByteArray, Err)
hkdf_async(hash: String, secret: PackedByteArray, salt: PackedByteArray, info: PackedByteArray, size: int) -> GDTask (await PackedByteArray, Err)
hkdf_extract_async(hash: String, secret: PackedByteArray, salt: PackedByteArray) -> GDTask (await PackedByteArray, Err)
hkdf_expand_async(hash: String, key: PackedByteArray, info: PackedByteArray, size: int) -> GDTask (await PackedByteArray, Err)
sha224_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha256_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha384_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha512_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha3_224_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha3_256_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha3_384_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha3_512_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
sha1_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)
hmac_async(hash: String, key: PackedByteArray, msg: PackedByteArray) -> GDTask (await PackedByteArray, Err)
hmac_sha256_async(key: PackedByteArray, msg: PackedByteArray) -> GDTask (await PackedByteArray)
equal_ct_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await bool)
Serialization
csv(src: String, sep: String = ",") -> Array, Err
to_csv(rows: Array, sep: String = ",") -> String
csv_objects(src: String, sep: String = ",") -> Array, Err
to_csv_objects(items: Array, sep: String = ",") -> String
ini(src: String) -> Dictionary, Err
to_ini(data: Dictionary) -> String
toml(src: String) -> Dictionary, Err
to_toml(data: Dictionary, prefix: String = "") -> String, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
yaml(src: String) -> Variant, Err
to_yaml(data: Variant, depth: int = 0) -> String, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
jsonc(src: String) -> Variant, Err
strip_jsonc(src: String) -> String
jsonl(src: String) -> Array, Err
to_jsonl(items: Array) -> String, Err
jsonl_reader() -> GDJSONLReader
front_matter(src: String) -> Dictionary, Err
has_front_matter(src: String) -> bool
to_front_matter(attrs: Dictionary, body: String, kind: String = "yaml") -> String, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
xml(src: String) -> Dictionary, Err
to_xml(data: Dictionary, indent: int = 0) -> String, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
env(src: String) -> Dictionary, Err
環境変数の辞書とErrを返します。不正な名前や、閉じていない引用符はエラーになります。
Return an environment dictionary and Err. Invalid names and unterminated quotes return an Err.
to_env(data: Dictionary) -> String, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
tar(entries: Array) -> PackedByteArray, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
untar(data: PackedByteArray) -> Array, Err
json_encode(value: Variant, opts: Dictionary = { }) -> PackedByteArray, Err
json_decode(data: PackedByteArray) -> Variant, Err
msgpack(value: Variant) -> PackedByteArray, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
unmsgpack(data: PackedByteArray) -> Variant, Err
MessagePackのデータを読み取ります。不正なUTF-8やNULを含む文字列はPackedByteArrayで保持し、先頭のBOMも残します。
Decode MessagePack without losing text bytes. Non-UTF-8 or NUL-containing text remains PackedByteArray; leading BOM is preserved.
cbor(value: Variant) -> PackedByteArray, Err
変換した値とErrを返します。変換先の形式で表せない値がある場合は、その値を省略せずにエラーを返します。
Return the encoded value and Err. Inputs that cannot be represented produce an Err instead of omitted entries or an empty success value.
uncbor(data: PackedByteArray) -> Variant, Err
CBORのデータを読み取ります。不正なUTF-8の文字列はエラーになります。NULを含む正しい文字列は、切り捨てずにPackedByteArrayで保持します。
Decode CBOR and report malformed UTF-8 text as Err. Valid text containing NUL remains PackedByteArray without truncation.
json_encode_async(value: Variant, opts: Dictionary = { }) -> GDTask (await PackedByteArray, Err)
json_decode_async(data: PackedByteArray) -> GDTask (await Variant, Err)
msgpack_async(value: Variant) -> GDTask (await PackedByteArray, Err)
unmsgpack_async(data: PackedByteArray) -> GDTask (await Variant, Err)
cbor_async(value: Variant) -> GDTask (await PackedByteArray, Err)
uncbor_async(data: PackedByteArray) -> GDTask (await Variant, Err)
csv_async(src: String, sep: String = ",") -> GDTask (await Array, Err)
to_csv_async(rows: Array, sep: String = ",") -> GDTask (await String)
csv_objects_async(src: String, sep: String = ",") -> GDTask (await Array, Err)
to_csv_objects_async(items: Array, sep: String = ",") -> GDTask (await String)
ini_async(src: String) -> GDTask (await Dictionary, Err)
to_ini_async(data: Dictionary) -> GDTask (await String)
toml_async(src: String) -> GDTask (await Dictionary, Err)
to_toml_async(data: Dictionary, prefix: String = "") -> GDTask (await String, Err)
yaml_async(src: String) -> GDTask (await Variant, Err)
to_yaml_async(data: Variant, depth: int = 0) -> GDTask (await String, Err)
jsonc_async(src: String) -> GDTask (await Variant, Err)
strip_jsonc_async(src: String) -> GDTask (await String)
jsonl_async(src: String) -> GDTask (await Array, Err)
to_jsonl_async(items: Array) -> GDTask (await String, Err)
front_matter_async(src: String) -> GDTask (await Dictionary, Err)
to_front_matter_async(attrs: Dictionary, body: String, kind: String = "yaml") -> GDTask (await String, Err)
xml_async(src: String) -> GDTask (await Dictionary, Err)
to_xml_async(data: Dictionary, indent: int = 0) -> GDTask (await String, Err)
env_async(src: String) -> GDTask (await Dictionary, Err)
to_env_async(data: Dictionary) -> GDTask (await String, Err)
tar_async(entries: Array) -> GDTask (await PackedByteArray, Err)
untar_async(data: PackedByteArray) -> GDTask (await Array, Err)
Codec
hex_encode(data: PackedByteArray) -> String
hex_decode(text: String) -> PackedByteArray, Err
base64_encode(data: PackedByteArray) -> String
base64_decode(text: String, raw: bool = false) -> PackedByteArray, Err
Base64の文字列をバイト列に戻します。既定では末尾のパディング(=)付きとして扱い、raw=trueを指定するとパディングなしとして扱います。失敗時も、変換できたバイト列は返します。
Decode with standard padding by default; raw=true selects unpadded input. Return partial bytes with Err. Base32 uses uppercase letters.
base64url_encode(data: PackedByteArray) -> String
base64url_decode(text: String, raw: bool = true) -> PackedByteArray, Err
URL用のBase64文字列をバイト列に戻します。既定はパディングなしのraw=trueです。パディング付きの入力はraw=falseを指定します。暗号署名の解析では、正しい表記かどうかを別途検査します。
Decode the URL-safe alphabet; raw=true is the default. Set raw=false for padded input. Identity-sensitive signature parsing applies separate canonical checks.
base32_encode(data: PackedByteArray) -> String
base32_decode(text: String, raw: bool = false) -> PackedByteArray, Err
Base32の文字列をバイト列に戻します。文字は大文字を使います。既定では末尾のパディング(=)付きとして扱い、raw=trueを指定するとパディングなしとして扱います。失敗時も、変換できたバイト列は返します。
Decode with standard padding by default; raw=true selects unpadded input. Return partial bytes with Err. Base32 uses uppercase letters.
varint_encode(n: int) -> PackedByteArray
varint_decode(data: PackedByteArray, at: int = 0) -> Dictionary, Err
hex_encode_async(data: PackedByteArray) -> GDTask (await String)
hex_decode_async(text: String) -> GDTask (await PackedByteArray, Err)
base64_encode_async(data: PackedByteArray) -> GDTask (await String)
base64_decode_async(text: String, raw: bool = false) -> GDTask (await PackedByteArray, Err)
base64url_encode_async(data: PackedByteArray) -> GDTask (await String)
base64url_decode_async(text: String, raw: bool = true) -> GDTask (await PackedByteArray, Err)
base32_encode_async(data: PackedByteArray) -> GDTask (await String)
base32_decode_async(text: String, raw: bool = false) -> GDTask (await PackedByteArray, Err)
Bytes
concat(parts: Array) -> PackedByteArray
equals(a: PackedByteArray, b: PackedByteArray) -> bool
includes(hay: PackedByteArray, needle: PackedByteArray) -> bool
index_of(hay: PackedByteArray, needle: PackedByteArray, from: int = 0) -> int
last_index_of(hay: PackedByteArray, needle: PackedByteArray) -> int
starts_with(hay: PackedByteArray, prefix: PackedByteArray) -> bool
ends_with(hay: PackedByteArray, suffix: PackedByteArray) -> bool
repeat(src: PackedByteArray, times: int) -> PackedByteArray
fit(src: PackedByteArray, size: int) -> PackedByteArray
split(src: PackedByteArray, sep: PackedByteArray) -> Array
xor_bytes(a: PackedByteArray, b: PackedByteArray) -> PackedByteArray
concat_async(parts: Array) -> GDTask (await PackedByteArray)
equals_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await bool)
includes_async(hay: PackedByteArray, needle: PackedByteArray) -> GDTask (await bool)
index_of_async(hay: PackedByteArray, needle: PackedByteArray, from: int = 0) -> GDTask (await int)
last_index_of_async(hay: PackedByteArray, needle: PackedByteArray) -> GDTask (await int)
starts_with_async(hay: PackedByteArray, prefix: PackedByteArray) -> GDTask (await bool)
ends_with_async(hay: PackedByteArray, suffix: PackedByteArray) -> GDTask (await bool)
repeat_async(src: PackedByteArray, times: int) -> GDTask (await PackedByteArray)
fit_async(src: PackedByteArray, size: int) -> GDTask (await PackedByteArray)
split_async(src: PackedByteArray, sep: PackedByteArray) -> GDTask (await Array)
xor_bytes_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await PackedByteArray)

GD.id

UUIDと、時刻順に並べられるULIDを生成・検査します。ULID時刻の-1は現在時刻を選び、その他の48ビット範囲外は空文字を返します。範囲外の符号化文字列は拒否します。

Entry for generating and checking UUIDs and time-ordered ULIDs. Timestamp -1 selects the current time; other values outside the 48-bit range return an empty string. Encoded overflow is rejected.

Methods
ulid(ms: int = -1) -> String
is_ulid(text: String) -> bool
ulid_time(text: String) -> int, Err
uuid() -> String
uuid_v5(space: String, name: String) -> String, Err
uuid_v5_async(space: String, name: String) -> GDTask (await String, Err)
is_uuid(text: String) -> bool
uuid_bytes(text: String) -> PackedByteArray, Err
uuid_version(text: String) -> int
nil_uuid() -> String
dns_namespace() -> String
url_namespace() -> String
oid_namespace() -> String

GD.text

文字列の整形と比較を行います。

Entry for formatting and comparing text.

Methods
closest(word: String, options: PackedStringArray) -> String
ellipsis(text: String, width: int) -> String
size_of(bytes: int) -> String
duration(ms: float) -> String
distance(a: String, b: String) -> int
snake(text: String) -> String
camel(text: String) -> String
title(text: String) -> String
table(rows: Array, gap: int = 2) -> String
distance_async(a: String, b: String) -> GDTask (await int)
closest_async(word: String, options: PackedStringArray) -> GDTask (await String)
ellipsis_async(text: String, width: int) -> GDTask (await String)
snake_async(text: String) -> GDTask (await String)
camel_async(text: String) -> GDTask (await String)
title_async(text: String) -> GDTask (await String)
table_async(rows: Array, gap: int = 2) -> GDTask (await String)

GD.html

HTMLの文字参照、タグ、テンプレートを扱います。テンプレートへ埋め込む値は、本文、属性、URL、スタイル、スクリプトのどこに使うかに応じてエスケープします。

Entry for HTML entities, tags, and templates with context-sensitive escaping for text, attributes, URLs, styles, and scripts.

Methods
fill(tpl: String, data: Dictionary, partials: Dictionary = { }) -> String, Err
生成した文字列とErrを返します。不正なテンプレートはエラーになります。
Return rendered text, Err. Invalid templates do not silently become empty text.
template(tpl: String, partials: Dictionary = { }) -> GDHTMLTemplate, Err
attr(value: String) -> String
tag(name: String, body: String, attrs: Dictionary = { }) -> String
escape(text: String) -> String
unescape(text: String) -> String
escape_async(text: String) -> GDTask (await String)
unescape_async(text: String) -> GDTask (await String)
attr_async(value: String) -> GDTask (await String)
tag_async(name: String, body: String, attrs: Dictionary = { }) -> GDTask (await String)
fill_async(tpl: String, data: Dictionary, partials: Dictionary = { }) -> GDTask (await String, Err)

GD.math

数学関数、IEEE 754の特殊な値、浮動小数点数とビット列の変換を扱います。

Entry for standard mathematical functions, IEEE 754 special values, and bit conversions.

Properties

bits: GD.math.bits
64ビット整数のビット数の計算、回転、反転、桁上がり付きの演算を行います。
Integer math entry for uint64 bit counts, rotations, reversals, and operations with carry.
e: float
pi: float
phi: float
sqrt2: float
sqrt_e: float
sqrt_pi: float
sqrt_phi: float
ln2: float
log2_e: float
ln10: float
log10_e: float
max_float64: float
smallest_nonzero_float64: float
Methods
abs(x: float) -> float
acos(x: float) -> float
acosh(x: float) -> float
asin(x: float) -> float
asinh(x: float) -> float
atan(x: float) -> float
atanh(x: float) -> float
cbrt(x: float) -> float
ceil(x: float) -> float
cos(x: float) -> float
cosh(x: float) -> float
erf(x: float) -> float
erfc(x: float) -> float
erfinv(x: float) -> float
erfcinv(x: float) -> float
exp(x: float) -> float
exp2(x: float) -> float
expm1(x: float) -> float
floor(x: float) -> float
gamma(x: float) -> float
ilogb(x: float) -> int
j0(x: float) -> float
j1(x: float) -> float
log(x: float) -> float
log1p(x: float) -> float
log2(x: float) -> float
log10(x: float) -> float
logb(x: float) -> float
round(x: float) -> float
round_to_even(x: float) -> float
signbit(x: float) -> bool
sin(x: float) -> float
sinh(x: float) -> float
sqrt(x: float) -> float
tan(x: float) -> float
tanh(x: float) -> float
trunc(x: float) -> float
y0(x: float) -> float
y1(x: float) -> float
float64_bits(x: float) -> int
float64_from_bits(x: int) -> float
float32_bits(x: float) -> int
float32_from_bits(x: int) -> float
nan() -> float
inf(sign: int) -> float
is_inf(x: float, sign: int = 0) -> bool
is_nan(x: float) -> bool
atan2(y: float, x: float) -> float
copysign(value: float, sign: float) -> float
dim(x: float, y: float) -> float
fma(x: float, y: float, z: float) -> float
hypot(x: float, y: float) -> float
ldexp(frac: float, exp: int) -> float
max(x: float, y: float) -> float
min(x: float, y: float) -> float
mod(x: float, y: float) -> float
nextafter(x: float, y: float) -> float
nextafter32(x: float, y: float) -> float
pow(x: float, y: float) -> float
pow10(n: int) -> float
remainder(x: float, y: float) -> float
frexp(x: float) -> Array
lgamma(x: float) -> Array
modf(x: float) -> Array
sincos(x: float) -> Array

GD.version

セマンティックバージョンを解析・比較し、指定したバージョン範囲に含まれるか調べます。

Entry for parsing, comparing, and range-matching Semantic Versions.

Methods
parse(raw: String) -> Dictionary, Err
is_canonical(raw: String) -> bool
compare(a: Dictionary, b: Dictionary) -> int
is_stable(v: Dictionary) -> bool
text(v: Dictionary) -> String
best(list: PackedStringArray, range: String = "*") -> Dictionary, Err
best_async(list: PackedStringArray, range: String = "*") -> GDTask (await Dictionary, Err)
satisfies(v: Dictionary, range: String) -> bool

GD.time

Unix時刻、ISO 8601、HTTPの日付を変換・計算します。parse_isoはRFC 3339形式を受け取ります。加算や差分が64ビット整数の範囲を超える場合は、最大値または最小値になります。

Entry for converting and computing Unix time, ISO 8601, and HTTP dates. parse_iso accepts RFC 3339, and add and diff clamp at the 64-bit integer ends.

Methods
now() -> int
to_parts(unix: int) -> Dictionary
from_parts(parts: Dictionary) -> int
to_iso(unix: int) -> String
to_http(unix: int) -> String
parse_iso(text: String) -> int, Err
add(unix: int, amount: int, unit: String = "second") -> int
diff(a: int, b: int, unit: String = "second") -> int
start_of_day(unix: int) -> int
weekday(unix: int) -> int
is_leap(year: int) -> bool
days_in_month(year: int, month: int) -> int
ago(unix: int, base: int = -1) -> String
format(unix: int, pattern: String) -> String

GD.cli

gdのバージョンや文書の表示、コマンドライン引数、環境変数、システム情報の取得に使います。アクセス権限の設定に従います。

Entry for gd's version and docs, flags, and allowed environment and system information.

Methods
version() -> String
docs_url() -> String
flags() -> GDCLIFlags
env(name: String, fallback: Variant = null) -> Variant
require_env(name: String) -> String, Err
cwd() -> String
platform() -> String
arch() -> String
stdin_tty() -> bool
stdout_tty() -> bool
stderr_tty() -> bool
paint(text: String, code: int) -> String
red(text: String) -> String
green(text: String) -> String
yellow(text: String) -> String
blue(text: String) -> String
gray(text: String) -> String
bold(text: String) -> String
run(path: String, args: PackedStringArray = [], opts: Dictionary = { }) -> Dictionary, Err
終了コードと取得済みの出力を返します。終了コードが0以外の場合はErrも返し、info.codeに終了コードを記録します。タイムアウトやキャンセルでも、結果のcodeとoutputは残ります。
Return exit code and captured output. A nonzero exit returns Err with info.code; timeout and cancellation also retain code and output in the value.
run_async(path: String, args: PackedStringArray = [], opts: Dictionary = { }) -> GDTask (await Dictionary, Err)

GD.test

期待した結果と実際の結果を比較する、テスト用の機能です。

Entry for small test helpers that collect asserts.

Methods
check() -> GDTestCheck

GD.database

SQLiteとPostgreSQLを共通のAPIで扱います。処理の完了を待つ間も、ほかのGDScriptは動き続けます。_async付きの関数はGDTaskを返し、あとからawaitで結果を受け取れます。

Database entry shared by SQLite and PostgreSQL. Synchronous-looking calls suspend only their GDScript; *_async returns a GDTask for composition.

Properties

sqlite: GD.database.sqlite
組み込みのSQLiteへ直接接続する、同期処理用のAPIです。
Entry for opening low-level synchronous connections to embedded SQLite databases.
postgres: GD.database.postgres
PostgreSQLの接続と、接続を再利用するプールを作ります。
Entry for creating PostgreSQL clients and connection pools.
redis: GD.database.redis
Redisの接続と、接続を再利用するプールを作ります。
Entry for creating Redis clients and connection pools.
Methods
client() -> GDDatabaseClient

GD.online

オンラインゲームのマッチング先を管理します。ゲームの同期とゲスト認証はgd-godotのOnlineとSecretで行います。

Manage matchmaking destinations for online games. Online and Secret in gd-godot handle game synchronization and guest authentication.

Methods
match(opts: Dictionary = { }) -> GDOnlineMatch, Err
マッチング用のエンドポイントを作ります。keyは部屋の告知に必要な共有鍵、redisは複数プロセスで共有する保存先です。
Create a matchmaking endpoint. key authenticates room announcements; redis shares the directory between processes.

GD.net.dial_tcp

TCPまたはTLSの接続です。読み取りと書き込みはそれぞれ受付順に進みます。タイムアウトを設定でき、close()を呼ぶと待機中の処理も終了します。

Concurrency-safe TCP or TLS byte stream with FIFO reads and writes, deadlines, Close wakeups, and addresses.

Methods
read(max: int = 65536) -> PackedByteArray, Err
read_async(max: int = 65536) -> GDTask (await PackedByteArray, Err)
write(data: PackedByteArray) -> int, Err
write_async(data: PackedByteArray) -> GDTask (await int, Err)
start_tls(host: String, opts: Dictionary = { }) -> GDTCPConn, Err
既存の平文TCP接続を同じ相手との検証済みTLS接続へ切り替えます。読み書きが待機中なら失敗します。成功時は返された接続を使います。
Upgrade an idle plaintext TCP connection to verified TLS on the same socket. Use the returned connection after success.
start_tls_async(host: String, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)
set_deadline(seconds: float) -> Err
set_read_deadline(seconds: float) -> Err
set_write_deadline(seconds: float) -> Err
local_addr() -> Dictionary
remote_addr() -> Dictionary
connection_state() -> Dictionary
TLS接続の状態をhandshake_complete、server_name、negotiated_protocol、versionで返します。接続処理中のデータを直接参照せず、確認できた状態を返します。versionは未確定なら0、TLS 1.2なら771、TLS 1.3なら772です。
Inspect published handshake_complete, server_name, negotiated_protocol, and numeric TLS version without accessing active worker state. Version is zero before negotiation; 771 and 772 denote TLS 1.2 and 1.3.
is_open() -> bool
close() -> void

GD.net.listen_udp

UDPのパケットを送受信します。パケットの区切りと送信元アドレスを保持します。待ち時間を制限でき、close()を呼ぶと待機中の処理も終了します。

UDP endpoint preserving packet boundaries and source addresses, with deadlines and Close wakeups.

Methods
read_from(max: int = 65536) -> Dictionary, Err
read_from_async(max: int = 65536) -> GDTask (await Dictionary, Err)
write_to(data: PackedByteArray, host: String, port: int) -> int, Err
write_to_async(data: PackedByteArray, host: String, port: int) -> GDTask (await int, Err)
set_deadline(seconds: float) -> Err
set_read_deadline(seconds: float) -> Err
set_write_deadline(seconds: float) -> Err
addr() -> Dictionary
is_open() -> bool
close() -> void

GD.mail.mime

MIMEメディアタイプ、encoded-word、quoted-printable、multipartの読書きを扱います。

Parse and format MIME media types, encoded words, quoted-printable bytes, and multipart bodies.

Methods
parse_media_type(text: String) -> Dictionary, Err
format_media_type(type: String, params: Dictionary) -> String, Err
encode_word(text: String, mode: String = "b") -> String, Err
decode_word(text: String) -> String, Err
decode_header(text: String) -> String, Err
quoted_printable_encode(data: PackedByteArray) -> PackedByteArray, Err
quoted_printable_decode(data: PackedByteArray) -> PackedByteArray, Err
quoted_printable_reader(source: Variant) -> Variant, Err
quoted_printable_writer(sink: Variant) -> Variant, Err
multipart_reader(data: PackedByteArray, boundary: String) -> Variant, Err
multipart_writer(boundary: String = "") -> Variant, Err
multipart_reader_stream(source: Variant, boundary: String) -> Variant, Err
multipart_writer_to(sink: Variant, boundary: String = "") -> Variant, Err

GD.mail.dial_smtp

SMTP接続を再利用し、挨拶、認証、宛先指定、DATA送信、接続終了を順に行います。

Reuse one SMTP session for greeting, authentication, recipients, DATA transfer, and shutdown.

Methods
hello(name: String = "localhost") -> Dictionary, Err
hello_async(name: String = "localhost") -> GDTask (await Dictionary, Err)
start_tls(opts: Dictionary = { }) -> Dictionary, Err
start_tls_async(opts: Dictionary = { }) -> GDTask (await Dictionary, Err)
auth(config: Dictionary) -> Dictionary, Err
auth_async(config: Dictionary) -> GDTask (await Dictionary, Err)
mail(from: String) -> Dictionary, Err
mail_async(from: String) -> GDTask (await Dictionary, Err)
rcpt(to: String) -> Dictionary, Err
rcpt_async(to: String) -> GDTask (await Dictionary, Err)
data() -> GDSMTPDataWriter, Err
data_async() -> GDTask (await GDSMTPDataWriter, Err)
reset() -> Dictionary, Err
reset_async() -> GDTask (await Dictionary, Err)
noop() -> Dictionary, Err
noop_async() -> GDTask (await Dictionary, Err)
verify(address: String) -> Dictionary, Err
verify_async(address: String) -> GDTask (await Dictionary, Err)
quit() -> Dictionary, Err
quit_async() -> GDTask (await Dictionary, Err)
close() -> void
extension(name: String) -> Dictionary
tls_state() -> Dictionary

GD.file.open

ファイルを少しずつ読み書きするオブジェクトです。同じファイルストリームへの操作は受付順に進み、別のストリームは並行して処理できます。使い終わったらclose()で閉じます。

Reader, Writer, and Closer for ordered incremental access to a regular file. Separate streams proceed concurrently.

Methods
read(max: int = 32768) -> PackedByteArray, Err
read_async(max: int = 32768) -> GDTask (await PackedByteArray, Err)
write(data: PackedByteArray) -> int, Err
write_async(data: PackedByteArray) -> GDTask (await int, Err)
seek(offset: int) -> Variant, Err
seek_async(offset: int) -> GDTask (await Variant, Err)
close() -> Variant, Err
close_async() -> GDTask (await Variant, Err)
is_open() -> bool

GD.math.bits

64ビット整数のビット数の計算、回転、反転、桁上がり付きの演算を行います。

Integer math entry for uint64 bit counts, rotations, reversals, and operations with carry.

Methods
len64(x: int) -> int
leading_zeros64(x: int) -> int
trailing_zeros64(x: int) -> int
ones_count64(x: int) -> int
rotate_left64(x: int, k: int) -> int
reverse64(x: int) -> int
reverse_bytes64(x: int) -> int
add64(x: int, y: int, carry: int) -> Array
sub64(x: int, y: int, borrow: int) -> Array
mul64(x: int, y: int) -> Array
接続先ごとのAPIAdvanced backends
戻り値の型Return types

Err

失敗の種類、説明、追加情報、原因、部分結果を持つ値です。Err.NOT_FOUNDなどは共有値で、直接返せます。独立した失敗はjoin()でまとめ、原因に同じ種類があるかはfind()で調べます。

A failure value with a category, message, details, causes, and partial result. Err.NOT_FOUND and related names are shared values. join() retains independent failures, and find() searches every cause.

Properties

msg: String
kind: Err
info: Dictionary
cause: Err
causes: Array
partial: Variant
Methods
not_found(msg: String = "") -> Err
permission_denied(msg: String = "") -> Err
already_exists(msg: String = "") -> Err
invalid_data(msg: String = "") -> Err
timed_out(msg: String = "") -> Err
interrupted(msg: String = "") -> Err
unsupported(msg: String = "") -> Err
unauthenticated(msg: String = "") -> Err
limited(msg: String = "") -> Err
from(reason: Variant, kind: Err = null) -> Err
join(errors: Array) -> Err
as_kind(kind: Err) -> Err
note(msg: String, info: Dictionary = { }) -> Err
with_partial(value: Variant) -> Err
find(target: Variant, where: Dictionary = { }) -> Err
text() -> String
name_of(kind: Err) -> String
names() -> PackedStringArray

Constants

ERROR: Err
NOT_FOUND: Err
PERMISSION_DENIED: Err
ALREADY_EXISTS: Err
INVALID_DATA: Err
TIMED_OUT: Err
INTERRUPTED: Err
UNSUPPORTED: Err
UNAUTHENTICATED: Err
LIMITED: Err

GDTestCheck

テストの実行件数と失敗を集計し、終了コードを返します。

Checker collecting assert counts and failures and producing the test exit code.

Properties

failures: int
count: int
Methods
eq(got: Variant, want: Variant, label: String = "") -> void
ne(got: Variant, other: Variant, label: String = "") -> void
ok(cond: bool, label: String = "") -> void
no(cond: bool, label: String = "") -> void
near(got: float, want: float, slack: float = 0.000000001, label: String = "") -> void
has(box: Variant, item: Variant, label: String = "") -> void
succeeds(error: Err, label: String = "") -> void
fails(error: Err, kind: Err = null, label: String = "") -> void
code() -> int
report() -> void

GDTask

開始した処理の結果を保持するオブジェクトです。ほかの処理を待った後でも、await、GD.async.all()、cancel()、finishedで結果を受け取れます。

Handle to a started operation. It keeps the result, so await, GD.async.all(), cancel() and finished still work after other waits.

Methods
is_done() -> bool
cancel() -> void

GDCLIFlags

コマンドラインのオプションを型に合わせて読み取り、オプション以外の引数も集めます。真偽値はtrue/falseや1/0、整数は0x・0o・0bで始まる表記も使えます。

Parser reading typed bool flags such as true/false and 1/0, integers with 0x, 0o, and 0b prefixes, and collecting positional arguments.

Methods
set_name(name: String) -> void
flag_bool(name: String, fallback: bool, help: String = "") -> void
flag_str(name: String, fallback: String, help: String = "") -> void
flag_int(name: String, fallback: int, help: String = "") -> void
parse(args: Array) -> Variant, Err
get_bool(name: String) -> bool
get_str(name: String) -> String
get_int(name: String) -> int
get_rest() -> PackedStringArray
usage() -> String

GDBodySource

ファイルやHTTPレスポンスの本文を少しずつ読み書きする型の共通の基底クラスです。通常はGDFileStream、GDWebWriter、GDGzipWriterを使います。

Public base for incrementally supplying file and HTTP response bodies. Users normally work with it as GDFileStream, GDWebWriter, or GDGzipWriter.

GDWebServer

HTTP通信を直接扱うサーバーです。HTTP/1のリクエストにはHTTP/1.1で応答し、TLSでHTTP/2を選んだ場合は、各リクエストを独立したストリームで処理します。

Low-level server using HTTP/1.1 responses for HTTP/1 requests and independent streams for TLS-negotiated HTTP/2 requests.

Methods
body_limit(bytes: int) -> void
header_limits(bytes: int, values: int) -> void
listen(port: int, host: String = "127.0.0.1") -> Variant, Err
port() -> int
stop() -> void
is_listening() -> bool
poll() -> PackedInt32Array
get_method(id: int) -> String
get_path(id: int) -> String
get_query(id: int) -> String
get_header(id: int, name: String) -> String
get_headers(id: int) -> Dictionary
read_body(id: int, bytes: int = 32768) -> Dictionary
respond(id: int, status: int, body: PackedByteArray, content_type: String = "text/plain; charset=utf-8") -> void
respond_with(id: int, status: int, headers: Dictionary, body: PackedByteArray) -> void
connection_count() -> int
dropped_headers() -> int

GDWebWriter

GD.web.streamに渡した関数が受け取る出力先です。write(data, offset=0, count=-1)は指定範囲のバイト列を送り、受け付けたバイト数を返します。write_text(text, offset=0, count=-1)は指定範囲の文字列をUTF-8に変換して送ります。count=-1は残りすべてです。送信先が受け取れない間は待ちます。flushは、それまでに書き込んだデータの送信完了を待ちます。切断はflushのエラーやリクエストのキャンセルで確認できます。

The byte destination passed to a GD.web.stream producer. write(data, offset=0, count=-1) sends a range and returns accepted bytes, waiting while the connection is backed up. write_text(text, offset=0, count=-1) sends a character range as UTF-8. count=-1 selects the remainder. flush waits until preceding writes are sent. Detect disconnects through flush errors and request-context cancellation.

Methods
write(data: PackedByteArray, offset: int = 0, count: int = -1) -> int, Err
write_async(data: PackedByteArray, offset: int = 0, count: int = -1) -> GDTask (await int, Err)
write_text(text: String, offset: int = 0, count: int = -1) -> int, Err
write_text_async(text: String, offset: int = 0, count: int = -1) -> GDTask (await int, Err)
flush() -> int, Err
flush_async() -> GDTask (await int, Err)

GDGzipWriter

データを少しずつgzip圧縮し、ファイルや接続、HTTPレスポンスへ出力します。writeは受け付けた入力バイト数を返し、flushは途中までのデータを出力し、closeは圧縮を完了します。操作は受付順に行い、エラーはresetまで残ります。呼び出した処理だけが完了を待ちます。GDTaskを受け取ってあとで待つ場合は_async付きの関数を使います。

Incremental gzip output to files, connections, or HTTP response Writers. write returns the accepted input-byte count; flush publishes buffered output; close completes the member; reset discards state and clears errors. Operations are ordered; failures remain sticky until reset. Methods suspend only the calling routine, with explicit _async variants for signals.

Properties

header: Dictionary
最初にwrite、flush、closeを呼ぶ前に設定するgzipヘッダー情報です。nameとcommentはNULを含まないLatin-1文字列、extraは最大65535バイト、mod_timeは0〜4294967295のUnix秒、osは1バイトの値(既定値255)です。resetを呼ぶと初期値に戻ります。
Configure metadata before the first write, flush, or close: name/comment are non-NUL Latin-1, extra is bytes within the 65535-byte wire width, mod_time is Unix seconds from 0 to 4294967295, and os is a byte defaulting to 255. Reset clears metadata.
Methods
set_header(header: Dictionary) -> void
write(data: PackedByteArray) -> int, Err
write_async(data: PackedByteArray) -> GDTask (await int, Err)
flush() -> Variant, Err
flush_async() -> GDTask (await Variant, Err)
close() -> Variant, Err
close_async() -> GDTask (await Variant, Err)
reset(writer: RefCounted) -> Variant, Err
reset_async(writer: RefCounted) -> GDTask (await Variant, Err)

GDWebRequest

リクエストを処理する関数が受け取るHTTPリクエストです。JSONの解析、キャンセルの管理、大きな本文を少しずつ保存する機能を持ちます。

The HTTP request received by a route handler, with strict JSON, a per-request context, and streaming of large bodies.

Properties

context: GDAsyncContext
method: String
path: String
ip: String
query: Dictionary
キーごとの先頭の値です。すべての値はquery_allから取得できます。解析エラーは、元のクエリ文字列をdecode_queryに渡して確認してください。
First value of each valid query key. Use query_all for duplicate values, or decode_query on the raw query to inspect errors.
query_all: Dictionary
キーごとのすべての値を、受信した順のArrayで返します。文字列に変換できないキーと値はPackedByteArrayで保持します。
All values for each valid query key in arrival order. Binary keys and values remain PackedByteArray.
params: Dictionary
target: String
Methods
header(name: String) -> String
headers() -> Dictionary
read(bytes: int = 32768) -> PackedByteArray, Err
bytes() -> PackedByteArray, Err
body_size() -> int
limit(bytes: int) -> Err
save(path: String) -> int, Err
text() -> String, Err
json() -> Variant, Err
read_async(bytes: int = 32768) -> GDTask (await PackedByteArray, Err)
bytes_async() -> GDTask (await PackedByteArray, Err)
save_async(path: String) -> GDTask (await int, Err)
text_async() -> GDTask (await String, Err)
json_async() -> GDTask (await Variant, Err)
keep(name: String, value: Variant) -> void
kept(name: String, fallback: Variant = null) -> Variant
valid(name: String, fallback: Variant = null) -> Variant

GDWebMiddleware

リクエスト処理の前に入力を検査・加工するミドルウェアの基底クラスです。自作する場合は関数か、handle(req)を持つオブジェクトを渡します。

Base of middleware that inspects and reshapes a request before the handler. To write your own, pass a function or an object with handle(req).

GDWebApp

URLごとの処理、静的ファイル、ミドルウェアを登録して、リクエストを待ち受けるWebアプリケーションです。

Web application that listens with routes, static files, and middleware together.

設定Settings: jobs job_timeout header_timeout body_timeout header_bytes header_values

Methods
route(method: String, pattern: String, handler: Callable, middleware: Array = []) -> void
pre(middleware: Variant) -> void
use(middleware: Variant) -> void
after(handler: Callable) -> void
on_error(handler: Callable) -> void
show_errors(on: bool) -> void
body_limit(bytes: int) -> void
limits(opts: Dictionary) -> void
dropped_headers() -> int
group(prefix: String, middleware: Array = []) -> GDWebRouteGroup
static(prefix: String, dir: String) -> void
fallback(handler: Callable) -> void
file_at(path: String) -> GDWebResponse, Err
file_at_async(path: String) -> GDTask (await GDWebResponse, Err)
listen(port: int, host: String = "127.0.0.1") -> Variant, Err
listen_tls(port: int, cert: String, key: String, host: String = "127.0.0.1", opts: Dictionary = { }) -> Variant, Err
PEM形式の証明書チェーンと暗号化されていない秘密鍵を使い、HTTPSの待ち受けを開始します。TLS 1.2/1.3に対応し、ALPNでHTTP/2またはHTTP/1.1を選びます。起動結果は値とErrで返します。optsのclient_authはnone/request/require/verify_if_given/require_and_verifyから選び、client_caにはクライアント証明書の検証に使うCAを指定します。
Start an HTTPS listener from a PEM certificate chain and an unencrypted private key, selecting HTTP/2 or HTTP/1.1 through ALPN. Supports TLS 1.2 and 1.3. The startup returns a value and Err. opts sets client_auth to none, request, require, verify_if_given, or require_and_verify; client_ca selects the client trust bundle.
listen_tls_async(port: int, cert: String, key: String, host: String = "127.0.0.1", opts: Dictionary = { }) -> GDTask (await Variant, Err)
port() -> int
shutdown(context: GDAsyncContext) -> Variant, Err
shutdown_async(context: GDAsyncContext) -> GDTask (await Variant, Err)
stop() -> void
is_listening() -> bool
serve_error() -> Err
poll() -> void

GDHTTPResponse

受信したHTTPステータスコード、ヘッダー、本文を持つオブジェクトです。本文をJSONとして解析すると、値とErrを返します。

Response holding the received HTTP status, headers, and body, returning strict JSON as a value and Err.

Properties

status: int
headers: Dictionary
body: PackedByteArray
Methods
ok() -> bool
text() -> String
json() -> Variant, Err

GDOnlineMatch

ゲーム名ごとに部屋と身元確認サーバーの場所を記録し、参加先を返すエンドポイントです。ゲームの通信内容は中継しません。

Directory that records rooms and identity gateways per game and returns a destination. It does not relay game traffic.

Methods
handle(req: GDWebRequest) -> GDWebResponse, Err
Webアプリケーションのハンドラーとしてマッチング要求に答えます。返事は値とErrの二値です。
Answer a matchmaking request as a web application handler, returning a value and Err.
listen(port: int, host: String = "127.0.0.1") -> Variant, Err
マッチング用のHTTP待ち受けを開始します。返り値は値とErrの二値です。
Start the matchmaking HTTP listener, returning a value and Err.
port() -> int
listenで開いたポートを返します。待ち受け前は0です。
Return the listening port, or zero before listen.
stop() -> void
待ち受けを停止します。
Stop the listener.

GDPostgresClient

1つのPostgreSQL接続を操作します。通常の関数は呼び出した処理だけを待たせ、_async付きの関数はGDTaskを返します。

Client for one PostgreSQL connection. Regular methods suspend only their caller; *_async returns a GDTask for concurrent composition.

設定Settings: user database password connect_timeout timeout auth allow_cleartext_password tls ca

Methods
open(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }) -> Variant, Err
query(sql: String, args: Array = []) -> Dictionary, Err
query_row(sql: String, args: Array = [], max_bytes: int = 0) -> Dictionary, Err
query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Err
query_values(sql: String, args: Array = []) -> Dictionary, Err
query_flat(sql: String, args: Array = []) -> Dictionary, Err
query_many(sql: String, rows: Array) -> Array, Err
fetch_many(sql: String, rows: Array) -> Array, Err
fetch_values_many(sql: String, rows: Array) -> Array, Err
fetch_flat_many(sql: String, rows: Array) -> Array, Err
exec_many(sql: String, rows: Array) -> int, Err
open_async(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }) -> GDTask (await Variant, Err)
query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_row_async(sql: String, args: Array = [], max_bytes: int = 0) -> GDTask (await Dictionary, Err)
query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)
query_values_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_flat_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_values_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_flat_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
exec_many_async(sql: String, rows: Array) -> GDTask (await int, Err)
is_open() -> bool
close() -> void
check(sql: String) -> Variant, Err
check_async(sql: String) -> GDTask (await Variant, Err)
in_flight() -> int
cached_stmts() -> int

GDPostgresPool

PostgreSQL接続を必要に応じて上限まで作り、複数の処理で再利用します。空き接続の待機と、接続状況の確認ができます。

Concurrency-safe pool opening PostgreSQL connections on demand up to a maximum, with a wait queue and connection statistics.

Methods
open(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }, size: int = 0) -> Variant, Err
query(sql: String, args: Array = []) -> Dictionary, Err
query_row(sql: String, args: Array = [], max_bytes: int = 0) -> Dictionary, Err
query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Err
query_values(sql: String, args: Array = []) -> Dictionary, Err
query_flat(sql: String, args: Array = []) -> Dictionary, Err
query_many(sql: String, rows: Array) -> Array, Err
fetch_many(sql: String, rows: Array) -> Array, Err
fetch_values_many(sql: String, rows: Array) -> Array, Err
fetch_flat_many(sql: String, rows: Array) -> Array, Err
exec_many(sql: String, rows: Array) -> int, Err
open_async(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }, size: int = 0) -> GDTask (await Variant, Err)
query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_row_async(sql: String, args: Array = [], max_bytes: int = 0) -> GDTask (await Dictionary, Err)
query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)
query_values_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_flat_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_values_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
fetch_flat_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)
exec_many_async(sql: String, rows: Array) -> GDTask (await int, Err)
close() -> void
size() -> int
in_flight() -> int
stats() -> Dictionary

GDDatabaseClient

SQLiteとPostgreSQLに共通する、SQLの実行、1行ずつの読み取り、先頭行の取得、接続状況の確認に使います。

Client providing shared SQLite and PostgreSQL queries, streaming Rows, first-row lookup, and connection statistics.

設定Settings: driver path host port max_rows max_bytes

Methods
open(opts: Dictionary) -> Variant, Err
open_async(opts: Dictionary) -> GDTask (await Variant, Err)
query(sql: String, args: Array = []) -> Dictionary, Err
query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_row(sql: String, args: Array = []) -> Dictionary, Err
query_row_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Err
query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)
transaction(action: Callable) -> Variant, Err
transaction_async(action: Callable) -> GDTask (await Variant, Err)
serialize(action: Callable) -> Variant, Err
serialize_async(action: Callable) -> GDTask (await Variant, Err)
migrate(statements: Array) -> int, Err
migrate_async(statements: Array) -> GDTask (await int, Err)
stats() -> Dictionary
close() -> void
is_open() -> bool

GDDatabaseTx

トランザクションが終わるまで専用の接続を使うデータベースクライアントです。

Dedicated client holding one physical connection until the transaction ends.

Methods
query(sql: String, args: Array = []) -> Dictionary, Err
query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_row(sql: String, args: Array = []) -> Dictionary, Err
query_row_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)
query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Err
query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)
is_active() -> bool

GDRedisClient

1つのRedis接続を操作します。通常の関数は呼び出した処理だけを待たせ、_async付きの関数はGDTaskを返します。

Client for one Redis connection. Regular methods suspend only their caller; *_async returns a GDTask for concurrent composition.

設定Settings: password timeout tls ca

Methods
open(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }) -> Variant, Err
query(cmd: String, args: Array = []) -> Variant, Err
コマンドの結果とErrを返します。値がなければNOT_FOUNDで、info.codeはnilです。配列内のnullはそのまま残し、バイナリデータはPackedByteArrayで保持します。
Return a command value and Err. A missing value is NOT_FOUND with info.code=nil; null elements within array replies remain null. Binary bulk values remain PackedByteArray.
pipeline(cmds: Array) -> Array, Err
コマンドが1件の場合も、コマンド順のArrayを返します。失敗時も受信済みの結果は残し、受信できなかった位置にErrを入れます。
Always return an Array in command order, including one-command pipelines. Failure retains known replies and marks unknown replies with Err.
transaction(cmds: Array) -> Array, Err
各コマンドの結果とErrを返します。WATCHによる中断はINTERRUPTEDで、info.codeはtx_failedです。あるコマンドが失敗しても、ほかのコマンドの結果は残ります。
Return command results and Err. WATCH abort is INTERRUPTED with info.code=tx_failed; command failures retain sibling results.
subscribe(channels: PackedStringArray) -> Variant, Err
open_async(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }) -> GDTask (await Variant, Err)
query_async(cmd: String, args: Array = []) -> GDTask (await Variant, Err)
pipeline_async(cmds: Array) -> GDTask (await Array, Err)
transaction_async(cmds: Array) -> GDTask (await Array, Err)
subscribe_async(channels: PackedStringArray) -> GDTask (await Variant, Err)
is_open() -> bool
is_subscribed() -> bool
in_flight() -> int
close() -> void

GDRedisPool

複数のRedis接続へ処理を割り振り、同時に利用できるようにします。

Concurrency-safe pool distributing work across several Redis connections.

Methods
open(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }, size: int = 0) -> Variant, Err
query(cmd: String, args: Array = []) -> Variant, Err
open_async(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }, size: int = 0) -> GDTask (await Variant, Err)
query_async(cmd: String, args: Array = []) -> GDTask (await Variant, Err)
close() -> void
size() -> int
in_flight() -> int

GDSQLiteStatement

一度prepareで解析し、値を変えて繰り返し実行できるSQLiteのSQL文です。

A SQLite statement prepared once and reused.

Methods
run(params: Array = []) -> Dictionary, Err
run_many(rows: Array) -> Dictionary, Err
one(params: Array = []) -> Variant, Err
先頭行とErrを返します。行がなければErr.NOT_FOUNDを返します。
Return the first row and Err. An empty result returns Err.NOT_FOUND.
all(params: Array = []) -> Array, Err
close() -> void
is_valid() -> bool

GDLRUCache

最近使った値を、件数と有効期限を指定して保存するキャッシュです。必要な値がなければ作成して返せます。

Cache holding recently used values under a count and expiry limit, creating a value when missing.

Methods
setup(limit: int, ttl_ms: int = 0) -> void
put(key: Variant, value: Variant) -> void
take(key: Variant, fallback: Variant = null) -> Variant
fetch(key: Variant, make: Callable) -> Variant
has(key: Variant) -> bool
erase(key: Variant) -> void
clear() -> void
size() -> int
limit() -> int
hit_count() -> int
miss_count() -> int
hit_rate() -> float

GDWebApp.file_at

GD.web.text、html、json、bytes、streamなどが返すHTTPレスポンスです。statusとbodyを変更でき、typeからContent-Typeを読めます。headersには追加ヘッダーとContent-Typeが入ります。ヘッダーの追加にはGD.web.headerを使います。

The HTTP response returned by GD.web.text, html, json, bytes, and stream. Its status and body can be changed, while type exposes Content-Type. The headers property includes extra fields and Content-Type; use GD.web.header to add a field.

Properties

status: int
body: Variant
headers: Dictionary
type: String
Methods
set_status(status: int) -> void
set_body(body: Variant) -> void
set_headers(headers: Dictionary) -> void

GDPostgresClient.query_rows

結果を1行ずつ読み取るオブジェクトです。next()で次の行に進み、scan()またはvalues()でその行の値を取得します。読み取り後はerr()でエラーを確認し、close()で閉じます。

Incremental query results. Advance with next(), decode the current row with scan() or values(), inspect err(), and release resources with close().

Methods
next() -> bool
next_async() -> GDTask (await bool)
scan() -> Dictionary, Err
values() -> Array, Err
columns() -> PackedStringArray
err() -> Err
command_tag() -> String
close() -> void
cancel() -> void
is_closed() -> bool