KScript 文档
ZH

项目与 kscript.json

生成文件:kscript make

kscript make <type> <name> 会在项目保存该类文件的位置创建文件,必要时创建所需文件夹,并按项目的格式编写脚本。kscript make 命令列出了每种类型及其选项和示例,kscript make --list 也会列出;kscript make <type> --help 显示某一种类型的详情。

命令作用
kscript make route users在 routes/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 --api在 routes/api.kscript 中添加 Post(…, to: @users.store),在 /api 下提供服务。
kscript make route people --resource --apiResource(path: /people, to: people),包含全部五个函数。
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,通过 @inject(can: read) 接收路由中的 post。
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:在每个脚本中无需导入即可使用。
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 令牌(参见登录)
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 中,或者使用 routes/api.kscript 加上 --api。如果项目已经在顶部保留了 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}" each stop with a message saying what the value should be, and exit with 2. kscript make project does the same for an option its template doesn't have, and lists the ones it has. make document --template takes paper, report, plain, letter or 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

每个文件只包含一种类型。每个类型、模型、枚举和错误类型都有自己的文件,文件名与之同名(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'
}

这些生成器和项目模板都是这样工作的。在项目中,kscript check 会对声明了第二个类型的文件发出警告(KS6008),并说明应将其移到何处。单独运行的项目外脚本,可以把它的类型保留在脚本本身之中。组件 可以在自己的代码块中保存只有它自己使用的类型、枚举、错误和模型。

无需导入即可找到两类内容。原生类型(见natives/)在所有脚本中都可用,它们是语言本身的一部分,就像email一样。另外,模型字段可以直接使用 models 文件夹中的另一个模型(见paths.models),而无需导入它,因为两个相互引用的模型(一个中的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),文件名使用短横线命名法(kebab case)。选项:--dir <project>(默认值:项目内为项目的站点根目录,否则为当前文件夹),--force 用于替换已有文件,--dry-run 用于打印文件内容而不是写入文件。其他每个 --key value(或 --key=value,或单独的 --flag 表示 true)都会传递给模板。

脚本和测试都以 .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: 行(可按需添加任意多行)用于填写其在 kscript make --list 中的条目,而 --option: what it does 行则为 $defaults: actions=index 的选项提供默认值。$checks: tries=int; level=debug|info|warn 会在写入任何内容之前拒绝无效的值:即不在可选列表中的值,或 int、number、status、duration、durations、fields、names、assignments、locale 或 file(项目中的文件)。name= 会检查名称本身。base: project 使 to 相对于项目文件夹(即 kscript.json 所在位置)而非站点根目录,与 test 模板的做法一致。
  • {{ name }} 是输入时的原始名称;{{ kebab }}、{{ snake }}、{{ pascal }}、{{ camel }} 和 {{ title }} 是它的其他拼写形式;{{ dir }} 是它的文件夹(blog/ 对应 blog/first-post),{{ path }} 是文件夹和 kebab 名称,{{ 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} 会按原样写出。