-
Notifications
You must be signed in to change notification settings - Fork 514
Expand file tree
/
Copy pathio.ts
More file actions
373 lines (312 loc) · 11.2 KB
/
Copy pathio.ts
File metadata and controls
373 lines (312 loc) · 11.2 KB
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
import { Effect, FileSystem, Path, Schema } from "effect";
import * as SmolToml from "smol-toml";
import { ProjectConfigSchema, type ProjectConfig } from "./base.ts";
import { ProjectConfigParseError } from "./errors.ts";
import { interpolateEnvReferencesAgainstSchema } from "./lib/env.ts";
import { findProjectPaths } from "./paths.ts";
import { loadProjectEnvironment } from "./project.ts";
const projectConfigSchemaKey = "$schema";
export type ConfigFormat = "json" | "toml";
export interface LoadedProjectConfig {
readonly path: string;
readonly format: ConfigFormat;
readonly config: ProjectConfig;
readonly schemaRef?: string;
readonly ignoredPaths: ReadonlyArray<string>;
}
export interface SaveProjectConfigOptions {
readonly cwd: string;
readonly config: ProjectConfig;
readonly format?: ConfigFormat;
readonly schemaRef?: string;
}
const decodeProjectConfig = Schema.decodeUnknownSync(ProjectConfigSchema);
const encodeProjectConfig = Schema.encodeSync(ProjectConfigSchema);
const defaultEncodedProjectConfig = encodeProjectConfig(decodeProjectConfig({}));
const defaultEncodedFunctionConfig = {
enabled: true,
verify_jwt: true,
import_map: "",
entrypoint: "",
static_files: [],
env: {},
};
function configJsonPathWith(path: Path.Path, cwd: string): string {
return path.join(cwd, "supabase", "config.json");
}
function configTomlPathWith(path: Path.Path, cwd: string): string {
return path.join(cwd, "supabase", "config.toml");
}
function siblingConfigPathWith(path: Path.Path, cwd: string, format: ConfigFormat): string {
return format === "json" ? configTomlPathWith(path, cwd) : configJsonPathWith(path, cwd);
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isEqualValue(left: unknown, right: unknown): boolean {
if (Array.isArray(left) && Array.isArray(right)) {
if (left.length !== right.length) {
return false;
}
for (let index = 0; index < left.length; index += 1) {
if (!isEqualValue(left[index], right[index])) {
return false;
}
}
return true;
}
if (isObject(left) && isObject(right)) {
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) {
return false;
}
for (const key of leftKeys) {
if (!(key in right) || !isEqualValue(left[key], right[key])) {
return false;
}
}
return true;
}
return Object.is(left, right);
}
function stripDefaults(value: unknown, defaults: unknown): unknown {
if (defaults === undefined) {
return value;
}
if (Array.isArray(value)) {
return isEqualValue(value, defaults) ? undefined : value;
}
if (isObject(value)) {
const defaultObject = isObject(defaults) ? defaults : {};
const result: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
const stripped = stripDefaults(child, defaultObject[key]);
if (stripped !== undefined) {
result[key] = stripped;
}
}
return Object.keys(result).length === 0 ? undefined : result;
}
return isEqualValue(value, defaults) ? undefined : value;
}
function stripFunctionRecordDefaults(value: unknown): unknown {
if (!isObject(value)) {
return value;
}
const functionsValue = value.functions;
if (!isObject(functionsValue)) {
return value;
}
const functions: Record<string, unknown> = {};
for (const [name, functionConfig] of Object.entries(functionsValue)) {
functions[name] = stripDefaults(functionConfig, defaultEncodedFunctionConfig) ?? {};
}
return { ...value, functions };
}
function encodeMinimalProjectConfig(config: ProjectConfig): Record<string, unknown> {
const encoded = stripFunctionRecordDefaults(encodeProjectConfig(config));
const stripped = stripDefaults(encoded, defaultEncodedProjectConfig);
return isObject(stripped) ? stripped : {};
}
function toConfigDocument(
config: ProjectConfig,
schemaRef: string | undefined,
): Record<string, unknown> {
const encoded = encodeMinimalProjectConfig(config);
return schemaRef === undefined ? encoded : { [projectConfigSchemaKey]: schemaRef, ...encoded };
}
function parseProjectConfigDocument(content: string, format: ConfigFormat): unknown {
return format === "json" ? JSON.parse(content) : SmolToml.parse(content);
}
function normalizeDeprecatedSMTPSections(document: unknown): unknown {
if (!isObject(document)) {
return document;
}
const normalized = { ...document };
if ("inbucket" in normalized) {
if (!("local_smtp" in normalized)) {
normalized.local_smtp = normalized.inbucket;
}
delete normalized.inbucket;
}
if (isObject(normalized.remotes)) {
normalized.remotes = Object.fromEntries(
Object.entries(normalized.remotes).map(([name, remote]) => {
if (!isObject(remote) || !("inbucket" in remote)) {
return [name, remote];
}
const normalizedRemote = { ...remote };
if (!("local_smtp" in normalizedRemote)) {
normalizedRemote.local_smtp = normalizedRemote.inbucket;
}
delete normalizedRemote.inbucket;
return [name, normalizedRemote];
}),
);
}
return normalized;
}
function getSchemaRef(document: unknown): string | undefined {
if (!isObject(document)) {
return undefined;
}
const schemaRef = document[projectConfigSchemaKey];
return typeof schemaRef === "string" ? schemaRef : undefined;
}
function parseProjectConfig(
document: unknown,
format: ConfigFormat,
path: string,
): Effect.Effect<ProjectConfig, ProjectConfigParseError> {
return Effect.try({
try: () => decodeProjectConfig(document),
catch: (cause) => new ProjectConfigParseError({ path, format, cause }),
});
}
export const configJsonPath = Effect.fnUntraced(function* (cwd: string) {
const path = yield* Path.Path;
const project = yield* findProjectPaths(cwd);
return configJsonPathWith(path, project?.projectRoot ?? cwd);
});
export const configTomlPath = Effect.fnUntraced(function* (cwd: string) {
const path = yield* Path.Path;
const project = yield* findProjectPaths(cwd);
return configTomlPathWith(path, project?.projectRoot ?? cwd);
});
export function encodeProjectConfigToJson(config: ProjectConfig): string {
return encodeProjectConfigToJsonDocument(config, undefined);
}
export function encodeProjectConfigToToml(config: ProjectConfig): string {
return encodeProjectConfigToTomlDocument(config, undefined);
}
function encodeProjectConfigToJsonDocument(
config: ProjectConfig,
schemaRef: string | undefined,
): string {
return `${JSON.stringify(toConfigDocument(config, schemaRef), null, 2)}\n`;
}
function encodeProjectConfigToTomlDocument(
config: ProjectConfig,
schemaRef: string | undefined,
): string {
return `${SmolToml.stringify(toConfigDocument(config, schemaRef))}\n`;
}
export const loadProjectConfigFile = Effect.fnUntraced(function* (filePath: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const format = filePath.endsWith(".json") ? "json" : "toml";
const content = yield* fs.readFileString(filePath);
const document = yield* Effect.try({
try: () => parseProjectConfigDocument(content, format),
catch: (cause) => new ProjectConfigParseError({ path: filePath, format, cause }),
});
const normalized = normalizeDeprecatedSMTPSections(document);
// Substitute `env(VAR)` references against `.env`/`.env.local`/ambient env
// before schema decode. Required for numeric/boolean fields, which would
// otherwise crash the strict decoder with `Expected number` (CLI-1489).
// The config file lives at `<projectRoot>/supabase/config.{toml,json}`, so
// walking two directories up gives us the project root that
// `loadProjectEnvironment` expects.
const projectRoot = path.dirname(path.dirname(filePath));
const projectEnv = yield* loadProjectEnvironment({
cwd: projectRoot,
baseEnv: process.env,
});
const interpolated = interpolateEnvReferencesAgainstSchema(
normalized,
projectEnv?.values ?? {},
ProjectConfigSchema,
);
const config = yield* parseProjectConfig(interpolated, format, filePath);
return {
path: filePath,
format,
config,
schemaRef: getSchemaRef(document),
ignoredPaths: [],
} satisfies LoadedProjectConfig;
});
export const loadProjectConfig = Effect.fnUntraced(function* (cwd: string) {
const fs = yield* FileSystem.FileSystem;
const project = yield* findProjectPaths(cwd);
if (project === null) {
return null;
}
const jsonPath = project.configPath.endsWith(".json")
? project.configPath
: project.configPath.replace(/config\.toml$/, "config.json");
const tomlPath = project.configPath.endsWith(".toml")
? project.configPath
: project.configPath.replace(/config\.json$/, "config.toml");
if (yield* fs.exists(jsonPath)) {
const json = yield* loadProjectConfigFile(jsonPath);
return {
...json,
ignoredPaths: (yield* fs.exists(tomlPath)) ? [tomlPath] : [],
} satisfies LoadedProjectConfig;
}
if (yield* fs.exists(tomlPath)) {
return yield* loadProjectConfigFile(tomlPath);
}
return null;
});
const resolveSaveFormat = Effect.fnUntraced(function* (
cwd: string,
format: ConfigFormat | undefined,
) {
if (format !== undefined) {
return format;
}
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const jsonPath = configJsonPathWith(path, cwd);
const tomlPath = configTomlPathWith(path, cwd);
if (yield* fs.exists(jsonPath)) {
return "json" as const;
}
if (yield* fs.exists(tomlPath)) {
return "toml" as const;
}
return "json" as const;
});
function writeFileAtomic(
filePath: string,
content: string,
): Effect.Effect<void, never, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tmpPath = `${filePath}.tmp.${Date.now()}`;
yield* fs.writeFileString(tmpPath, content);
yield* fs.rename(tmpPath, filePath);
}).pipe(Effect.catchTag("PlatformError", (e) => Effect.die(e)));
}
export const saveProjectConfig = Effect.fnUntraced(function* (options: SaveProjectConfigOptions) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const project = yield* findProjectPaths(options.cwd);
const baseCwd = project?.projectRoot ?? options.cwd;
const format = yield* resolveSaveFormat(baseCwd, options.format);
const existingConfig =
options.schemaRef !== undefined || project === null ? null : yield* loadProjectConfig(baseCwd);
const schemaRef = options.schemaRef ?? existingConfig?.schemaRef;
const filePath =
format === "json" ? configJsonPathWith(path, baseCwd) : configTomlPathWith(path, baseCwd);
const siblingPath = siblingConfigPathWith(path, baseCwd, format);
const content =
format === "json"
? encodeProjectConfigToJsonDocument(options.config, schemaRef)
: encodeProjectConfigToTomlDocument(options.config, schemaRef);
yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
yield* writeFileAtomic(filePath, content);
if (yield* fs.exists(siblingPath)) {
yield* fs.remove(siblingPath);
}
return {
path: filePath,
format,
config: options.config,
schemaRef,
ignoredPaths: [],
} satisfies LoadedProjectConfig;
});