gaji 0.3.2

Type-safe GitHub Actions workflows in TypeScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# TypeScript API 레퍼런스

gaji의 TypeScript API에 대한 완전한 레퍼런스입니다.

## 핵심 클래스

### `Workflow`

GitHub Actions 워크플로우를 나타냅니다.

```typescript
class Workflow {
  constructor(config: WorkflowConfig)
  addJob(id: string, job: Job | CompositeJob | CallJob): this
  static fromObject(def: WorkflowDefinition, id?: string): Workflow
  build(filename?: string): void
  toJSON(): WorkflowDefinition
}
```

| 메서드 | 설명 |
|--------|------|
| `addJob(id, job)` | 워크플로우에 job을 추가합니다. `Job`, `CompositeJob`, `CallJob`을 받습니다. |
| `fromObject(def, id?)` | `WorkflowDefinition` 객체로부터 Workflow를 생성합니다. 기존 YAML 형태의 정의를 래핑할 때 유용합니다. |
| `build(filename?)` | 워크플로우를 YAML로 컴파일하여 출력합니다. |
| `toJSON()` | `WorkflowDefinition` 객체로 직렬화합니다. |

#### `WorkflowConfig`

```typescript
interface WorkflowConfig {
  name: string
  on: WorkflowTriggers
  env?: Record<string, string>
  permissions?: WorkflowPermissions
  concurrency?: WorkflowConcurrency
}
```

#### 예제

```typescript
const workflow = new Workflow({
  name: "CI",
  on: {
    push: { branches: ["main"] },
    pull_request: { branches: ["main"] },
  },
  env: {
    NODE_ENV: "production",
  },
})
  .addJob("test", testJob)
  .addJob("build", buildJob);

workflow.build("ci");
```

#### `Workflow.fromObject()` 예제

```typescript
const workflow = Workflow.fromObject({
  name: "Raw Workflow",
  on: { push: {} },
  jobs: {
    test: {
      "runs-on": "ubuntu-latest",
      steps: [{ run: "echo hello" }],
    },
  },
});

workflow.build("raw");
```

---

### `Job`

워크플로우의 작업을 나타냅니다.

```typescript
class Job {
  constructor(runsOn: string | string[], options?: Partial<JobDefinition>)
  addStep(step: Step): this
  needs(jobs: string | string[]): this
  env(variables: Record<string, string>): this
  when(condition: string): this
  permissions(perms: Permissions): this
  outputs(outputs: Record<string, string>): this
  strategy(strategy: JobStrategy): this
  continueOnError(v: boolean): this
  timeoutMinutes(m: number): this
  toJSON(): JobDefinition
}
```

| 메서드 | 설명 |
|--------|------|
| `addStep(step)` | job에 스텝을 추가합니다. |
| `needs(jobs)` | job 의존성을 설정합니다. |
| `env(variables)` | 환경 변수를 설정합니다. |
| `when(condition)` | job의 `if` 조건을 설정합니다 (예: `"github.ref == 'refs/heads/main'"`). |
| `permissions(perms)` | job 수준의 권한을 설정합니다 (예: `{ contents: 'read' }`). |
| `outputs(outputs)` | job 출력을 정의합니다. |
| `strategy(strategy)` | 매트릭스 전략을 설정합니다. |
| `continueOnError(v)` | `continue-on-error` 플래그를 설정합니다. |
| `timeoutMinutes(m)` | `timeout-minutes` 값을 설정합니다. |
| `toJSON()` | `JobDefinition` 객체로 직렬화합니다. |

생성자의 `options` 파라미터로 모든 옵션을 한번에 설정할 수 있습니다:

```typescript
const job = new Job("ubuntu-latest", {
  needs: ["test"],
  env: { NODE_ENV: "production" },
  "timeout-minutes": 30,
});
```

#### 예제

