KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

プロジェクトとジェネレーター

はじめに

A project is a folder with a kscript.json in it. The file tells every kscript command about the project: which scripts and pages it has, how to serve and test it, and how its code is written. Inside a project, kscript make writes new files where they belong, already wired together.

To get started, make a project and serve it:

シェル
kscript make project my-app   # a web app, a desktop app, an API and tests
cd my-app
kscript serve                 # then open http://localhost:8080

プロジェクトの開始: kscript make project

kscript make projectは、新しいWebアプリを、同じアプリのデスクトップウィンドウとともに、すべてが連携した状態で設定します:

シェル
kscript make project my-app --port 3000
cd my-app
kscript serve            # http://localhost:3000, from kscript.json
kscript desktop.kscript  # the desktop app, in a window
kscript compile          # build it as a program: dist/mac-arm64/My App.app, dist/win-x64/My App.exe...
kscript test             # runs the tests in tests/
kscript check            # checks every page and script in the project
kscript fmt              # tidies every script and page in the project

作成されるもの:

ファイル 概要
kscript.json serve、check、test、デスクトップアプリの場合はappセクションkscript compileが読み取る設定です。configセクションにはアプリ独自の設定があり、$configとして読み取られます。
index.html, about.md, _layout.html, _components/site-nav.kscript, site.css サイト: 2ページ、それらが共有するレイアウト、ナビゲーションコンポーネント。
tasks.html <live>ブロックによる、JavaScriptを使わないToDoリストです。
lib/tasks.kscript ToDoのルール(追加、チェック、削除、クリア、件数)。ページ、デスクトップアプリ、API、テストで共有されます。
desktop.kscript 同じToDoリストをデスクトップアプリとして作成したものです: Window { }ブロック。
routes/api.kscript, controllers/tasks.kscript /api配下のタスク用JSON API(KScript.Http)です。kscript serveの実行中は、ドキュメントが/_api(OpenAPI)で公開されます。
lib/greeting.kscript, scripts/hello.kscript 関数と、それを使うコマンドラインスクリプト。
tests/tasks.test.kscript, tests/greeting.test.kscript ルールとスクリプトのテスト。kscript testで実行します。
.vscode/extensions.json, .gitignore VS CodeにKScript拡張機能のインストールを促します。ビルドされたアプリ(dist/)はgitから除外します。
AGENTS.md, CLAUDE.md, .kscript/agents/ プロジェクトのコードから生成され、エディターによって最新に保たれるコーディングエージェント向けドキュメントです(コーディングエージェントを参照)。

スクリプト、テスト、ルート、デスクトップアプリは.kscript形式で記述します。--syntax xmlはその代わりにXML(.ks.xml)として書き出し、"make": { "syntax": "xml" }をkscript.jsonに記録するため、以後のkscript make scriptとkscript make testもそれに従います。ページはどちらの場合もHTMLのままです。

--no-desktopはdesktop.kscriptとappセクションを省きます。Webサイトのみの場合です。--no-httpはAPIを省きます。kscript make project .は現在のフォルダを設定します。既存のファイルは--forceを指定しない限り置き換えられません。kscript make project --helpはテンプレートのオプションを一覧表示します。

最小構成のプロジェクト: --bare

kscript make project my-tool --bareはkscript.json、main.kscript(スクリプト)、tests/main.test.kscriptに加え、VS Codeの推奨設定とエージェント用ドキュメント(AGENTS.md)のみを作成します。ページ、デスクトップアプリ、APIは作成しません。コマンドラインツールやスクリプト向けです。--syntax xmlもここで使えます。--bareは--template bareの短縮形で、kscript make project --help --bareでオプションを一覧できます。

オプションを任意に組み合わせて、最小構成のプロジェクトに部品を追加します:

コマンド機能
kscript make project my-app --bare --web --api空のWebサイトとJSON API。
kscript make project my-api --bare --apiAPIのみ: routes/api.kscript、controllers/hello.kscriptとそのテスト。
kscript make project my-app --bare --desktopスクリプトと空のデスクトップアプリ(Windowブロック)

--webはindex.html、_layout.html、site.cssを追加します。--apiはroutes/api.kscript(/api配下で配信されるRoutesファイル)、controllers/hello.kscript、tests/hello.test.kscriptを追加します。--desktopはdesktop.kscriptとkscript.jsonのappセクションを追加します。kscript.jsonは、Webサイトまたは API がある場合は常にserveの設定(および--port)を取得します。

API: --template api

kscript make project shop --template apiは、設定することが他にない、JSON APIを作成します。ルート、コントローラー、アプリ独自のミドルウェア、データベース内のモデル、APIトークンによるサインアップ、キャッシュ、テストが含まれます。

シェル
kscript make project shop --template api
cd shop
kscript serve      # http://localhost:8080/api/health, and the API's docs at /_api
kscript test       # 12 tests, against a database in memory
ファイル 概要
routes/api.kscript /api配下のルート: GET /health、POST /register、/tokens(スロットリング付き)、GET、DELETE /me、そしてauthミドルウェアの背後にある/notes用のResource。
controllers/notes.kscript notesリソース: index、store、show、update、destroyで、いずれもJSONで応答します。インポートするNoteInputのtypeが投稿内容を検証し(合わない場合は422)、存在しないノート(または自分のものでないノート)は404になります。
controllers/accounts.kscript KScript.Authを使った、サインアップ、トークン、アカウントの削除です。
models/note.kscript Noteのモデルです。テーブルは初回使用時に作成されます。
requests/note-input.kscript, requests/sign-up.kscript, requests/sign-in.kscript コントローラーがインポートする、型付きのリクエストボディです。1ファイルに1つのtypeがあります。
middleware/request-id.kscript アプリ独自のミドルウェア: すべてのレスポンスにX-Request-Idヘッダーが付与されます。
lib/cache.kscript アプリのキャッシュで、ストアと有効期限はkscript.json内のcacheから取得されます。
kscript.json, kscript.test.json, config.kscript アプリの設定: kscript.jsonのconfigセクションにあるデータベースとキャッシュ、kscript.test.jsonにあるテスト用のインメモリデータベース、環境変数(DATABASE_URL、CACHE_STORE)から読み込まれるものはconfig.kscriptです。
tests/ @api(/api/notes)を使い、クライアントと同じようにAPIを呼び出すテストです(自分のAPIを呼び出すを参照)。

