@dbt-tools/web 0.5.0 → 0.5.4

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,144 +1,66 @@
1
1
  #!/usr/bin/env node
2
- import { execFile } from "node:child_process";
3
2
  import fs from "node:fs";
4
3
  import http from "node:http";
5
4
  import path from "node:path";
6
5
  import { fileURLToPath } from "node:url";
7
6
  import fs$1 from "node:fs/promises";
8
- import { DBT_MANIFEST_JSON, DBT_RUN_RESULTS_JSON, getDbtToolsRemoteSourceConfigFromEnv, getDbtToolsTargetDirFromEnv, isDbtToolsDebugEnabled } from "@dbt-tools/core";
9
- import { GetObjectCommand, ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
10
- import { Storage } from "@google-cloud/storage";
11
- //#region src/artifact-source/prefix.ts
12
- /** Trim leading/trailing slashes for object-store key prefix handling. */
13
- function normalizeArtifactPrefix(prefix) {
14
- return prefix.replace(/^\/+|\/+$/g, "");
15
- }
16
- //#endregion
7
+ import { ARTIFACT_RUN_ID_CURRENT, DBT_CATALOG_JSON, DBT_MANIFEST_JSON, DBT_RUN_RESULTS_JSON, DBT_SOURCES_JSON, discoverArtifactCandidates, discoverLocalArtifactRunPaths, getDbtToolsRemoteSourceConfigFromEnv, getDbtToolsTargetDirFromEnv, isDbtToolsDebugEnabled, joinObjectStorageKey, mergeRemoteSourceConfigWithParsedLocation, normalizeArtifactPrefix, normalizeArtifactPrefix as normalizeArtifactPrefix$1, parseArtifactSourceLocation, remoteKeysToListedArtifacts } from "@dbt-tools/core";
8
+ import { createRemoteObjectStoreClient } from "@dbt-tools/core/artifact-io";
17
9
  //#region src/artifact-source/discovery.ts
18
- function toRelativeKey(key, prefix) {
19
- const normalizedKey = key.replace(/^\/+/, "");
20
- const normalizedPrefix = normalizeArtifactPrefix(prefix);
21
- if (normalizedPrefix === "") return normalizedKey;
22
- if (normalizedKey === normalizedPrefix) return "";
23
- if (normalizedKey.startsWith(`${normalizedPrefix}/`)) return normalizedKey.slice(normalizedPrefix.length + 1);
24
- return null;
25
- }
26
- function runIdForKey(relativeKey) {
27
- const dir = path.posix.dirname(relativeKey);
28
- return dir === "." ? "current" : dir;
10
+ function mapCoreCandidatesToResolvedRuns(disc, resolveKey) {
11
+ return disc.candidates.map((c) => ({
12
+ runId: c.runId,
13
+ manifestKey: resolveKey(c.manifestRelative),
14
+ runResultsKey: resolveKey(c.runResultsRelative),
15
+ ...c.catalogRelative != null ? { catalogKey: resolveKey(c.catalogRelative) } : {},
16
+ ...c.sourcesRelative != null ? { sourcesKey: resolveKey(c.sourcesRelative) } : {},
17
+ updatedAtMs: c.updatedAtMs,
18
+ versionToken: c.versionToken
19
+ }));
20
+ }
21
+ async function discoverLocalResolvedArtifactRuns(resolvedDirAbs) {
22
+ const { discovery, runs: paths } = await discoverLocalArtifactRunPaths(resolvedDirAbs);
23
+ if (!discovery.ok) return {
24
+ runs: [],
25
+ discovery
26
+ };
27
+ return {
28
+ runs: paths.map((r) => ({
29
+ runId: r.runId,
30
+ manifestKey: r.manifestKey,
31
+ runResultsKey: r.runResultsKey,
32
+ ...r.catalogKey != null ? { catalogKey: r.catalogKey } : {},
33
+ ...r.sourcesKey != null ? { sourcesKey: r.sourcesKey } : {},
34
+ updatedAtMs: r.updatedAtMs,
35
+ versionToken: r.versionToken
36
+ })),
37
+ discovery
38
+ };
29
39
  }
30
- function versionTokenForKeys(parts) {
31
- return parts.map((part) => [
32
- part.key,
33
- part.updatedAtMs,
34
- part.etag ?? "",
35
- part.generation ?? ""
36
- ].join(":")).join("|");
40
+ function discoverRemoteArtifactDiscovery(objects, prefix) {
41
+ return discoverArtifactCandidates(remoteKeysToListedArtifacts(objects, prefix));
37
42
  }
38
43
  function discoverLatestArtifactRuns(objects, prefix) {
39
- const grouped = /* @__PURE__ */ new Map();
40
- for (const object of objects) {
41
- const relativeKey = toRelativeKey(object.key, prefix);
42
- if (relativeKey == null) continue;
43
- const fileName = path.posix.basename(relativeKey);
44
- if (fileName !== DBT_MANIFEST_JSON && fileName !== DBT_RUN_RESULTS_JSON) continue;
45
- const runId = runIdForKey(relativeKey);
46
- const current = grouped.get(runId) ?? {};
47
- if (fileName === DBT_MANIFEST_JSON) current.manifest = object;
48
- if (fileName === DBT_RUN_RESULTS_JSON) current.runResults = object;
49
- grouped.set(runId, current);
50
- }
51
- return [...grouped.entries()].flatMap(([runId, parts]) => {
52
- if (parts.manifest == null || parts.runResults == null) return [];
53
- return [{
54
- runId,
55
- manifestKey: parts.manifest.key,
56
- runResultsKey: parts.runResults.key,
57
- updatedAtMs: Math.max(parts.manifest.updatedAtMs, parts.runResults.updatedAtMs),
58
- versionToken: versionTokenForKeys([parts.manifest, parts.runResults])
59
- }];
60
- }).sort((left, right) => {
61
- if (right.updatedAtMs !== left.updatedAtMs) return right.updatedAtMs - left.updatedAtMs;
62
- return right.runId.localeCompare(left.runId);
63
- });
44
+ const disc = discoverRemoteArtifactDiscovery(objects, prefix);
45
+ if (!disc.ok) return [];
46
+ const normPrefix = normalizeArtifactPrefix(prefix);
47
+ return mapCoreCandidatesToResolvedRuns(disc, (rel) => joinObjectStorageKey(normPrefix, rel));
64
48
  }
65
49
  function toRemoteArtifactRun(provider, run) {
66
50
  return {
67
51
  runId: run.runId,
68
- label: run.runId === "current" ? `${provider.toUpperCase()} current` : `${provider.toUpperCase()} ${run.runId}`,
52
+ label: run.runId === ARTIFACT_RUN_ID_CURRENT ? `${provider.toUpperCase()} current` : `${provider.toUpperCase()} ${run.runId}`,
69
53
  updatedAtMs: run.updatedAtMs,
70
54
  versionToken: run.versionToken
71
55
  };
72
56
  }
73
- //#endregion
74
- //#region src/artifact-source/remoteObjectStore.ts
75
- var S3RemoteObjectStoreClient = class {
76
- client;
77
- constructor(config) {
78
- this.client = new S3Client({
79
- region: config.region,
80
- endpoint: config.endpoint,
81
- forcePathStyle: config.forcePathStyle
82
- });
83
- }
84
- async listObjects(bucket, prefix) {
85
- const results = [];
86
- let continuationToken;
87
- do {
88
- const response = await this.client.send(new ListObjectsV2Command({
89
- Bucket: bucket,
90
- Prefix: prefix === "" ? void 0 : `${prefix}/`,
91
- ContinuationToken: continuationToken
92
- }));
93
- for (const object of response.Contents ?? []) {
94
- if (!object.Key || !object.LastModified) continue;
95
- results.push({
96
- key: object.Key,
97
- updatedAtMs: object.LastModified.getTime(),
98
- etag: object.ETag ?? void 0
99
- });
100
- }
101
- continuationToken = response.IsTruncated ? response.NextContinuationToken : void 0;
102
- } while (continuationToken);
103
- return results;
104
- }
105
- async readObjectBytes(bucket, key) {
106
- const bytes = await (await this.client.send(new GetObjectCommand({
107
- Bucket: bucket,
108
- Key: key
109
- }))).Body?.transformToByteArray();
110
- if (bytes == null) throw new Error(`Missing S3 object body for ${key}`);
111
- return bytes;
112
- }
113
- };
114
- var GcsRemoteObjectStoreClient = class {
115
- storage;
116
- constructor(config) {
117
- this.storage = new Storage({ projectId: config.projectId });
118
- }
119
- async listObjects(bucket, prefix) {
120
- const [files] = await this.storage.bucket(bucket).getFiles({
121
- prefix: prefix === "" ? void 0 : `${prefix}/`,
122
- autoPaginate: true
123
- });
124
- return files.flatMap((file) => {
125
- const updated = file.metadata.updated;
126
- if (!updated) return [];
127
- return [{
128
- key: file.name,
129
- updatedAtMs: new Date(updated).getTime(),
130
- etag: file.metadata.etag,
131
- generation: file.metadata.generation == null ? void 0 : String(file.metadata.generation)
132
- }];
133
- });
134
- }
135
- async readObjectBytes(bucket, key) {
136
- const [bytes] = await this.storage.bucket(bucket).file(key).download();
137
- return bytes;
138
- }
139
- };
140
- function createRemoteObjectStoreClient(config) {
141
- return config.provider === "s3" ? new S3RemoteObjectStoreClient(config) : new GcsRemoteObjectStoreClient(config);
57
+ function toLocalManagedArtifactRun(run) {
58
+ return {
59
+ runId: run.runId,
60
+ label: run.runId === ARTIFACT_RUN_ID_CURRENT ? "Local (root)" : `Local (${run.runId})`,
61
+ updatedAtMs: run.updatedAtMs,
62
+ versionToken: run.versionToken
63
+ };
142
64
  }
143
65
  //#endregion
144
66
  //#region src/artifact-source/resolveLocalTargetDir.ts
@@ -150,12 +72,12 @@ function resolveLocalArtifactTargetDirFromEnv(cwd, rawTargetDir) {
150
72
  }
151
73
  //#endregion
152
74
  //#region src/artifact-source/sourceService.ts
153
- /** Node (Vite dev) service: local target dir vs remote S3/GCS; drives middleware routes. */
75
+ /** Node (Vite dev) service: configurable local path or remote S3/GCS; drives middleware routes. */
154
76
  function debugLog(...args) {
155
77
  if (isDbtToolsDebugEnabled()) console.log("[artifact-source]", ...args);
156
78
  }
157
- function toLocationLabel(provider, bucket, prefix) {
158
- return `${provider.toUpperCase()} ${bucket}/${prefix}`;
79
+ function toRemoteLocationLabel(provider, bucket, prefix) {
80
+ return `${provider.toUpperCase()} ${bucket}/${normalizeArtifactPrefix$1(prefix)}`;
159
81
  }
160
82
  function toArtifactSourceStatus(status) {
161
83
  return {
@@ -163,137 +85,331 @@ function toArtifactSourceStatus(status) {
163
85
  checkedAtMs: Date.now()
164
86
  };
165
87
  }
166
- var LocalArtifactSourceAdapter = class {
167
- constructor(targetDir) {
168
- this.targetDir = targetDir;
88
+ function runToUiRow(mode, provider, run) {
89
+ if (mode === "remote" && provider != null) return toRemoteArtifactRun(provider, run);
90
+ return toLocalManagedArtifactRun(run);
91
+ }
92
+ function missingOptionalFromRun(run) {
93
+ return {
94
+ missingCatalog: run.catalogKey == null,
95
+ missingSources: run.sourcesKey == null
96
+ };
97
+ }
98
+ var ArtifactSourceService = class {
99
+ cwd;
100
+ seedFromEnv;
101
+ delegatedAdapter = null;
102
+ initPromise = null;
103
+ mode = "none";
104
+ localDir = null;
105
+ locationDisplay = null;
106
+ sourceKind = null;
107
+ remoteConfig = null;
108
+ remoteClient = null;
109
+ remoteProvider = null;
110
+ runs = [];
111
+ discoveryResult = null;
112
+ selectedRunId = null;
113
+ constructor(options = {}) {
114
+ this.cwd = options.cwd ?? process.cwd();
115
+ this.seedFromEnv = options.seedFromEnv !== false;
116
+ if (options.adapter !== void 0) {
117
+ this.delegatedAdapter = options.adapter;
118
+ return;
119
+ }
120
+ if (options.remoteConfig !== void 0 || options.targetDir !== void 0) {
121
+ this.initPromise = this.bootstrapFromExplicitOptions(options);
122
+ return;
123
+ }
124
+ if (this.seedFromEnv) this.initPromise = this.seedFromEnvironment();
169
125
  }
170
- async getStatus() {
126
+ async ensureReady() {
127
+ if (this.delegatedAdapter != null) return;
128
+ if (this.initPromise != null) await this.initPromise;
129
+ }
130
+ async bootstrapFromExplicitOptions(options) {
131
+ if (options.remoteConfig != null) {
132
+ await this.applyRemoteConfiguration(options.remoteConfig, options.remoteClient ?? createRemoteObjectStoreClient(options.remoteConfig), true);
133
+ return;
134
+ }
135
+ if (options.targetDir != null) {
136
+ const resolved = resolveLocalArtifactTargetDirFromEnv(this.cwd, options.targetDir);
137
+ await this.applyLocalDirectory(resolved, true);
138
+ }
139
+ }
140
+ async seedFromEnvironment() {
141
+ const remoteEnv = getDbtToolsRemoteSourceConfigFromEnv();
142
+ if (remoteEnv != null) {
143
+ await this.applyRemoteConfiguration(remoteEnv, createRemoteObjectStoreClient(remoteEnv), true);
144
+ return;
145
+ }
146
+ const rawTarget = getDbtToolsTargetDirFromEnv();
147
+ if (rawTarget == null) return;
148
+ const resolved = resolveLocalArtifactTargetDirFromEnv(this.cwd, rawTarget);
149
+ await this.applyLocalDirectory(resolved, true);
150
+ }
151
+ pickBootstrapRunId(mode, runs) {
152
+ if (mode === "remote") return runs[0]?.runId ?? null;
153
+ if (runs.length === 1) return runs[0].runId;
154
+ return null;
155
+ }
156
+ discoveryErrorMessage() {
157
+ return this.discoveryResult != null && !this.discoveryResult.ok ? this.discoveryResult.failure.message : null;
158
+ }
159
+ resolveSelectedRun() {
160
+ if (this.selectedRunId == null) return null;
161
+ return this.runs.find((r) => r.runId === this.selectedRunId) ?? null;
162
+ }
163
+ statusWhenNone() {
171
164
  return toArtifactSourceStatus({
172
- mode: "preload",
173
- currentSource: "preload",
174
- label: "Live target",
165
+ mode: "none",
166
+ currentSource: null,
167
+ label: "Waiting for artifacts",
175
168
  remoteProvider: null,
176
169
  remoteLocation: null,
177
170
  pollIntervalMs: null,
178
171
  currentRun: null,
179
172
  pendingRun: null,
180
- supportsSwitch: false
173
+ supportsSwitch: false,
174
+ needsSelection: false,
175
+ candidates: void 0,
176
+ discoveryError: null,
177
+ sourceKind: null,
178
+ locationDisplay: null,
179
+ missingOptionalArtifacts: void 0
181
180
  });
182
181
  }
183
- async getCurrentArtifacts() {
184
- try {
185
- const [manifestBytes, runResultsBytes] = await Promise.all([fs$1.readFile(path.join(this.targetDir, DBT_MANIFEST_JSON)), fs$1.readFile(path.join(this.targetDir, DBT_RUN_RESULTS_JSON))]);
186
- return {
187
- source: "preload",
188
- manifestBytes,
189
- runResultsBytes
190
- };
191
- } catch {
192
- return null;
193
- }
182
+ mapRunsToUiRows() {
183
+ return this.runs.map((run) => runToUiRow(this.mode, this.remoteProvider, run));
184
+ }
185
+ runToUiOrNull(run) {
186
+ if (run == null) return null;
187
+ return runToUiRow(this.mode, this.remoteProvider, run);
188
+ }
189
+ needsExplicitRunSelection(discoveryError) {
190
+ return this.runs.length > 0 && this.selectedRunId == null && discoveryError == null;
191
+ }
192
+ optionalArtifactsForResolved(currentResolved) {
193
+ return currentResolved == null ? void 0 : missingOptionalFromRun(currentResolved);
194
+ }
195
+ remotePollIntervalOrNull() {
196
+ if (this.mode !== "remote") return null;
197
+ return this.remoteConfig?.pollIntervalMs ?? null;
198
+ }
199
+ remoteSupportsPendingSwitch(pendingRun, needsSelection) {
200
+ return this.mode === "remote" && pendingRun != null && !needsSelection;
201
+ }
202
+ currentManagedSourceOrNull(params) {
203
+ if (params.needsSelection || params.discoveryError != null || params.currentResolved == null) return null;
204
+ if (this.mode === "none") return null;
205
+ return this.mode;
206
+ }
207
+ buildActiveArtifactStatus() {
208
+ const discoveryError = this.discoveryErrorMessage();
209
+ const candidatesUi = this.mapRunsToUiRows();
210
+ const currentResolved = this.resolveSelectedRun();
211
+ const currentRunUi = this.runToUiOrNull(currentResolved);
212
+ const pendingRun = this.pendingRunAfterLatest(currentResolved);
213
+ const needsSelection = this.needsExplicitRunSelection(discoveryError);
214
+ const missingOptionalArtifacts = this.optionalArtifactsForResolved(currentResolved);
215
+ const supportsSwitch = this.remoteSupportsPendingSwitch(pendingRun, needsSelection);
216
+ const pollIntervalMs = this.remotePollIntervalOrNull();
217
+ const currentSource = this.currentManagedSourceOrNull({
218
+ needsSelection,
219
+ discoveryError,
220
+ currentResolved
221
+ });
222
+ return {
223
+ mode: this.mode,
224
+ currentSource,
225
+ label: this.locationDisplay ?? "Artifacts",
226
+ remoteProvider: this.remoteProvider,
227
+ remoteLocation: this.mode === "remote" ? this.locationDisplay : null,
228
+ pollIntervalMs,
229
+ currentRun: currentRunUi,
230
+ pendingRun,
231
+ supportsSwitch,
232
+ needsSelection,
233
+ candidates: candidatesUi.length > 0 ? candidatesUi : void 0,
234
+ discoveryError,
235
+ sourceKind: this.sourceKind ?? void 0,
236
+ locationDisplay: this.locationDisplay,
237
+ missingOptionalArtifacts
238
+ };
194
239
  }
195
- async switchToRun() {
196
- return this.getStatus();
240
+ pendingRunAfterLatest(currentResolved) {
241
+ const latestRun = this.runs[0] ?? null;
242
+ if (this.mode !== "remote" || this.remoteProvider == null || latestRun == null || currentResolved == null || latestRun.runId === currentResolved.runId) return null;
243
+ return runToUiRow("remote", this.remoteProvider, latestRun);
244
+ }
245
+ async readPreloadArtifacts(run) {
246
+ const [manifestBytes, runResultsBytes, catalogBytes, sourcesBytes] = await Promise.all([
247
+ fs$1.readFile(run.manifestKey),
248
+ fs$1.readFile(run.runResultsKey),
249
+ run.catalogKey != null ? fs$1.readFile(run.catalogKey).catch(() => null) : Promise.resolve(null),
250
+ run.sourcesKey != null ? fs$1.readFile(run.sourcesKey).catch(() => null) : Promise.resolve(null)
251
+ ]);
252
+ return {
253
+ source: "preload",
254
+ manifestBytes,
255
+ runResultsBytes,
256
+ ...catalogBytes != null ? { catalogBytes } : {},
257
+ ...sourcesBytes != null ? { sourcesBytes } : {}
258
+ };
197
259
  }
198
- };
199
- var RemoteArtifactSourceAdapter = class {
200
- currentRunId = null;
201
- constructor(config, client) {
202
- this.config = config;
203
- this.client = client;
204
- }
205
- async resolveRuns() {
206
- return discoverLatestArtifactRuns(await this.client.listObjects(this.config.bucket, normalizeArtifactPrefix(this.config.prefix)), this.config.prefix);
207
- }
208
- chooseCurrentRun(runs) {
209
- if (runs.length === 0) return null;
210
- if (this.currentRunId == null) {
211
- this.currentRunId = runs[0].runId;
212
- return runs[0];
260
+ async readRemoteArtifacts(run, bucket, client) {
261
+ const readOptional = async (key) => {
262
+ if (key == null) return null;
263
+ try {
264
+ return await client.readObjectBytes(bucket, key);
265
+ } catch {
266
+ return null;
267
+ }
268
+ };
269
+ const [manifestBytes, runResultsBytes, catalogBytes, sourcesBytes] = await Promise.all([
270
+ client.readObjectBytes(bucket, run.manifestKey),
271
+ client.readObjectBytes(bucket, run.runResultsKey),
272
+ readOptional(run.catalogKey),
273
+ readOptional(run.sourcesKey)
274
+ ]);
275
+ return {
276
+ source: "remote",
277
+ manifestBytes,
278
+ runResultsBytes,
279
+ ...catalogBytes != null ? { catalogBytes } : {},
280
+ ...sourcesBytes != null ? { sourcesBytes } : {}
281
+ };
282
+ }
283
+ previewToUiRows(discovery) {
284
+ return discovery.runs.map((run) => runToUiRow(discovery.mode, discovery.remoteProvider, run));
285
+ }
286
+ discoveryNeedsSelection(discovery, selectedRunId) {
287
+ const discoveryError = discovery.discoveryResult.ok === true ? null : discovery.discoveryResult.failure.message;
288
+ return discovery.runs.length > 0 && selectedRunId == null && discoveryError == null;
289
+ }
290
+ resolveConfiguredRunId(discovery, runId) {
291
+ if (!discovery.discoveryResult.ok) throw new Error(discovery.discoveryResult.failure.message);
292
+ const trimmedRunId = runId?.trim();
293
+ if (trimmedRunId != null && trimmedRunId !== "") {
294
+ if (!discovery.runs.some((run) => run.runId === trimmedRunId)) throw new Error(`Unknown run id "${trimmedRunId}". Candidates: ${discovery.runs.map((run) => run.runId).join(", ")}`);
295
+ return trimmedRunId;
213
296
  }
214
- const current = runs.find((run) => run.runId === this.currentRunId);
215
- if (current) return current;
216
- this.currentRunId = runs[0].runId;
217
- return runs[0];
297
+ if (discovery.runs.length === 1) return discovery.runs[0].runId;
298
+ if (discovery.runs.length === 0) throw new Error("No complete dbt artifact pair found at this location.");
299
+ throw new Error(`Multiple artifact sets found (${discovery.runs.length}). Select a candidate run before loading.`);
300
+ }
301
+ applyDiscoveredArtifactSource(discovery, selectedRunId) {
302
+ this.mode = discovery.mode;
303
+ this.localDir = discovery.localDir;
304
+ this.locationDisplay = discovery.locationDisplay;
305
+ this.sourceKind = discovery.sourceKind;
306
+ this.remoteConfig = discovery.remoteConfig;
307
+ this.remoteClient = discovery.remoteClient;
308
+ this.remoteProvider = discovery.remoteProvider;
309
+ this.discoveryResult = discovery.discoveryResult;
310
+ this.runs = discovery.runs;
311
+ this.selectedRunId = selectedRunId;
312
+ }
313
+ async discoverLocalDirectory(resolvedDir) {
314
+ const { runs, discovery } = await discoverLocalResolvedArtifactRuns(resolvedDir);
315
+ if (!discovery.ok) debugLog("Local discovery failed", discovery.failure.message);
316
+ return {
317
+ mode: "preload",
318
+ sourceKind: "local",
319
+ locationDisplay: resolvedDir,
320
+ remoteProvider: null,
321
+ localDir: resolvedDir,
322
+ remoteConfig: null,
323
+ remoteClient: null,
324
+ runs,
325
+ discoveryResult: discovery
326
+ };
218
327
  }
219
- async getStatus() {
220
- const runs = await this.resolveRuns();
221
- const currentRun = this.chooseCurrentRun(runs);
222
- const latestRun = runs[0] ?? null;
223
- const pendingRun = latestRun != null && currentRun != null && latestRun.runId !== currentRun.runId ? latestRun : null;
224
- return toArtifactSourceStatus({
328
+ async discoverRemoteConfiguration(config, client) {
329
+ const prefixNorm = normalizeArtifactPrefix$1(config.prefix);
330
+ const objects = await client.listObjects(config.bucket, prefixNorm);
331
+ const discovery = discoverRemoteArtifactDiscovery(objects, config.prefix);
332
+ const runs = discovery.ok ? discoverLatestArtifactRuns(objects, config.prefix) : [];
333
+ if (!discovery.ok) debugLog("Remote discovery failed", discovery.failure.message);
334
+ return {
225
335
  mode: "remote",
226
- currentSource: currentRun == null ? null : "remote",
227
- label: "Remote source",
228
- remoteProvider: this.config.provider,
229
- remoteLocation: toLocationLabel(this.config.provider, this.config.bucket, normalizeArtifactPrefix(this.config.prefix)),
230
- pollIntervalMs: this.config.pollIntervalMs,
231
- currentRun: currentRun == null ? null : toRemoteArtifactRun(this.config.provider, currentRun),
232
- pendingRun: pendingRun == null ? null : toRemoteArtifactRun(this.config.provider, pendingRun),
233
- supportsSwitch: pendingRun != null
234
- });
336
+ sourceKind: config.provider,
337
+ locationDisplay: toRemoteLocationLabel(config.provider, config.bucket, config.prefix),
338
+ remoteProvider: config.provider,
339
+ localDir: null,
340
+ remoteConfig: config,
341
+ remoteClient: client,
342
+ runs,
343
+ discoveryResult: discovery
344
+ };
235
345
  }
236
- async getCurrentArtifacts() {
237
- const runs = await this.resolveRuns();
238
- const currentRun = this.chooseCurrentRun(runs);
239
- if (currentRun == null) return null;
240
- const [manifestBytes, runResultsBytes] = await Promise.all([this.client.readObjectBytes(this.config.bucket, currentRun.manifestKey), this.client.readObjectBytes(this.config.bucket, currentRun.runResultsKey)]);
346
+ async discoverArtifactSourceInternal(kind, location) {
347
+ const parsed = parseArtifactSourceLocation(kind, location, this.cwd);
348
+ if (parsed.kind === "local") return this.discoverLocalDirectory(parsed.resolvedPath);
349
+ const merged = mergeRemoteSourceConfigWithParsedLocation(getDbtToolsRemoteSourceConfigFromEnv(), parsed);
350
+ const client = createRemoteObjectStoreClient(merged);
351
+ return this.discoverRemoteConfiguration(merged, client);
352
+ }
353
+ async applyLocalDirectory(resolvedDir, fromEnvBootstrap) {
354
+ const discovery = await this.discoverLocalDirectory(resolvedDir);
355
+ const selectedRunId = discovery.discoveryResult.ok && fromEnvBootstrap ? this.pickBootstrapRunId("preload", discovery.runs) : null;
356
+ this.applyDiscoveredArtifactSource(discovery, selectedRunId);
357
+ }
358
+ async applyRemoteConfiguration(config, client, fromEnvBootstrap) {
359
+ const discovery = await this.discoverRemoteConfiguration(config, client);
360
+ const selectedRunId = discovery.discoveryResult.ok && fromEnvBootstrap ? this.pickBootstrapRunId("remote", discovery.runs) : null;
361
+ this.applyDiscoveredArtifactSource(discovery, selectedRunId);
362
+ }
363
+ async discoverArtifactSource(kind, location) {
364
+ await this.ensureReady();
365
+ const discovery = await this.discoverArtifactSourceInternal(kind, location);
366
+ const candidates = this.previewToUiRows(discovery);
367
+ const needsSelection = this.discoveryNeedsSelection(discovery, null);
241
368
  return {
242
- source: "remote",
243
- manifestBytes,
244
- runResultsBytes
369
+ sourceKind: discovery.sourceKind,
370
+ locationDisplay: discovery.locationDisplay,
371
+ candidates: candidates.length > 0 ? candidates : void 0,
372
+ needsSelection,
373
+ discoveryError: discovery.discoveryResult.ok === true ? null : discovery.discoveryResult.failure.message
245
374
  };
246
375
  }
247
- async switchToRun(runId) {
248
- const runs = await this.resolveRuns();
249
- const target = runId == null ? runs[0] : runs.find((candidate) => candidate.runId === runId);
250
- if (target != null) {
251
- this.currentRunId = target.runId;
252
- debugLog("Switched remote artifact run", this.currentRunId);
253
- }
376
+ /**
377
+ * User-driven configuration (UI or API). Commits the location only when the
378
+ * selected run is explicit or uniquely determined.
379
+ */
380
+ async configureArtifactSource(kind, location, runId) {
381
+ await this.ensureReady();
382
+ const discovery = await this.discoverArtifactSourceInternal(kind, location);
383
+ const selectedRunId = this.resolveConfiguredRunId(discovery, runId);
384
+ this.applyDiscoveredArtifactSource(discovery, selectedRunId);
254
385
  return this.getStatus();
255
386
  }
256
- };
257
- var ArtifactSourceService = class {
258
- adapter;
259
- constructor(options = {}) {
260
- if (options.adapter !== void 0) {
261
- this.adapter = options.adapter;
262
- return;
263
- }
264
- const remoteConfig = options.remoteConfig === void 0 ? getDbtToolsRemoteSourceConfigFromEnv() : options.remoteConfig;
265
- if (remoteConfig != null) {
266
- debugLog("Configured remote artifact source", remoteConfig.provider, remoteConfig.bucket, remoteConfig.prefix);
267
- this.adapter = new RemoteArtifactSourceAdapter(remoteConfig, options.remoteClient ?? createRemoteObjectStoreClient(remoteConfig));
268
- return;
269
- }
270
- const targetDir = options.targetDir === void 0 ? getDbtToolsTargetDirFromEnv() : options.targetDir;
271
- if (targetDir == null) {
272
- this.adapter = null;
273
- return;
274
- }
275
- this.adapter = new LocalArtifactSourceAdapter(resolveLocalArtifactTargetDirFromEnv(process.cwd(), targetDir));
276
- }
277
387
  async getStatus() {
278
- if (this.adapter == null) return toArtifactSourceStatus({
279
- mode: "none",
280
- currentSource: null,
281
- label: "Waiting for artifacts",
282
- remoteProvider: null,
283
- remoteLocation: null,
284
- pollIntervalMs: null,
285
- currentRun: null,
286
- pendingRun: null,
287
- supportsSwitch: false
288
- });
289
- return this.adapter.getStatus();
388
+ await this.ensureReady();
389
+ if (this.delegatedAdapter != null) return this.delegatedAdapter.getStatus();
390
+ if (this.mode === "none") return this.statusWhenNone();
391
+ return toArtifactSourceStatus(this.buildActiveArtifactStatus());
290
392
  }
291
393
  async getCurrentArtifacts() {
292
- return this.adapter?.getCurrentArtifacts() ?? null;
394
+ await this.ensureReady();
395
+ if (this.delegatedAdapter != null) return this.delegatedAdapter.getCurrentArtifacts();
396
+ if (this.selectedRunId == null || this.discoveryResult?.ok !== true) return null;
397
+ const run = this.runs.find((r) => r.runId === this.selectedRunId);
398
+ if (run == null) return null;
399
+ if (this.mode === "preload" && this.localDir != null) return this.readPreloadArtifacts(run);
400
+ if (this.mode === "remote" && this.remoteClient != null && this.remoteConfig != null) return this.readRemoteArtifacts(run, this.remoteConfig.bucket, this.remoteClient);
401
+ return null;
293
402
  }
294
403
  async switchToRun(runId) {
295
- if (this.adapter == null) return this.getStatus();
296
- return this.adapter.switchToRun(runId);
404
+ await this.ensureReady();
405
+ if (this.delegatedAdapter != null) return this.delegatedAdapter.switchToRun(runId);
406
+ if (runId != null && runId.trim() !== "") {
407
+ if (this.runs.some((r) => r.runId === runId)) {
408
+ this.selectedRunId = runId;
409
+ debugLog("Selected artifact run", this.selectedRunId);
410
+ }
411
+ }
412
+ return this.getStatus();
297
413
  }
298
414
  };
299
415
  //#endregion
@@ -313,34 +429,118 @@ function sendJson(res, statusCode, payload) {
313
429
  res.statusCode = statusCode;
314
430
  res.end(JSON.stringify(payload));
315
431
  }
432
+ function currentArtifactBytes(pathname, current) {
433
+ if (current == null) return null;
434
+ if (pathname.endsWith(DBT_MANIFEST_JSON)) return current.manifestBytes;
435
+ if (pathname.endsWith(DBT_RUN_RESULTS_JSON)) return current.runResultsBytes;
436
+ if (pathname.endsWith(DBT_CATALOG_JSON)) return current.catalogBytes ?? null;
437
+ if (pathname.endsWith(DBT_SOURCES_JSON)) return current.sourcesBytes ?? null;
438
+ return null;
439
+ }
440
+ var CURRENT_ARTIFACT_PATHS = new Set([
441
+ `/api/${DBT_MANIFEST_JSON}`,
442
+ `/api/artifacts/current/${DBT_MANIFEST_JSON}`,
443
+ `/api/${DBT_RUN_RESULTS_JSON}`,
444
+ `/api/artifacts/current/${DBT_RUN_RESULTS_JSON}`,
445
+ `/api/${DBT_CATALOG_JSON}`,
446
+ `/api/artifacts/current/${DBT_CATALOG_JSON}`,
447
+ `/api/${DBT_SOURCES_JSON}`,
448
+ `/api/artifacts/current/${DBT_SOURCES_JSON}`
449
+ ]);
450
+ function requestPathname$1(req) {
451
+ return req.url?.split("?")[0] ?? null;
452
+ }
453
+ function isArtifactStatusRequest(req, pathname) {
454
+ return req.method === "GET" && pathname === "/api/artifact-source";
455
+ }
456
+ function isArtifactSwitchRequest(req, pathname) {
457
+ return req.method === "POST" && pathname === "/api/artifact-source/switch";
458
+ }
459
+ function isArtifactConfigureRequest(req, pathname) {
460
+ return req.method === "POST" && pathname === "/api/artifact-source/configure";
461
+ }
462
+ function isArtifactDiscoverRequest(req, pathname) {
463
+ return req.method === "POST" && pathname === "/api/artifact-source/discover";
464
+ }
465
+ function isCurrentArtifactRequest(req, pathname) {
466
+ return req.method === "GET" && CURRENT_ARTIFACT_PATHS.has(pathname);
467
+ }
468
+ async function respondArtifactStatus(res, service) {
469
+ sendJson(res, 200, await service.getStatus());
470
+ }
471
+ async function respondArtifactSwitch(req, res, service) {
472
+ const body = await readJsonBody(req);
473
+ const runId = typeof body.runId === "string" && body.runId.trim() !== "" ? body.runId : void 0;
474
+ sendJson(res, 200, await service.switchToRun(runId));
475
+ }
476
+ async function respondArtifactConfigure(req, res, service) {
477
+ const body = await readJsonBody(req);
478
+ const typeRaw = body.type;
479
+ const locationRaw = body.location;
480
+ const runIdRaw = body.runId;
481
+ const location = typeof locationRaw === "string" ? locationRaw.trim() : "";
482
+ const runId = typeof runIdRaw === "string" ? runIdRaw.trim() : void 0;
483
+ if (typeRaw !== "local" && typeRaw !== "s3" && typeRaw !== "gcs") {
484
+ sendJson(res, 400, { error: "Invalid or missing type (expected local, s3, or gcs)." });
485
+ return;
486
+ }
487
+ try {
488
+ sendJson(res, 200, await service.configureArtifactSource(typeRaw, location, runId));
489
+ } catch (error) {
490
+ sendJson(res, 400, { error: error instanceof Error ? error.message : "Invalid configuration." });
491
+ }
492
+ }
493
+ async function respondArtifactDiscover(req, res, service) {
494
+ const body = await readJsonBody(req);
495
+ const typeRaw = body.type;
496
+ const locationRaw = body.location;
497
+ const location = typeof locationRaw === "string" ? locationRaw.trim() : "";
498
+ if (typeRaw !== "local" && typeRaw !== "s3" && typeRaw !== "gcs") {
499
+ sendJson(res, 400, { error: "Invalid or missing type (expected local, s3, or gcs)." });
500
+ return;
501
+ }
502
+ try {
503
+ sendJson(res, 200, await service.discoverArtifactSource(typeRaw, location));
504
+ } catch (error) {
505
+ sendJson(res, 400, { error: error instanceof Error ? error.message : "Invalid configuration." });
506
+ }
507
+ }
508
+ async function respondCurrentArtifactBytes(pathname, res, service) {
509
+ const bytes = currentArtifactBytes(pathname, await service.getCurrentArtifacts());
510
+ if (bytes == null) {
511
+ res.statusCode = 404;
512
+ res.end();
513
+ return;
514
+ }
515
+ res.setHeader("Content-Type", "application/json");
516
+ res.statusCode = 200;
517
+ res.end(Buffer.from(bytes));
518
+ }
316
519
  /**
317
520
  * Vite middleware handler for artifact-source HTTP routes. Returns `true` when
318
521
  * the request was fully handled (response ended).
319
522
  */
320
523
  async function tryHandleArtifactSourceViteRequest(req, res, service) {
321
- const pathname = req.url?.split("?")[0];
524
+ const pathname = requestPathname$1(req);
322
525
  if (!pathname) return false;
323
- if (req.method === "GET" && pathname === "/api/artifact-source") {
324
- sendJson(res, 200, await service.getStatus());
526
+ if (isArtifactStatusRequest(req, pathname)) {
527
+ await respondArtifactStatus(res, service);
325
528
  return true;
326
529
  }
327
- if (req.method === "POST" && pathname === "/api/artifact-source/switch") {
328
- const body = await readJsonBody(req);
329
- const runId = typeof body.runId === "string" && body.runId.trim() !== "" ? body.runId : void 0;
330
- sendJson(res, 200, await service.switchToRun(runId));
530
+ if (isArtifactSwitchRequest(req, pathname)) {
531
+ await respondArtifactSwitch(req, res, service);
331
532
  return true;
332
533
  }
333
- if (req.method === "GET" && (pathname === `/api/${DBT_MANIFEST_JSON}` || pathname === `/api/artifacts/current/${DBT_MANIFEST_JSON}` || pathname === `/api/${DBT_RUN_RESULTS_JSON}` || pathname === `/api/artifacts/current/${DBT_RUN_RESULTS_JSON}`)) {
334
- const current = await service.getCurrentArtifacts();
335
- if (current == null) {
336
- res.statusCode = 404;
337
- res.end();
338
- return true;
339
- }
340
- const bytes = pathname.endsWith(DBT_MANIFEST_JSON) ? current.manifestBytes : current.runResultsBytes;
341
- res.setHeader("Content-Type", "application/json");
342
- res.statusCode = 200;
343
- res.end(Buffer.from(bytes));
534
+ if (isArtifactConfigureRequest(req, pathname)) {
535
+ await respondArtifactConfigure(req, res, service);
536
+ return true;
537
+ }
538
+ if (isArtifactDiscoverRequest(req, pathname)) {
539
+ await respondArtifactDiscover(req, res, service);
540
+ return true;
541
+ }
542
+ if (isCurrentArtifactRequest(req, pathname)) {
543
+ await respondCurrentArtifactBytes(pathname, res, service);
344
544
  return true;
345
545
  }
346
546
  return false;
@@ -485,7 +685,6 @@ Usage: dbt-tools-web [options]
485
685
 
486
686
  --target <dir> Path to dbt target directory (sets DBT_TOOLS_TARGET_DIR)
487
687
  --port <n> Port to listen on (default: 3000)
488
- --no-open Do not open the browser automatically
489
688
  --help Show this help message
490
689
  `.trimStart();
491
690
  function readRequiredValue(argv, i, flagDesc) {
@@ -511,13 +710,10 @@ function consumeOne(argv, i, state) {
511
710
  status: "done",
512
711
  result: { kind: "help" }
513
712
  };
514
- if (arg === "--no-open") {
515
- state.open = false;
516
- return {
517
- status: "advance",
518
- nextIndex: i + 1
519
- };
520
- }
713
+ if (arg === "--no-open") return {
714
+ status: "advance",
715
+ nextIndex: i + 1
716
+ };
521
717
  if (arg === "--target" || arg === "-t") {
522
718
  const r = readRequiredValue(argv, i, "--target (or -t)");
523
719
  if (!r.ok) return {
@@ -574,8 +770,7 @@ function consumeOne(argv, i, state) {
574
770
  function parseCliArgs(argv) {
575
771
  const state = {
576
772
  targetDir: void 0,
577
- port: 3e3,
578
- open: true
773
+ port: 3e3
579
774
  };
580
775
  let i = 0;
581
776
  while (i < argv.length) {
@@ -586,8 +781,7 @@ function parseCliArgs(argv) {
586
781
  return {
587
782
  kind: "ok",
588
783
  targetDir: state.targetDir,
589
- port: state.port,
590
- open: state.open
784
+ port: state.port
591
785
  };
592
786
  }
593
787
  //#endregion
@@ -601,22 +795,10 @@ if (parsed.kind === "error") {
601
795
  process.stderr.write(`${parsed.message}\n`);
602
796
  process.exit(1);
603
797
  }
604
- var { targetDir, port, open } = parsed;
798
+ var { targetDir, port } = parsed;
605
799
  if (targetDir !== void 0) process.env.DBT_TOOLS_TARGET_DIR = targetDir;
606
800
  await startServer(port);
607
801
  var url = `http://${LISTEN_HOST}:${port}`;
608
802
  process.stdout.write(`dbt-tools-web ${url}\n`);
609
- function openBrowser(safeUrl) {
610
- const cb = () => {};
611
- if (process.platform === "darwin") execFile("open", [safeUrl], cb);
612
- else if (process.platform === "win32") execFile("cmd.exe", [
613
- "/c",
614
- "start",
615
- "",
616
- safeUrl
617
- ], { windowsHide: true }, cb);
618
- else execFile("xdg-open", [safeUrl], cb);
619
- }
620
- if (open) openBrowser(url);
621
803
  //#endregion
622
804
  export {};