```typescript
const job = new Job("ubuntu-latest")
  .needs(["test"])
  .env({
    NODE_ENV: "production",
  })
  .when("github.event_name == 'push'")
  .permissions({ contents: "read" })
  .strategy({
    matrix: {
      node: ["18", "20", "22"],
    },
  })
  .outputs({
    version: "${{ steps.version.outputs.value }}",
  })
  .continueOnError(false)
  .timeoutMinutes(30)
  .addStep(checkout({}))
  .addStep({ run: "npm test" });
```

---

### `CompositeAction`

재사용 가능한 컴포지트 액션을 만듭니다.

```typescript
class CompositeAction {
  constructor(config: CompositeActionConfig)
  addStep(step: Step): this
  build(filename: string): void
}
```

#### `CompositeActionConfig`

```typescript
interface CompositeActionConfig {
  name: string
  description: string
  inputs?: Record<string, ActionInput>
  outputs?: Record<string, ActionOutput>
}
```

#### 예제

```ts twoslash
// @noErrors
// @filename: workflows/example.ts
// ---cut---
import { CompositeAction } from "../generated/index.js";

const setupEnv = new CompositeAction({
  name: "환경 설정",
  description: "Node.js 설정 및 의존성 설치",
  inputs: {
    "node-version": {
      description: "Node.js 버전",
      required: true,
      default: "20",
    },
  },
})
  .addStep(checkout({}))
  .addStep(setupNode({
    with: {
      "node-version": "${{ inputs.node-version }}",
    },
  }))
  .addStep({
    run: "npm ci",
  });

setupEnv.build("setup-env");
```

생성된 `action.yml`은 다음과 같이 사용할 수 있습니다:

```typescript
// 다른 워크플로우에서
const setupEnv = getAction("./setup-env");

const job = new Job("ubuntu-latest")
  .addStep(setupEnv({
    with: {
      "node-version": "20",
    },
  }));
```

---

### `JavaScriptAction`

Node.js 기반 GitHub Actions를 만듭니다.

```typescript
class JavaScriptAction {
  constructor(config: JavaScriptActionConfig, runs: JavaScriptActionRuns)
  build(filename: string): void
}
```

#### `JavaScriptActionConfig`

```typescript
interface JavaScriptActionConfig {
  name: string
  description: string
  inputs?: Record<string, ActionInputDefinition>
  outputs?: Record<string, ActionOutputDefinition>
}
```

#### `JavaScriptActionRuns`

```typescript
interface JavaScriptActionRuns {
  using: 'node12' | 'node16' | 'node20'
  main: string
  pre?: string
  post?: string
  'pre-if'?: string
  'post-if'?: string
}
```

#### 예제

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { JavaScriptAction } from "../generated/index.js";

const action = new JavaScriptAction(
  {
    name: "Hello World",
    description: "인사하고 시간을 기록합니다",
    inputs: {
      "who-to-greet": {
        description: "인사할 대상",
        required: true,
        default: "World",
      },
    },
    outputs: {
      time: {
        description: "인사한 시간",
      },
    },
  },
  {
    using: "node20",
    main: "dist/index.js",
  },
);

action.build("hello-world");
```

`.github/actions/hello-world/action.yml`이 생성됩니다.

`CallAction.from()`으로 워크플로우에서 참조할 수 있습니다:

```typescript
const step = {
  id: "hello",
  ...CallAction.from(action).toJSON(),
  with: { "who-to-greet": "Mona the Octocat" },
};
```

---

### `CompositeJob`

TypeScript 클래스 상속을 통해 재사용 가능한 작업 템플릿을 만듭니다. `CompositeJob`은 `Job`을 상속하므로 모든 `Job` 메서드를 사용할 수 있습니다.

```typescript
class CompositeJob extends Job {
  constructor(runsOn: string | string[], options?: Partial<JobDefinition>)
}
```

`Job`과 달리 `CompositeJob`은 `extends`로 서브클래싱하여 도메인별 파라미터화된 job 템플릿을 만들 때 사용합니다. YAML 출력은 일반 `Job`과 동일합니다.

::: tip CompositeJob vs Job
일회성 job에는 `Job`을 직접 사용하세요. 공통 패턴을 파라미터와 함께 캡슐화한 **재사용 가능한 클래스**를 만들 때 `CompositeJob`을 사용하세요.
:::

#### 예제

```ts twoslash
// @noErrors
// @filename: workflows/example.ts
// ---cut---
import { CompositeJob } from "../generated/index.js";