APIを備えたWebアプリ: --template fullstack

kscript make project my-site --template fullstackは、ホームページ、レイアウト、APIのヘルスチェックエンドポイント、そのエンドポイントのテストを備えたサイトを作成します。プロジェクトに合わせて、データベース、サインイン、キャッシュ、Dockerのオプションを選んでください。

--examplesを渡すか、ウィザードでNotesのサンプルを含めますか?を選ぶと、ライブのNotesページ、CRUD API、そのテストが追加されます。ページはlib/notes-client.kscriptを通じて@api(/api/notes)付きでAPIを呼び出します。

データベース、サインイン、キャッシュ、Docker

apiとfullstackのテンプレートには、次のオプションが共通しています:

オプション 既定値 機能
--db sqlite|postgres|mysql|none sqlite kscript.jsonのconfigセクションで設定されるデータベース。noneを指定すると、Notesの例はJSONファイル(設定内のnotes.file)を使います。postgresまたはmysqlを指定すると、アプリはそのサーバーに接続します(DATABASE_URLはURLを上書きし、--dockerはそれをComposeファイルに追加します)。一方、kscript testは引き続きインメモリのSQLiteを使います。
--auth, --no-auth on(api)、off(fullstack) サインイン。apiテンプレートではPOST /api/register、/api/tokens、GET /api/meと、サインイン中のユーザーに属するノートを提供します。fullstackテンプレートでは、サインインページ用にkscript make authも実行します。ページは閲覧中のユーザーとしてAPIを呼び出します。
--cache, --no-cache on キャッシュの設定とヘルパーを追加します。Notesの例はこれを使ってリストをキャッシュし、304 Not Modifiedで繰り返しのリクエストに応答します。
--docker オフ Dockerfile、.dockerignore、compose.yamlを追加します。これらのデータベースにはPostgresまたはMySQLのサービスを追加し、make upとmake downも設定します。
--port 8080 kscript serveが使用するポート。

オプションは--db postgresまたは--db=postgresと書けます。はい/いいえのオプションはyes/no(--cache no)を取りますが、フォルダ名は取りません。そのためkscript make project --docker shopはshopになります。

既存のサイトにDockerを追加する

プロジェクト内の任意の場所でkscript make dockerを実行します。kscript.jsonの横にDockerfile、compose.yaml、.dockerignoreを追加します。--dry-runでファイルをプレビューできます。出力ファイルが既に存在する場合、コマンドは書き込む前に停止します。それらのファイルを置き換えるには--forceを使用してください。同じキットは、空のサイトを作成する際にも利用できます。

シェル
kscript make project portal --bare --web --api --port 4820 --docker -n
cd portal
docker compose up --build

http://localhost:4820を開きます。コンテナは、プロジェクトに設定されたserve.rootでサーバーを動かし、serve.portを使用します。ポートを変更する場合は、キットを再生成するか、公開ポートを更新してください。その際は、EXPOSEとヘルスチェックも合わせて更新してください。

Compose 2.17以降とBuildKitは、リリース済みCLIのGitリビジョンから、Linux ARM64またはAMD64向けのKScriptをビルドします。その際、固定されたマルチアーキテクチャの.NETベースイメージを使用します。開発版のビルドにはソースのチェックアウトが必要です。変更済みまたは未公開のKScriptをビルドする場合は、KSCRIPT_SOURCEにそのチェックアウト先を設定してください。

シェル
KSCRIPT_SOURCE=/absolute/path/to/kscript docker compose up --build

アプリは、読み取り専用のアプリケーションディレクトリを持つ非特権ユーザーとして実行されます。Composeは、KScript.Storage、認証状態、プロジェクト相対のSQLiteファイルを/var/lib/kscriptにあるapp-stateボリュームに保存します。このボリュームは、コンテナを置き換えても維持されます。KSCRIPT_PROJECT_DATA_ROOTは、設定された相対パスの認証データとSQLiteデータをこのフォルダの下に配置します。絶対パスや別のデータベースサーバーを使う場合は、デプロイ環境に応じて対応するマウントや接続を設定してください。ストレージパスを変更したら、kscript serveを再起動して、公開配信から除外されている非公開ファイルを更新してください。シークレットは、実行時の環境変数として渡せます。生成される.dockerignoreは、ドットファイル、一般的な認証情報ファイル、ローカルのデータベース、実行時の状態ファイルを除外します。ビルドの前に、プロジェクト固有のシークレットファイル名があれば追加してください。

コンテナがデータを保存する場所

生成されるDockerfileは、app-stateボリューム上に次の2つのフォルダを設定します:

変数 設定値 保持する内容
KSCRIPT_STORAGE_ROOT /var/lib/kscript/storage 各アプリのアプリフォルダー: KScript.Authのユーザー、セッション、APIトークンは既定のフォルダーに保存され、@storage()ファイルとファイルキャッシュもここに置かれます。
KSCRIPT_PROJECT_DATA_ROOT /var/lib/kscript/project kscript.json内の相対パス。認証データ(http.auth.folder)とSQLiteデータベース用です。これらは、設定しないと読み取り専用の/app内に置かれてしまいます。

どちらも必ずボリューム上に置く必要があります。ボリュームがないと、docker compose up --buildのたびにコンテナが再作成され、その中のデータはすべて失われます。どちらかの変数が未設定の場合、コンテナ内のkscript serveは警告を出力します。

0.27より前のDockerファイル

0.27より前のkscript make dockerで作成されたDockerファイルは、app-data:/app/dataしかマウントしていません。そのため、ユーザーとセッションはコンテナのホームフォルダに保存され、コンテナを再作成するとすべてのアカウントが失われます。これらのファイルに独自の変更(追加したPostgresサービスなど)を残したい場合は、--forceを使わずに手動で更新してください:

dockerfile
# Dockerfile: make the folder, owned by the app's user, and point KScript at it
RUN install -d -o app -g app -m 700 /var/lib/kscript
ENV KSCRIPT_STORAGE_ROOT=/var/lib/kscript/storage KSCRIPT_PROJECT_DATA_ROOT=/var/lib/kscript/project
YAML
# compose.yaml
services:
  app:
    volumes:
      - app-state:/var/lib/kscript
volumes:
  app-state:

