@cvr/linear 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,164 +1,153 @@
1
- import { Context, Effect, Layer, Option } from "effect";
2
- import { FileSystem, Path } from "@effect/platform";
1
+ import { parse } from "toml";
2
+ import { Config, Context, Effect, FileSystem, Layer, Option, Path, Redacted, Schema } from "effect";
3
3
  import { ConfigError, TokenNotFoundError } from "../lib/errors.js";
4
4
 
5
- // Config structure for .linear.toml
6
- export interface LinearConfig {
7
- readonly teamId?: string;
8
- readonly workspace?: string;
9
- readonly issueSort?: "manual" | "priority";
10
- }
5
+ export class LinearConfig extends Schema.Class<LinearConfig>("LinearConfig")({
6
+ teamId: Schema.optional(Schema.String),
7
+ }) {}
8
+
9
+ class LinearConfigFile extends Schema.Class<LinearConfigFile>("LinearConfigFile")({
10
+ team_id: Schema.optional(Schema.String),
11
+ }) {}
11
12
 
12
- export class ConfigService extends Context.Tag("@linear/ConfigService")<
13
+ export class ConfigService extends Context.Service<
13
14
  ConfigService,
14
15
  {
15
- readonly getToken: Effect.Effect<string, TokenNotFoundError | ConfigError>;
16
- readonly saveToken: (token: string) => Effect.Effect<void, ConfigError>;
16
+ readonly getToken: Effect.Effect<Redacted.Redacted<string>, TokenNotFoundError | ConfigError>;
17
+ readonly saveToken: (token: Redacted.Redacted<string>) => Effect.Effect<void, ConfigError>;
17
18
  readonly getConfig: Effect.Effect<LinearConfig, ConfigError>;
18
19
  }