// 재사용 가능한 작업 템플릿 정의
class NodeTestJob extends CompositeJob {
  constructor(nodeVersion: string) {
    super("ubuntu-latest");

    this
      .addStep(checkout({}))
      .addStep(setupNode({
        with: { "node-version": nodeVersion },
      }))
      .addStep({ run: "npm ci" })
      .addStep({ run: "npm test" });
  }
}

// 워크플로우에서 사용
const workflow = new Workflow({
  name: "테스트 매트릭스",
  on: { push: { branches: ["main"] } },
})
  .addJob("test-node-18", new NodeTestJob("18"))
  .addJob("test-node-20", new NodeTestJob("20"))
  .addJob("test-node-22", new NodeTestJob("22"));
```

더 복잡한 재사용 가능한 작업도 만들 수 있습니다:

```typescript
class DeployJob extends CompositeJob {
  constructor(environment: "staging" | "production") {
    super("ubuntu-latest");

    this
      .env({
        ENVIRONMENT: environment,
        API_URL: environment === "production"
          ? "https://api.example.com"
          : "https://staging.api.example.com",
      })
      .addStep(checkout({}))
      .addStep(setupNode({ with: { "node-version": "20" } }))
      .addStep({
        name: "배포",
        run: `npm run deploy:${environment}`,
        env: {
          DEPLOY_TOKEN: "${{ secrets.DEPLOY_TOKEN }}",
        },
      });
  }
}

// 워크플로우에서 사용
const workflow = new Workflow({
  name: "배포",
  on: { push: { tags: ["v*"] } },
})
  .addJob("deploy-staging", new DeployJob("staging"))
  .addJob("deploy-production", new DeployJob("production").needs(["deploy-staging"]));
```

---

### `CallJob`

다른 리포지토리나 파일에 정의된 [재사용 가능한 워크플로우](https://docs.github.com/en/actions/using-workflows/reusing-workflows)를 호출합니다. `Job`과 달리 `CallJob`은 `steps`가 없으며, `uses`를 통해 참조된 워크플로우에 위임합니다.

```typescript
class CallJob {
  constructor(uses: string)
  with(inputs: Record<string, unknown>): this
  secrets(s: Record<string, unknown> | 'inherit'): this
  needs(deps: string | string[]): this
  when(condition: string): this
  permissions(perms: Permissions): this
  toJSON(): object
}
```

| 메서드 | 설명 |
|--------|------|
| `with(inputs)` | 재사용 워크플로우에 입력값을 전달합니다. |
| `secrets(s)` | 시크릿을 명시적으로 전달하거나, `'inherit'`로 모든 시크릿을 전달합니다. |
| `needs(deps)` | job 의존성을 설정합니다. |
| `when(condition)` | job의 `if` 조건을 설정합니다. |
| `permissions(perms)` | job 수준의 권한을 설정합니다. |

#### 예제

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { CallJob, Workflow } from "../generated/index.js";

const deploy = new CallJob("octo-org/deploy/.github/workflows/deploy.yml@main")
  .with({ environment: "production" })
  .secrets("inherit")
  .needs(["build"]);

const workflow = new Workflow({
  name: "Release",
  on: { push: { tags: ["v*"] } },
})
  .addJob("deploy", deploy);

workflow.build("release");
```

생성되는 YAML:

```yaml
jobs:
  deploy:
    uses: octo-org/deploy/.github/workflows/deploy.yml@main
    with:
      environment: production
    secrets: inherit
    needs:
      - build
```

---

### `CallAction`

gaji로 빌드한 로컬 composite 또는 JavaScript 액션을 job의 스텝으로 참조합니다.