変更前に作成されたアカウントは、古いコンテナ内にあり、それが置き換えられると失われます。残したい場合は、まず実行中のコンテナからコピーしてください: docker compose cp app:/home/app/.local ./kscript-backup。各アプリのファイルはそこのshare/<app>とstate/<app>にあります。新しいコンテナが起動したら、それらを/var/lib/kscript/storage/<App name>/dataと/var/lib/kscript/storage/<App name>/stateにコピーしてください。

Dockerで開発用サイトを実行する

Composeファイルのあるローカルプロジェクトでkscript serveを実行すると、そのappサービスが起動します。ホストで配信するには--no-dockerを使用します。これはプロジェクトを/appに読み取り専用でバインドマウントし、デフォルトで開発環境になります。ローカルでページ、スタイル、ルートファイルを編集してください。コンテナが変更を検知すると、ブラウザが再読み込みされます。手動で更新するには--no-reloadを使います。起動時の設定やイメージの依存関係を変更したら、サービスを再起動してください。既存のComposeデータボリュームは引き続き適用されます。/app/dataのように、ソースディレクトリ配下にマウントされた名前付きボリュームや匿名ボリュームの場合、KScriptはComposeを起動する前にローカルのマウントポイントディレクトリを作成します。

ローカルのDocker配信を設定するには、kscript.json内でserve.dockerを使用します。

JSON
{
  "serve": {
    "docker": {
      "compose_file": "compose.yaml",
      "service": "app",
      "mount": "/app",
      "build": true
    }
  }
}

"docker": "auto"はローカル配信中にComposeファイルを検出し、これがデフォルトです。ローカルでComposeを必須にするには"docker": trueを、--dockerを必須にするには"docker": falseを設定します。オブジェクト形式では、enabled: "auto"を使うとカスタム設定で検出できます。--portのようなホスト固有のオプションは、自動モードでホストを選択します。カスタムイメージ内のアプリディレクトリはmountに設定してください。イメージに組み込まれたファイルを配信するにはmount: nullを、既存のイメージを再利用するにはbuild: falseを設定します。テスト設定を選ぶにはkscript serve --docker --env testを使用します。公開ポートとサービスコマンドはComposeが制御します。Ctrl+Cで開発用のアプリコンテナが停止します。その依存サービスは実行されたままになることがあり、それらはdocker compose downで停止できます。

COMPOSE_PROJECT_NAME=myapp-test kscript serve --docker --env testを使うと、テスト用サービスとそのComposeで管理されるボリュームを、別のプロジェクトに分けられます。両方のサイトを同時に実行する場合は、テスト用のComposeファイルで別のホストポートを使用してください。

生成されるDockerfileとkscript serve --dockerは、配信の前に、コンテナに設定されたデータベースへ保留中のマイグレーションを適用します。マイグレーションが失敗すると、起動は停止します。マイグレーションを手動で適用するには、サービス実行中にdocker compose exec app kscript db migrate --forceを、または起動前にdocker compose run --rm app kscript db migrate --forceを実行してください。Docker内でも、ライブリロードはマウントされたソースを引き続き監視します。生成されるガイダンスを更新するには、ホストでkscript agentsを実行してください。

docker compose up --buildは、生成されたイメージにコピーされたソースを配信します。kscript serveを直接呼び出すカスタムイメージの場合は、コンテナ内でKSCRIPT_SERVE_IN_DOCKER=1を設定し、Webサーバーが起動するようにしてください。

セットアップウィザード

端末でオプションを指定せずにkscript make projectを実行すると、代わりにすべての項目を尋ねられます。フォルダ(指定していない場合)、プロジェクトの種類、そのテンプレートの各オプションです。各オプションにはデフォルト値があり、Enterを押すだけで確定できます。いずれかのオプション、または-n(--no-interaction)を指定すると、何も尋ねられません。指定しなかった項目はデフォルト値になります。スクリプトやCIではこの動作が求められます。入力または出力が端末でない場合も、何も尋ねられません。

Makefile

新しいプロジェクトには必ずMakefileがあるため、よく使うコマンドは短く書けます: make serve、make test、make check、make fmt、make agents、make compile、そしてAPIやデスクトップアプリがある場合はmake routes、make desktop、make appです。その他のターゲットはkscript makeに渡されます。名前にはname=を、オプションにはargs=を使います:

シェル
make page name=contact                          # kscript make page contact
make component name=Hero args="--props title"   # kscript make component Hero --props title

makeはmacOS(Xcodeコマンドラインツール内)とLinuxに付属しています。Windowsでは、インストールする(winget install GnuWin32.Make、scoop install make、またはchoco install make)か、kscriptコマンドを直接実行してください。別のkscriptを使うにはKSCRIPT=/path/to/kscriptを設定します。

新しいプロジェクトに含まれるものを変更する

kscript make projectが書き出すすべてのファイルはプロジェクトテンプレートから生成され、それらは変更できます:

コマンド機能
kscript make templates projectプロジェクトの外にいる場合: ~/.kscript/templates/projectにコピーされます。
kscript make templates project --globalプロジェクト内にいる場合も同じです。
kscript make templates projectプロジェクト内にいる場合: _templates/projectにコピーされます。
kscript make templates project bare空のテンプレートです。projectの代わりにproject-bareへコピーされます。
kscript make project my-app --template ../starters/api任意のフォルダ。