19
- >() {
20
+ >()("@cvr/linear/services/Config/ConfigService") {
20
21
  static readonly layer = Layer.effect(
21
22
  ConfigService,
22
23
  Effect.gen(function* () {
23
24
  const fs = yield* FileSystem.FileSystem;
24
25
  const path = yield* Path.Path;
25
-
26
- const homeDir = process.env.HOME ?? "";
26
+ const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
27
+ const envToken = yield* Config.redacted("LINEAR_API_KEY").pipe(Config.option);
27
28
  const configDir = path.join(homeDir, ".config", "linear");
28
29
  const tokenPath = path.join(configDir, "token");
29
30
  const configPath = path.join(configDir, "config.toml");
30
31
 
31
- const ensureConfigDir = Effect.gen(function* () {
32
- const exists = yield* fs.exists(configDir);
33
- if (!exists) {
34
- yield* fs.makeDirectory(configDir, { recursive: true });
35
- }
36
- }).pipe(
37
- Effect.catchAll((e) =>
38
- ConfigError.make({ message: `Failed to create config directory: ${e}` }),
32
+ const ensureConfigDir = fs
33
+ .makeDirectory(configDir, { recursive: true })
34
+ .pipe(
35
+ Effect.mapError((error) =>
36
+ ConfigError.make({ message: `Failed to create config directory: ${error}` }),
37
+ ),
38
+ );
39
+
40
+ const getToken = readTokenFile(fs, tokenPath).pipe(
41
+ Effect.flatMap(
42
+ Option.match({
43
+ onSome: Effect.succeed,
44
+ onNone: () =>
45
+ Option.match(envToken, {
46
+ onSome: Effect.succeed,
47
+ onNone: () => TokenNotFoundError.default,
48
+ }),
49
+ }),
39
50
  ),
51
+ Effect.withSpan("ConfigService.getToken"),
40
52
  );
41
53
 
42
- const getToken = Effect.gen(function* () {
43
- // 1. Try config file first
44
- const fileToken = yield* Effect.tryPromise({
45
- try: () => Bun.file(tokenPath).text(),
46
- catch: () => null,
47
- }).pipe(Effect.option);
48
-
49
- if (Option.isSome(fileToken) && fileToken.value.trim()) {
50
- return fileToken.value.trim();
51
- }
52
-
53
- // 2. Try env var
54
- const envToken = process.env.LINEAR_API_KEY;
55
- if (envToken) {
56
- return envToken;
57
- }
58
-
59
- // 3. Error
60
- return yield* TokenNotFoundError.default;
61
- }).pipe(Effect.withSpan("ConfigService.getToken"));
62
-
63
- const saveToken = (token: string) =>
64
- Effect.gen(function* () {
65
- yield* ensureConfigDir;
66
- yield* Effect.tryPromise({
67
- try: () => Bun.write(tokenPath, token.trim()),
68
- catch: (e) => ConfigError.make({ message: `Failed to save token: ${e}` }),
69
- });
70
- }).pipe(Effect.withSpan("ConfigService.saveToken"));
54
+ const saveToken = Effect.fn("ConfigService.saveToken")(function* (
55
+ token: Redacted.Redacted<string>,
56
+ ) {
57
+ yield* ensureConfigDir;
58
+ yield* fs
59
+ .writeFileString(tokenPath, Redacted.value(token).trim(), { mode: 0o600 })
60
+ .pipe(
61
+ Effect.mapError((error) =>
62
+ ConfigError.make({ message: `Failed to save token: ${error}` }),
63
+ ),
64
+ );
65
+ });
71
66
 
72
67
  const getConfig = Effect.gen(function* () {
73
- // Try project config first (.linear.toml in cwd or git root)
74
- const projectConfig = yield* loadProjectConfig(path);
75
- if (Option.isSome(projectConfig)) {
76
- return projectConfig.value;
68
+ const cwd = path.resolve(".");
69
+ for (const candidate of [path.join(cwd, ".linear.toml"), path.join(cwd, "linear.toml")]) {
70
+ const projectConfig = yield* readConfigFile(fs, candidate);
71
+ if (Option.isSome(projectConfig)) {
72
+ return projectConfig.value;
73
+ }
77
74
  }
78
75
 
79
- // Fall back to global config
80
- const globalConfig = yield* loadTomlConfig(configPath);
81
- return globalConfig;
76
+ return Option.getOrElse(yield* readConfigFile(fs, configPath), () => new LinearConfig({}));
82
77
  }).pipe(Effect.withSpan("ConfigService.getConfig"));
83
78
 
84
- return ConfigService.of({
85
- getToken,
86
- saveToken,
87
- getConfig,
88
- });
79
+ return ConfigService.of({ getToken, saveToken, getConfig });
89
80
  }),
90
81
  );
91
82
 
92
- static readonly testLayer = (options?: { token?: string; config?: LinearConfig }) =>
83
+ static readonly layerTest = (options?: { token?: string; config?: LinearConfig }) =>
93
84
  Layer.succeed(ConfigService, {
94
85
  getToken:
95
- options?.token != null
96
- ? Effect.succeed(options.token)
97
- : Effect.fail(TokenNotFoundError.default),
98
- saveToken: (_token) => Effect.void,
99
- getConfig: Effect.succeed(options?.config ?? {}),
86
+ options?.token === undefined
87
+ ? Effect.fail(TokenNotFoundError.default)
88
+ : Effect.succeed(Redacted.make(options.token)),
89
+ saveToken: () => Effect.void,
90
+ getConfig: Effect.succeed(options?.config ?? new LinearConfig({})),
100
91
  });
101
92
  }
102
93
 
103
- const loadTomlConfig = Effect.fn("ConfigService.loadTomlConfig")((filePath: string) =>
104
- Effect.tryPromise({
105
- try: async () => {
106
- const file = Bun.file(filePath);
107
- const exists = await file.exists();
108
- if (!exists) return {};
109
-
110
- const content = await file.text();
111
- // Simple TOML parsing for our use case
112
- let teamId: string | undefined;
113
- let workspace: string | undefined;
114
- let issueSort: "manual" | "priority" | undefined;
115
-
116
- for (const line of content.split("\n")) {
117
- const trimmed = line.trim();
118
- if (trimmed.startsWith("#") || !trimmed.includes("=")) continue;
119
-
120
- const [key, ...rest] = trimmed.split("=");
121
- const value = rest
122
- .join("=")
123
- .trim()
124
- .replace(/^["']|["']$/g, "");
125
-
126
- switch (key.trim()) {
127
- case "team_id":
128
- teamId = value;
129
- break;
130
- case "workspace":
131
- workspace = value;
132
- break;
133
- case "issue_sort":
134
- if (value === "manual" || value === "priority") {
135
- issueSort = value;
136
- }
137
- break;
138
- }
139
- }
140
- return { teamId, workspace, issueSort } as LinearConfig;
141
- },
142
- catch: (e) => ConfigError.make({ message: `Failed to load config: ${e}` }),
143
- }),
144
- );
145
-
146
- const loadProjectConfig = Effect.fn("ConfigService.loadProjectConfig")((pathService: Path.Path) =>
147
- Effect.gen(function* () {
148
- const cwd = process.cwd();
149
- const candidates = [
150
- pathService.join(cwd, ".linear.toml"),
151
- pathService.join(cwd, "linear.toml"),
152
- ];
153
-
154
- for (const candidate of candidates) {
155
- const exists = yield* Effect.promise(() => Bun.file(candidate).exists());
156
- if (exists) {
157
- const config = yield* loadTomlConfig(candidate);
158
- return Option.some(config);
159
- }
160
- }
94
+ const readTokenFile = (
95
+ fs: Context.Service.Shape<typeof FileSystem.FileSystem>,
96
+ tokenPath: string,
97
+ ): Effect.Effect<Option.Option<Redacted.Redacted<string>>, ConfigError> =>
98
+ fs.exists(tokenPath).pipe(
99
+ Effect.mapError((error) =>
100
+ ConfigError.make({ message: `Failed to inspect token file: ${error}` }),
101
+ ),
102
+ Effect.flatMap((exists) =>
103
+ exists
104
+ ? fs.readFileString(tokenPath).pipe(
105
+ Effect.mapError((error) =>
106
+ ConfigError.make({ message: `Failed to read token file: ${error}` }),
107
+ ),
108
+ Effect.map((token) => token.trim()),
109
+ Effect.map((token) =>
110
+ token.length === 0 ? Option.none() : Option.some(Redacted.make(token)),
111
+ ),
112
+ )
113
+ : Effect.succeed(Option.none()),
114
+ ),
115
+ );
161
116
 
117
+ const readConfigFile = Effect.fn("ConfigService.readConfigFile")(function* (
118
+ fs: Context.Service.Shape<typeof FileSystem.FileSystem>,
119
+ filePath: string,
120
+ ): Effect.fn.Return<Option.Option<LinearConfig>, ConfigError> {
121
+ const exists = yield* fs
122
+ .exists(filePath)
123
+ .pipe(
124
+ Effect.mapError((error) =>
125
+ ConfigError.make({ message: `Failed to inspect ${filePath}: ${error}` }),
126
+ ),
127
+ );
128
+ if (!exists) {
162
129
  return Option.none();
163
- }),
164
- );
130
+ }
131
+
132
+ const content = yield* fs
133
+ .readFileString(filePath)
134
+ .pipe(
135
+ Effect.mapError((error) =>
136
+ ConfigError.make({ message: `Failed to read ${filePath}: ${error}` }),
137
+ ),
138
+ );
139
+ const parsed = yield* Effect.try({
140
+ try: () => parse(content),
141
+ catch: (error) => ConfigError.make({ message: `Failed to parse ${filePath}: ${error}` }),
142
+ });
143
+ const decoded = yield* Schema.decodeUnknownEffect(LinearConfigFile)(parsed).pipe(
144
+ Effect.mapError((error) =>
145
+ ConfigError.make({ message: `Invalid Linear config in ${filePath}: ${error}` }),
146
+ ),
147
+ );
148
+ return Option.some(
149
+ new LinearConfig({
150
+ teamId: decoded.team_id,
151
+ }),
152
+ );
153
+ });