```typescript
class CallAction {
  constructor(uses: string)
  static from(action: CompositeAction | JavaScriptAction): CallAction
  toJSON(): Step
}
```

| 메서드 | 설명 |
|--------|------|
| `from(action)` | `CompositeAction` 또는 `JavaScriptAction` 인스턴스로부터 `CallAction`을 생성합니다. `.github/actions/<id>` 경로를 자동으로 해석합니다. |

#### 예제

```ts twoslash
// @filename: workflows/example.ts
// ---cut---
import { CompositeAction, CallAction, Job } from "../generated/index.js";

const setupEnv = new CompositeAction({
  name: "Setup",
  description: "환경 설정",
});
setupEnv.build("setup-env");

const job = new Job("ubuntu-latest")
  .addStep({
    ...CallAction.from(setupEnv).toJSON(),
    with: { "node-version": "20" },
  });
```

---

## 함수

### `getAction()`

타입이 지정된 액션 함수를 가져옵니다.

```typescript
function getAction<T extends string>(
  ref: T
): (config?: ActionConfig) => Step
```

#### 예제

```typescript
const checkout = getAction("actions/checkout@v5");
const setupNode = getAction("actions/setup-node@v4");

// 완전한 타입 안전성으로 사용
const step = checkout({
  name: "코드 체크아웃",
  with: {
    // ✅ 자동완성 사용 가능!
    repository: "owner/repo",
    ref: "main",
    "fetch-depth": 0,
  },
});
```

---

## 타입 정의

### `Step`

워크플로우 스텝입니다.

```typescript
interface Step {
  name?: string
  id?: string
  if?: string
  uses?: string
  with?: Record<string, string | number | boolean>
  run?: string
  env?: Record<string, string>
  "continue-on-error"?: boolean
  "timeout-minutes"?: number
}
```

### `WorkflowTriggers`

워크플로우 트리거 이벤트입니다.

```typescript
interface WorkflowTriggers {
  push?: PushTrigger
  pull_request?: PullRequestTrigger
  schedule?: ScheduleTrigger[]
  workflow_dispatch?: WorkflowDispatchTrigger
  [key: string]: any
}

interface PushTrigger {
  branches?: string[]
  tags?: string[]
  paths?: string[]
}

interface PullRequestTrigger {
  branches?: string[]
  types?: string[]
  paths?: string[]
}

interface ScheduleTrigger {
  cron: string
}
```

### `JobStrategy`

작업 매트릭스 전략입니다.

```typescript
interface JobStrategy {
  matrix?: {
    [key: string]: string[] | number[]
  }
  "fail-fast"?: boolean
  "max-parallel"?: number
}
```

### `ActionInput`

액션 입력 정의 (CompositeAction용)입니다.

```typescript
interface ActionInput {
  description: string
  required?: boolean
  default?: string
}
```

### `ActionOutput`

액션 출력 정의 (CompositeAction용)입니다.

```typescript
interface ActionOutput {
  description: string
  value: string
}
```

## 전체 예제

### 완전한 워크플로우

```typescript
import { getAction, Job, Workflow } from "../generated/index.js";

const checkout = getAction("actions/checkout@v5");
const setupNode = getAction("actions/setup-node@v4");

const test = new Job("ubuntu-latest")
  .addStep(checkout({}))
  .addStep(setupNode({ with: { "node-version": "20" } }))
  .addStep({ run: "npm ci" })
  .addStep({ run: "npm test" });

const build = new Job("ubuntu-latest")
  .needs(["test"])
  .addStep(checkout({}))
  .addStep(setupNode({ with: { "node-version": "20" } }))
  .addStep({ run: "npm ci" })
  .addStep({ run: "npm run build" });

const workflow = new Workflow({
  name: "CI",
  on: {
    push: { branches: ["main"] },
    pull_request: { branches: ["main"] },
  },
})
  .addJob("test", test)
  .addJob("build", build);

workflow.build("ci");
```

## 다음 단계

- [예제]/ko/examples/simple-ci 보기
- [액션]./actions.md에 대해 알아보기