--templateにはフォルダかテンプレート名を指定できます。bareなどの名前(またはapiのような独自の名前)は、デフォルトテンプレートと同じ場所でproject-<name>として検索されます。デフォルトテンプレートはprojectにあり、その後、組み込みテンプレート(web、api、bare、fullstack)の中から検索されます。kscript make projectは最初に見つかったテンプレートを使用します。検索順は、--templateフォルダ、次に新しいプロジェクトを作成する場所を含むプロジェクト内の_templates/project(複数のアプリをまとめたフォルダに便利です)、次に~/.kscript/templates/project(または$KSCRIPT_TEMPLATES/project)、最後に組み込みテンプレートです。新しいプロジェクトに含まれるものを変えるには、テンプレートフォルダ内のファイルを編集、追加、削除してください。

  • スクリプトは.kscriptファイルとして書き、他のスクリプトは{{ ext }}(import "lib/tasks{{ ext }}")で参照します。--syntax xmlを使うと、各.kscriptファイルはXMLに変換され、.ks.xmlという名前になります。{{ ext }}は.ks.xmlです。{{#if xml}}で形式を区別します。テンプレート内の.ks.xmlファイルは、そのままコピーされます。
  • 各ファイルは、kscript makeテンプレートと同じ{{ }}プレースホルダーを持つテンプレートです。{{ title }}はタイトルとしてのプロジェクト名(My App)、{{ kebab }}はmy-appで、すべてのオプションは値({{ port }}、{{#if desktop}} … {{/if}})になります。
  • ファイルは--- makeヘッダーで始めることができます。when: desktopは、オプションがオンのときだけコピーし、unless: desktopはオフのときだけコピーします。to: docs/{{ kebab }}.mdは別の場所に書き出します。whenとunlessは{{#if}}と同じ条件を使います: when: db is none、unless: db in sqlite, none。2つのファイルが同じパスに書き出す場合、どちらか一方だけがコピーされるようにできます(controllers/notes-file.kscriptとwhen: db is none、to: controllers/notes.kscript)。
  • .stubで終わる名前では、末尾が取り除かれます。テンプレート内ではkscript.json.stubのまま保持され、エディタやkscript checkが本物のプロジェクトとして読み込まないようにします。
  • kscript-template.jsonはテンプレートを説明するもので、コピーされません。optionsは各オプションを、そのdefaultとdescriptionとともに一覧にします(デフォルトがtrueのオプションは--no-nameでオフにします)。セットアップウィザード用のquestionを指定でき、いくつかの値のうち1つを取る場合はchoicesで指定します。その場合、--db oracleは値の一覧を含むエラーになります。nextは「Next:」の下に表示される行を保持します。notesは注記として表示される行です(空になる行は省略されます)。makeは、ファイル書き込み後に新しいプロジェクトで作成されるキットを保持します。"make": ["{{#if auth}}auth{{/if}}"]はkscript make authを実行します。テンプレートに記載されていないオプションは報告されるため、--no-dekstopのような入力ミスも見逃されません。
JSON
// _templates/project/kscript-template.json
{
  "description": "Our standard web app",
  "options": {
    "desktop": { "default": true, "description": "Add the desktop app" },
    "api": { "default": false, "description": "Add an API page", "question": "Add an API page?" },
    "db": { "default": "sqlite", "choices": ["sqlite", "none"], "description": "Where data is kept" },
    "port": { "default": 8080, "description": "The port kscript serve uses" }
  },
  "next": ["kscript serve   http://localhost:{{ port }}", "{{#if api}}kscript serve, then open /api{{/if}}"]
}

ソースライブラリのインストール

kscript lib add は、公開 GitHub リポジトリから KScript のソースファイルをインストールします。名前だけを指定した場合、KScript は次の対象を検索します。自身の kylepantall/kscript カタログ、orimovo/* と waggr-gb/* に一致する信頼済みの公開リポジトリ、およびプロジェクトに登録されたリポジトリです。各リポジトリでは、まず libraries/<name>/ を確認します。そのフォルダーが存在しない場合は、ルートの kscript.json で、指定された名前のライブラリを宣言するか、それを宣言しているフォルダーを指定できます。

1つだけ一致する場合は、すぐにインストールされます。同じ名前を持つ個別のパッケージが複数ある場合、CLIは一致の数と、修飾された各owner/repo@library名を表示します。いずれか1つを選び、その名前でkscript lib addを再実行してインストールしてください。各owner/repo@libraryは、そのリポジトリが信頼済みであり、かつローカルに登録されている場合でも1回だけ表示されます。ライブラリをGitサブモジュールとして固定する別のカタログには独自の修飾名があり、異なるリビジョンを固定することもできます。

公式ライブラリ 提供する機能 使用するランタイムパッケージ
integer-math 最大公約数、最小公倍数、階乗 コアのみ
app-cache プロジェクトのキャッシュストアと有効期限の設定を使って、計算済みの値をキャッシュします KScript.Cache
request-id 呼び出し元のリクエストIDをそのまま引き継ぐか、レスポンス用に新たに生成するHTTPミドルウェアです。 KScript.Http
isolink-connect Isolink デスクトップセッションを開き、スペースとレコードを操作します。 KScript.Net

Core はすべてのスクリプトで利用できます。表にあるほかのランタイムパッケージは KScript に同梱されており、各ライブラリは使用するパッケージをインポートします。たとえば、Isolink Connect は名前を指定してインストールしてください。

シェル
kscript lib add isolink-connect

新しいプロジェクトでは、信頼された所有者のどちらかの下にある公開リポジトリを明示的に選択できます。例えば、Isolink SDKはwaggr-gb/isolink-connectにあります。

シェル
kscript lib add waggr-gb/isolink-connect@isolink-connect

修飾インストールでは、他の発行元にまたがる探索をスキップします。探索が完了できない場合、または GitHub の API 上限に近い場合に使用してください。ただし、選択したリビジョンを解決するために API の割り当てはまだ必要です。GitHub の割り当てを使い切っている場合は、リセットされてから再試行してください。

インストーラーは、サイトのルートから使用するインポートを表示します。SDK 0.3 では、マニフェストのエントリーclient.kscriptと、KScript.Netからの汎用の@with_loopback_jsonトランスポートを使用します。

<import path="lib/isolink-connect/client.kscript" as="connect" />
import "lib/isolink-connect/client.kscript" as connect

組み込みのカタログや信頼済みの発行者に含まれない発行者の場合は、そのリポジトリを個別にプロジェクトへ登録してください。登録後は、名前だけを指定してインストールするか、その発行者を直接選択できます。たとえば、チームが slugs ライブラリを acme/kscript-libraries で公開している場合は、プロジェクトから両方のコマンドを実行してください。

コマンド機能
kscript repo add acme/kscript-librariesRepositories that publish libraries.
kscript lib add acme/kscript-libraries@slugsInstall its slugs library.

The first command also accepts the repository's HTTPS URL. It records the registration in .kscript/repos/ beside the nearest kscript.json, or in the current folder for standalone scripts. Commit the registration to share it with teammates. The second command downloads libraries/slugs/ from the registered repository's default branch. A script in the site root can then use import "lib/slugs/index.kscript" as slugs with the default layout.

For a direct install, kscript lib add owner/repo or kscript lib add https://github.com/owner/repo starts at the repository root. If its kscript.json points to a library folder, the installer copies just that folder. Otherwise it installs the entire repository. A GitHub tree URL selects a branch, tag, commit, or folder within it, such as kscript lib add https://github.com/owner/repo/tree/v1.0.0/libraries/slugs. Direct installs work without registering a repository.

Named libraries install into lib/<library-name>/. Direct installs use lib/<repository-name>/ when you select a repository or lib/<folder-name>/ when you select a folder. Set paths.lib in the nearest kscript.json to choose another folder relative to serve.root. Outside a project, the command installs into lib/ in the current folder. Imports are relative to the script containing them, so a script one level down would use ../lib/isolink-connect/client.kscript.

インストーラーは選択したフォルダーのkscript.jsonを読み取り、ライブラリのメタデータを検証して、library.entry用のインポートを出力します。library.entryがない場合、エントリーはライブラリの最上位のmain.kscript、main.ks.xml、index.kscript、index.ks.xmlの順に決まります(kscript runと同じメインスクリプトの規則です)。libraryセクションのない古いライブラリでも同じ規則を使い、その後に最も浅い階層のスクリプトを使います。インストール先フォルダー内に生成される.kscript-lib.jsonの受領記録には、ソース、正確なコミット、エントリーパスに加え、宣言されている場合は名前、バージョン、実行時パッケージが記録されます。

In VS Code, completions inside the project's packages array show which runtime packages the installed, pinned libraries require. Add a package there when you also want it available throughout your project. Completions under types use the running KScript version's built-in types and accepted options, such as types.password.min and types.uuid.v.

Restoring a project's libraries

kscript lib add records the source URL and full commit under libraries in the consuming project's kscript.json. If there is no project yet, a successful add creates this file in the current directory. Commit it so teammates and CI can restore the same revisions after cloning.

A named Isolink install records the selected publisher folder and commit. For example, a project pinned to one revision looks like this.

JSON
{
  "libraries": {
    "isolink-connect": {
      "source": "https://github.com/waggr-gb/isolink-connect/tree/HEAD/libraries/isolink-connect",
      "commit": "d12745f9989a9523fcb33922f75625f0c1a96766"
    }
  }
}

On a fresh checkout, run the following command from the project or one of its subdirectories.

シェル
kscript lib restore

Restore reads the pins from the nearest project and fetches each library directly from its recorded publisher at the exact commit. For the example above, it fetches libraries/isolink-connect/ from waggr-gb/isolink-connect. A direct repository install records the repository URL and commit. Restore follows the library folder reference from that commit. If a team catalog publishes a Git submodule, the recorded catalog commit also fixes the upstream commit. An existing copy at the recorded revision keeps its local edits. To share those edits, commit the modified library files or publish the changes upstream. The installer uses the empty .kscript/libraries.lock file to coordinate simultaneous adds. You can ignore it in Git.

Publishing a named library

On the default branch of your public repository, put each library in an ordinary folder under libraries/ or pin a separate public GitHub repository there as a Git submodule. Both layouts publish source directly. For an ordinary folder, include the entry script, any scripts it imports by path, and any data it reads. The acme/kscript-libraries@slugs example could contain these files.

テキスト
libraries/
  slugs/
    kscript.json
    index.kscript
    README.md

Put the manifest beside the public source. For example, libraries/slugs/kscript.json can declare a Core-only library.

JSON
{
  "name": "slugs",
  "library": { "version": "1.0.0", "entry": "index.kscript" },
  "packages": []
}

library.version is a semantic version. library.entry is a .kscript or .ks.xml path relative to this file and can point to a nested module. Leave it out when the entry is main.kscript or index.kscript beside the manifest: "library": { "version": "1.0.0" } is enough. List required native runtime packages such as KScript.Net under packages, and import them in the source modules that use them. Declare public functions in the entry module. Users can then install your published library by its qualified name.

A repository that publishes a single library can place the same manifest and entry script at its root. Set name to the library name users should install. For example, a root manifest named slugs in the registered repository acme/slug-tools can be installed as kscript lib add acme/slug-tools@slugs.

A repository with tests or examples alongside the SDK can point its root kscript.json to the package folder. For example, Connect can keep its test settings in the following root manifest.

JSON
{
  "library": "libraries/isolink-connect",
  "test": { "include": ["tests/**/*.test.kscript"] }
}

The path is relative to this manifest. The target folder must contain its own kscript.json declaring a library name, library.version and library.entry. Declare any runtime packages there, too. Both kscript lib add waggr-gb/isolink-connect and kscript lib add waggr-gb/isolink-connect@isolink-connect then install that folder and print the same import. The repository's tests and examples stay in the checkout.

To publish slugs from a separate repository, run this in your library catalog and commit both .gitmodules and libraries/slugs.

シェル
git submodule add https://github.com/acme/slug-tools.git libraries/slugs

kscript lib add acme/kscript-libraries@slugs downloads the upstream commit pinned by the catalog. If the upstream contains libraries/slugs/, only that folder is installed, so other SDKs can share the repository. Otherwise the installer uses the upstream root. Keep all scripts and assets in the selected folder. The installer follows one submodule level, and records both repositories' commits in .kscript-lib.json. To publish an update, commit the new submodule pin in the catalog.

Project settings: kscript.json

kscript serve, kscript check, kscript fmt, kscript make and the editor read the nearest kscript.json in the folder they work on or a parent folder, so they behave the same from anywhere in the project. Every setting is optional:

JSON
{
  "name": "my-site",
  "kscript": "0.51.0",                             // the KScript release the project is written for (see below)
  "timezone": "Europe/London",                     // the zone stored dates are in (see docs/data.md); this is the default
  "standard": "kscript:recommended",               // lint rules and format settings to start from (see Standards)
  "packages": ["KScript.Terminal", "KScript.IO"],   // imported by every script in the project
  "extensions": ["extensions", "shared/**/*.kscript"], // where the project's extend files are (default: extensions/)
  "natives": ["natives"], // where the project's native types are, used without an import (default: natives/)
  "serve": {
    "root": ".",          // the site folder, relative to kscript.json
    "port": 8080,         // --port and --host on the command line still win
    "host": "localhost",
    "docs": true          // also serve the docs, with a page about this project (see docs/web.md)
  },
  "http": {
    "middleware": ["log"],                     // routes, middleware and their settings (see docs/http.md)
    "groups": { "api": ["cors", "throttle"] }
  },
  "lint": {
    "include": ["**/*.html", "**/*.md", "**/*.kscript"],  // what `kscript check` looks at
    "exclude": ["_templates", "node_modules", "drafts/**"], // never checked, on the command line or in the editor
    "rules": { "KS3003": "off", "KS4*": "error" },          // off, hint, info, warning or error, by code or prefix
    "warnings_as_errors": false                               // same as kscript check --warnings-as-errors
  },
  "test": {
    "include": ["tests/**/*.test.kscript"],  // what `kscript test` runs (default: **/*.test.kscript and **/*.test.ks.xml)
    "exclude": ["tests/slow"],
    "timeout": 10,                          // seconds per test, 0 for no limit
    "packages": ["KScript.Terminal"],       // imported by test files only
    "env": "test"                           // the environment tests run in, so kscript.test.json applies
  },
  "format": {
    "indent": 2,           // spaces per level, or "tab"; used by kscript fmt and Format Document
    "print_width": 80,      // the longest a line should be; longer lines are wrapped
    "rules": { "statement_per_line": false },  // any rule can be turned off
    "exclude": ["vendor"]  // see docs/formatting.md for every format setting
  },
  "app": {
    "main": "app.kscript",      // what `kscript run` and `kscript compile` start from (default: main.kscript, then index.kscript)
    "name": "My App",           // shown in the Dock, Start menu or launcher (default: the project's name)
    "id": "com.example.myapp",  // the macOS bundle id
    "version": "1.0.0",
    "icon": "icon.png",         // a .png, .ico or .icns, used for every platform
    "user_config": true         // lay the person's own config.json (KScript.Storage) over $config
  },
  "types": {
    "uuid": { "v": 4 },                     // arguments for every use of a built-in type (see Types and validation)
    "password": { "min": 12 }
  },
  "config": {
    "app": { "name": "Shop" },              // the app's own settings: $config.app.name
    "database": { "connections": { "main": { "url": "sqlite:data/shop.sqlite" } } }
  }
}
  • A pattern without a / (such as _templates or *.draft.html) matches a file or folder of that name anywhere. Otherwise it is matched against the path from kscript.json: * stays within a folder, ** spans folders, and a folder matches everything in it.
  • kscript names the KScript release the project is written for: an exact release such as "0.51.0", or "0.51" for the newest 0.51.x. Editors that fetch KScript for you, such as FlowIDE, run the project with that release; without it they use the latest one.
  • standardは、プロジェクトのlintとformatの設定が出発点とする標準を選びます。既定はkscript:recommended、kscript:strict、または複数のプロジェクトで共有できる独自の標準ファイルです。kscript.json自体に設定された内容は、標準より優先されます。kscript check --print-configは結果と、各設定の出所を表示します。
  • rules changes how serious a diagnostic is (see the codes). The longest match wins, so "KS3*": "warning" with "KS3001": "error" keeps unknown elements as errors.
  • コメントと末尾のカンマが使えます。不明な設定は黙って無視されず、警告として報告されます。VS Code拡張機能はファイルを検証し、入力中に設定を補完します。
  • formatはkscript fmtとエディターのドキュメントの整形スタイルを設定し、format.rulesは個々のルールを無効にします。すべての設定と無視コメントについては整形を参照してください。
  • プロジェクト内では、kscript make page aboutはサブフォルダから実行しても、サイトのルートにページを作成します。
  • configにはアプリ独自の設定が入り、$configとして読み取られます。kscript.jsonと並ぶkscript.<env>.jsonとconfig.kscriptがその上に重ねられます(設定を参照)。
  • kscript serveはkscript.json、kscript.<env>.json、.envファイル、およびconfig.*のJSONファイルは配信しません。
  • httpは、KScript.Httpのルートファイル、ミドルウェア、CORS、認証、レート制限を設定します(ルート、コントローラー、ミドルウェアを参照)。
  • typesは、uuid、email、passwordなどの組み込み型に、プロジェクト全体で同じ引数を与えます。型を使う箇所で書かれた引数(uuid(v: 8)など)が優先されます(型と検証を参照)。
  • app.name(またはname)は、設定、データ、キャッシュ用のアプリ独自のフォルダーも指定します(アプリフォルダーを参照)。
  • queueは、ジョブが待機する接続、ワーカーが確認するキュー、失敗したジョブの保持期間を指定します(キューとジョブを参照)。
  • appはkscript compileが読み取る設定で、スクリプト(多くの場合デスクトップアプリ)をmacOS、Windows、Linux向けのプログラムにビルドします(プログラムを参照)。

ファイルの生成: kscript make

kscript make <type> <name>は、その種類のファイルをプロジェクトが保持する場所に作成し、必要なフォルダーを作り、プロジェクトの形式でスクリプトを書き出します。kscript makeコマンドには、各種類のオプションと例がすべて載っており、kscript make --listでも同じ内容を確認できます。kscript make <type> --helpは1つの種類を表示します。

コマンド機能
kscript make route usersroutes/web.kscript に Get(path: /users, to: @users.index) を追加し、index() を持つ controllers/users.kscript を作成します
kscript make route "users/{id}" --where "id: int"Get(…, to: @users.show) を追加し、コントローラーに show(id) を追加します。
kscript make route users --method post --apiroutes/api.kscript に Post(…, to: @users.store) を追加します。/api 配下で提供されます。
kscript make route people --resource --apiResource(path: /people, to: people) を、5 つの関数すべてを含めて作成します。
kscript make route about --view aboutGet(path: /about, view: "about") と views/about.html を作成します。
kscript make controller people --resourceControllers/people.kscript: index、show、store、update、destroy。
kscript make request NewPerson --fields "name: string, age?: int"Requests/new-person.kscript。型付きのボディを持ちます。
kscript make middleware secure-headersMiddleware/secure-headers.kscript。
kscript make view people/show --vars personViews/people/show.html。@view('people/show', person: $p) で使用します。
kscript make component Hero --props title,sub-title_components/hero.kscript。<hero title="…" sub-title="…" /> の形で使用します。
kscript make component NoteCard --for window --props titleComponents/note-card.kscript。NoteCard(title: …) としてウィンドウ内に描画します。
kscript make component PostCard --model Post --inject_components/post-card.kscript。ルートの post を @inject(can: read) で受け取ります。
kscript make page about --title "About us"About.html。_layout.html で囲みます(なければ作成します)。
kscript make page "people/[id]"People/[id].html。URL から $id を読み取ります。
kscript make css theme --primary "#3355ff"Styles/theme.ks.css。/styles/theme.css として提供されます。
kscript make type Repo --fields "name: string, stars: int from stargazers_count"Types/repo.kscript。
kscript make enum Size --values small,medium,largeTypes/size.kscript。
kscript make native Sku --pattern "/^[A-Z]{3}-\d{4}$/"Natives/sku.kscript。import なしであらゆるスクリプトで使用できます。
kscript make module pricing --fns subtotal,totalLib/pricing.kscript。
kscript make window settingsSettings.kscript。デスクトップウィンドウです。
kscript make document annual-reportDocuments/annual-report.kscript。PDF と Word の文書です。
kscript make config stagingKscript.staging.json。ステージング環境の設定です。
kscript make test checkoutTests/checkout.test.kscript。
kscript make error PaymentFailed --status 402 --fields "order: int"Errors/payment-failed.kscript。
kscript make extension date --methods api_date,is_paydayExtensions/date.kscript: extend date { fn api_date() … }。
kscript make policy PostPolicies/post.kscript: Post { fn update(user, post) … } のポリシー。
kscript make auth --apiサインアップ、サインイン、リセット、API トークン(Sign-in を参照)
kscript makeすべての種類を一覧表示します。

ターミナルで名前を省略すると、kscript make は名前を尋ねます。kscript make page はページの名前を尋ね、オプションも指定されていない場合は、ページの各オプションについても尋ねます。--timestamps のようなはい/いいえのオプションははい/いいえの質問になり、それ以外のオプションは Enter キーを押すとスキップされます。いずれかのオプションを指定すると、名前だけが尋ねられます。-n(--no-interaction)を使用する場合、または入力や出力がターミナルでない場合は、何も尋ねられず、名前が省略されているとエラーになります。

生成されるファイルには、各種類に必要な関数がすでに書かれており、// TODO:(HTMLでは<!-- TODO: -->)のコメントで、そこに何を書くかが示されています。コントローラーのshow(id)には、レコードを検索し、存在しなければ404を返すように書かれており、ジョブのhandle()には、そこで作業を行うように書かれています。生成されたファイルは、kscript checkとkscript fmt --checkをそのまま通過させます。

ルートはroutes/web.kscriptに追加されます。または、--apiを指定したroutes/api.kscriptに追加されます。routes.kscriptやapi.kscriptを先頭に置いている、あるいはルートファイルをhttp.routesに一覧しているプロジェクトでは、代わりにそちらにルートが追加されます。ルートファイルはコントローラーをインポートし、同じメソッドとパスのルートが既にそのファイルにある場合、ルートの追加は拒否されます。structとrecordはtypeの別名で、fnとfunctionはmoduleの別名です。スクリプトで宣言できるもの(関数、定数、列挙型、型)の種類ごとにジェネレーターがあります。

オプションの値は、何かを書き込む前に確認されます。kscript make job Send --tries abc、make error E --status abc、make document d --template nope、make route "a b/{id}" はそれぞれ、値として何が必要かを伝えるメッセージを表示して停止し、終了コード 2 で終了します。kscript make project は、テンプレートに存在しないオプションに対して同様に動作し、存在するオプションの一覧を表示します。make document --template には paper、report、plain、letter、invoice のいずれかを指定できます。

kscript make は、ファイルの種類ごとに専用のフォルダーへ振り分けます。フォルダーは初めて必要になった時点で作成されるため、プロジェクトには使用しているフォルダーだけが存在します:

テキスト
my-app/
  kscript.json     settings, including "paths"
  schedule.kscript tasks that run at set times (make schedule)
  Makefile
  .env             secrets (make env); never served
  routes/          web.kscript (served at /) and api.kscript (served at /api)
  controllers/     make controller, make route
  middleware/      make middleware
  requests/        make request
  views/           make view
  _components/     make component (folders starting with _ are never served)
  _layouts/        make layout (the default _layout.html stays at the top)
  _partials/       make partial
  styles/          make css
  lib/             make module, const, cache, storage and logger
  types/           make type, make enum
  models/          make model
  policies/        make policy: who may create, read, update and delete a model's records
  natives/         make native: types every script gets without an import
  extensions/      make extension: methods every script gets (extend date { … })
  errors/          make error
  jobs/            make job
  documents/       make document
  locales/         make locale
  data/            JSON that stores and caches write
  scripts/         make script
  tests/           make test

型は1ファイルに1つです。各型、モデル、列挙型、エラー型にはそれぞれ専用のファイルがあり、その名前は型名に由来します(OrderStatus は types/order-status.kscript 内)。型を使用するファイルは、その型をインポートします:

<!-- models/order.kscript -->
<import package="KScript.Data" />
<import path="../types/order-status.kscript" />

<model name="Order">
  <field name="status" type="OrderStatus" default="'open'" />
</model>
// models/order.kscript
import KScript.Data
import "../types/order-status.kscript"

model Order {
  status: OrderStatus = 'open'
}

ジェネレーターとプロジェクトテンプレートはすべてこの方式で動作します。プロジェクト内では、2つ目の型を宣言しているファイルに対してkscript checkが(KS6008)警告を出し、どこへ移すべきかを示します。プロジェクト外で単独実行されるスクリプトは、型をそのまま保持できます。コンポーネントは、そのブロック内でのみ使われる型、列挙型、エラー、モデルを保持できます。

インポートなしで見つかるものが2つあります。ネイティブ型はnatives/で、どのスクリプトでも使えます(emailと同様に言語の一部です)。また、モデルのフィールドは、modelsフォルダ内の別のモデル(paths.models)を、インポートせずに型として指定できます。互いにリンクする2つのモデル(一方のauthor: Userと、もう一方のposts: Post[])は、そうしないと互いをインポートしてしまい、循環インポートは許可されていないためです。この検索はモデルフィールドの型にのみ使われます。コントローラーやスクリプトでUserを使う場合は、引き続きmodels/user.kscriptをインポートする必要があります。

ページは、ページのパスがそのままURLになるため、現在の場所に残ります。デスクトップウィンドウ(make window)は、desktop.kscriptの隣の上部に配置されます。フォルダーを移動するには、pathsをkscript.jsonで使用してください:

JSON
{
  "paths": { "controllers": "app/controllers", "styles": "assets/css", "views": "app/views" }
}

名前は routes、controllers、middleware、requests、views、components、layouts、partials、styles、lib、types、models、errors、storage、jobs、windows、locales、logging、data、scripts、tests です。http.views で別の指定がない限り、@view() は paths.views も参照します。kscript serve は routes/web.kscript と routes/api.kscript を自動的に見つけます。それ以外の場所にあるルートファイルは、http.routes に記載する必要があります。パスはプロジェクトフォルダーからの相対パスです。ページは paths.components を参照します。既定値は _components/ です。

名前はどのような書き方でもかまいません(HeroBanner、hero-banner、hero_banner)。ファイルはケバブケースで名付けられます。オプション:--dir <project>(既定値:プロジェクト内ではプロジェクトのサイトルート、それ以外では現在のフォルダー)、既存のファイルを置き換えるには--force、ファイルに書き込まず出力するには--dry-runを使用します。その他の--key value(または--key=value、またはtrueの代わりの単独の--flag)はすべてテンプレートに渡されます。

スクリプトとテストは.kscriptファイルとして書きます。代わりに--syntax xmlは.ks.xmlを書き出し、kscript.jsonの"make": { "syntax": "xml" }によって、それがプロジェクトの既定値になります。

独自のテンプレート。 テンプレートはプロジェクトの_templates/フォルダーにあり、kscript serveはそれを決して配信しません。kscript make templatesは、編集用に組み込みのテンプレートをそこへコピーします。そこにあるファイルは、同じ名前の組み込みテンプレート(_templates/component.kscript)を置き換え、それ以外のファイルは新しい種類を追加します。_templates/card.htmlはkscript make card Profileを生成します。

HTMLページ
--- make
description: A card with an optional image
to: _components/{{ kebab }}-card.html
hint: Use it in a page: <{{ kebab }}-card />
---
<article class="card {{ variant ?? plain }}">
{{#if image}}
  <img src="{$image}" alt="">
{{/if}}
{{#each props}}
  <p>{${{ item | var }}}</p>
{{/each}}
  <slot />
</article>
  • --- makeヘッダーは省略可能です。toはファイルの出力先です(既定値: テンプレートの拡張子を付けた名前)。hintは後で出力されます。descriptionはkscript makeに表示されます。category、usage、example:の行は(必要な数だけ)書けます。--option: what it doesの行はkscript make --listの対応する項目を埋めます。$defaults: actions=indexはオプションに既定値を設定します。$checks: tries=int; level=debug|info|warnは、何かが書き込まれる前に動作しない値を拒否します。たとえば選択肢の一覧にない値、またはint、number、status、duration、durations、fields、names、assignments、locale、file(プロジェクト内のファイル)を指定した場合です。name=は名前そのものを検証します。base: projectはtoを、testテンプレートと同様にサイトのルートではなく、プロジェクトフォルダ(kscript.jsonがある場所)からの相対パスにします。
  • {{ name }} は入力されたままの名前です。{{ kebab }}、{{ snake }}、{{ pascal }}、{{ camel }}、{{ title }} は、その他のつづりです。{{ dir }} はそのフォルダです(blog/first-post の場合は blog/)。{{ path }} はフォルダ名とケバブケースの名前、{{ url }} はそのページの URL です。{{ params }} には [id] 個のセグメントが並びます。{{ paths.controllers }} と他の paths は、プロジェクトのフォルダです。{{ up }} は、新しいファイルからプロジェクトのフォルダへ戻るパスです(lib/x.kscript の場合は ../)。{{ ext }} は .kscript または .ks.xml です。
  • {{ value | kebab }} はフィルターを適用します(kebab snake pascal camel title var lower upper trim quoted code。var は sub-title をコンポーネントが受け取る sub_title に変換し、quoted は値を文字列として書き出します。二重引用符が必要な場合を除き、シングルクォートで囲みます。code は、何も埋めない入力された "text" をシングルクォートで囲みます)。また、{{ value ?? fallback }} はデフォルト値を指定します。
  • {{#if value}} … {{else}} … {{/if}}、{{#unless value}}、{{#if value is text}}、{{#if value in a, b}}、{{#if list has text}}、{{#each value}} … {{ item }} … {{/each}} を、カンマ区切りのリスト({{ index }}、{{ first }}、{{ last }} が設定されている)に対して使用します。ブロックタグを単独の行に置いても、空行は残りません。
  • 波括弧(単一の中括弧)はそのまま残されるため、KScript の {$value} はそのまま記述されます。

終了コード

すべての kscript コマンドは、次のいずれかの値で終了します。これにより、CI ジョブは「チェックが失敗した」のか「コマンドが誤っていた」のかを区別できます。

コード 意味
0 すべて正常に完了しました。
1 コマンドは実行されましたが問題が見つかりました。kscript check がエラー(--warnings-as-errors 指定時は警告も)を検出した、テストが失敗した、または --check(fmt、agents、watch)が古くなっているものを検出した場合です。
2 コマンドラインまたは設定が誤っています。不明なコマンドやオプション、値の欠落、存在しないファイルやフォルダー、または使用できない kscript.json や規格などが該当します。
3 スクリプトがエラーで停止しました(または exit に渡されたコード)。
70 kscript 自体でエラーが発生しました。スクリプトの実行中に発生した場合も含みます。
130 Ctrl+C で停止しました。kscript serve と kscript watch は停止されるまで実行を続けるため、Ctrl+C が終了方法となり、終了コードは 0 になります。

オプションの書き方はすべてのコマンドで共通です。--output text|json|yaml は結果の表示形式(check、queue、openapi)を選択し、--syntax kscript|xml はスクリプトの構文(make、docs、mcp、convert)を選択します。フラグはケバブケース(--warnings-as-errors、--stop-when-empty)で、kscript.json の設定はスネークケース(warnings_as_errors)です。--env name、--ansi、--no-ansi、--stack-trace はどのコマンドの後にも指定できます(kscript worker --env staging)。スクリプトの場合は、名前の前に指定します(kscript --env staging deploy.kscript、または kscript run --env staging deploy.kscript)。名前の後ろに続くものはスクリプトの $args になるためです。