metergraph 0.5.0 → 0.6.2

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.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,15 @@
1
- import { route, setSession, setTags, trace, type RouteOptions, type TraceOptions } from "./context.js";
1
+ import { route, setDefaultTags, setSession, setTags, trace, withContext, withSession, withTags, type ContextOptions, type RouteOptions, type TraceOptions } from "./context.js";
2
2
  import { BatchFirstIneligibleError, batchFirst, type BatchFirstMetadata, type BatchFirstPolicy, type BatchFirstProvider, type BatchFirstRequest, type BatchFirstResult, type BatchFirstSource, type LateBatchInfo } from "./batch-first.js";
3
3
  import { track } from "./track.js";
4
4
  import { type TransportMode, type WaitUntil } from "./transport.js";
5
- import { type VercelAISDKMiddleware, type VercelAISDKMiddlewareOptions, type VercelAISDKMiddlewareSpecificationOptions, type VercelAISDKMiddlewareVersionOptions, type VercelAISDKSpecificationVersion } from "./vercel-ai.js";
5
+ import { type VercelAISDKMiddleware, type VercelAISDKMiddlewareOptions as VercelAISDKCompatibilityOptions, type VercelAISDKMiddlewareSpecificationOptions, type VercelAISDKMiddlewareVersionOptions, type VercelAISDKSpecificationVersion } from "./vercel-ai.js";
6
6
  export interface MetergraphOptions {
7
7
  token?: string;
8
8
  ingestUrl?: string;
9
9
  captureText?: boolean;
10
10
  redact?: (text: string, kind: "request" | "response") => string;
11
11
  appRoot?: string;
12
+ repository?: string;
12
13
  skipFrames?: string[];
13
14
  environment?: string;
14
15
  disabled?: boolean;
@@ -18,7 +19,9 @@ export interface MetergraphOptions {
18
19
  flushMs?: number;
19
20
  configPollMs?: number;
20
21
  configHardTtlMs?: number;
22
+ textMaxBytes?: number;
21
23
  }
24
+ export type VercelAISDKMiddlewareOptions<TVersion extends VercelAISDKSpecificationVersion = "v3"> = MetergraphOptions & VercelAISDKCompatibilityOptions<TVersion>;
22
25
  export interface ModelForOptions {
23
26
  default: string;
24
27
  sessionKey?: string;
@@ -55,12 +58,13 @@ export declare function wrap<T extends Record<PropertyKey, any>>(client: T, prov
55
58
  export declare const wrapClient: typeof wrap;
56
59
  /**
57
60
  * Capture Vercel AI SDK language-model calls through its middleware API.
58
- * The returned middleware has no runtime dependency on `ai`.
61
+ * Initializes Metergraph from these options when no runtime exists. The
62
+ * returned middleware has no runtime dependency on `ai`.
59
63
  */
60
- export declare function vercelAISDKMiddleware(options: VercelAISDKMiddlewareVersionOptions): VercelAISDKMiddleware<"v2">;
61
- export declare function vercelAISDKMiddleware<TVersion extends VercelAISDKSpecificationVersion = "v3">(options?: VercelAISDKMiddlewareSpecificationOptions<TVersion>): VercelAISDKMiddleware<TVersion>;
62
- export { route, setSession, setTags, trace, track };
63
- export type { RouteOptions, TraceOptions, TransportMode, VercelAISDKMiddleware, VercelAISDKMiddlewareOptions, VercelAISDKSpecificationVersion, };
64
+ export declare function vercelAISDKMiddleware(options: MetergraphOptions & VercelAISDKMiddlewareVersionOptions): VercelAISDKMiddleware<"v2">;
65
+ export declare function vercelAISDKMiddleware<TVersion extends VercelAISDKSpecificationVersion = "v3">(options?: MetergraphOptions & VercelAISDKMiddlewareSpecificationOptions<TVersion>): VercelAISDKMiddleware<TVersion>;
66
+ export { route, setDefaultTags, setSession, setTags, trace, track, withContext, withSession, withTags, };
67
+ export type { ContextOptions, RouteOptions, TraceOptions, TransportMode, VercelAISDKMiddleware, VercelAISDKSpecificationVersion, };
64
68
  /**
65
69
  * Explicit, opt-in batch-first execution over a provider's Batch API —
66
70
  * never enabled by wrap()/capture defaults or by an environment variable.
package/dist/index.js CHANGED
@@ -1,20 +1,46 @@
1
- import { CaptureRuntime } from "./capture.js";
2
- import { ConfigPoller } from "./config.js";
3
- import { contextSnapshot, route, setSession, setTags, trace, } from "./context.js";
4
- import { BatchFirstIneligibleError, batchFirst, } from "./batch-first.js";
5
- import { ensureRepoConfig } from "./repo-config.js";
6
- import { SessionManager } from "./session.js";
7
- import { track } from "./track.js";
8
- import { Transport } from "./transport.js";
9
- import { SDK_VERSION } from "./version.js";
10
- import { setCaptureRuntime, wrap as wrapProvider } from "./wrap.js";
11
- import { createVercelAISDKMiddleware, } from "./vercel-ai.js";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BatchFirstIneligibleError = exports.batchFirst = exports.withTags = exports.withSession = exports.withContext = exports.track = exports.trace = exports.setTags = exports.setSession = exports.setDefaultTags = exports.route = exports.wrapClient = exports.DEFAULT_INGEST_URL = void 0;
4
+ exports.init = init;
5
+ exports.modelFor = modelFor;
6
+ exports.recordOutcome = recordOutcome;
7
+ exports.bindWaitUntil = bindWaitUntil;
8
+ exports.flush = flush;
9
+ exports.shutdown = shutdown;
10
+ exports.wrapHandler = wrapHandler;
11
+ exports.wrap = wrap;
12
+ exports.vercelAISDKMiddleware = vercelAISDKMiddleware;
13
+ const capture_js_1 = require("./capture.js");
14
+ const config_js_1 = require("./config.js");
15
+ const context_js_1 = require("./context.js");
16
+ Object.defineProperty(exports, "route", { enumerable: true, get: function () { return context_js_1.route; } });
17
+ Object.defineProperty(exports, "setDefaultTags", { enumerable: true, get: function () { return context_js_1.setDefaultTags; } });
18
+ Object.defineProperty(exports, "setSession", { enumerable: true, get: function () { return context_js_1.setSession; } });
19
+ Object.defineProperty(exports, "setTags", { enumerable: true, get: function () { return context_js_1.setTags; } });
20
+ Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return context_js_1.trace; } });
21
+ Object.defineProperty(exports, "withContext", { enumerable: true, get: function () { return context_js_1.withContext; } });
22
+ Object.defineProperty(exports, "withSession", { enumerable: true, get: function () { return context_js_1.withSession; } });
23
+ Object.defineProperty(exports, "withTags", { enumerable: true, get: function () { return context_js_1.withTags; } });
24
+ const batch_first_js_1 = require("./batch-first.js");
25
+ Object.defineProperty(exports, "BatchFirstIneligibleError", { enumerable: true, get: function () { return batch_first_js_1.BatchFirstIneligibleError; } });
26
+ Object.defineProperty(exports, "batchFirst", { enumerable: true, get: function () { return batch_first_js_1.batchFirst; } });
27
+ const node_fs_1 = require("node:fs");
28
+ const repo_config_js_1 = require("./repo-config.js");
29
+ const session_js_1 = require("./session.js");
30
+ const track_js_1 = require("./track.js");
31
+ Object.defineProperty(exports, "track", { enumerable: true, get: function () { return track_js_1.track; } });
32
+ const transport_js_1 = require("./transport.js");
33
+ const version_js_1 = require("./version.js");
34
+ const wrap_js_1 = require("./wrap.js");
35
+ const vercel_ai_js_1 = require("./vercel-ai.js");
12
36
  let initialized = false;
13
37
  let warnedNoToken = false;
38
+ let warnedNoRepository = false;
39
+ let warnedRepeatedInit = false;
14
40
  let transport;
15
41
  let config;
16
42
  let sessionManager;
17
- export const DEFAULT_INGEST_URL = "https://d2xus7mp8zdv6t.cloudfront.net";
43
+ exports.DEFAULT_INGEST_URL = "https://d2xus7mp8zdv6t.cloudfront.net";
18
44
  function env(name) {
19
45
  return typeof process === "undefined" ? undefined : process.env[name];
20
46
  }
@@ -24,15 +50,35 @@ function envBool(name, fallback) {
24
50
  ? fallback
25
51
  : !["0", "false", "no", "off"].includes(value.toLowerCase());
26
52
  }
27
- export function init(options = {}) {
28
- if (initialized)
53
+ function repositoryConfig(options, appRoot) {
54
+ const explicit = options.repository ?? env("METERGRAPH_REPOSITORY");
55
+ if (typeof explicit === "string" && explicit.trim().includes("/")) {
56
+ let repoRoot = appRoot;
57
+ try {
58
+ repoRoot = (0, node_fs_1.realpathSync)(appRoot);
59
+ }
60
+ catch { /* attribution remains best-effort */ }
61
+ return { repository: explicit.trim(), repoRoot };
62
+ }
63
+ return (0, repo_config_js_1.discoverRepoConfig)(appRoot);
64
+ }
65
+ function warnOnRepeatedInit() {
66
+ if (warnedRepeatedInit)
67
+ return;
68
+ warnedRepeatedInit = true;
69
+ console.warn("Metergraph init() was called more than once; the first configuration remains active.");
70
+ }
71
+ function init(options = {}) {
72
+ if (initialized) {
73
+ warnOnRepeatedInit();
29
74
  return;
75
+ }
30
76
  if (env("METERGRAPH_DISABLED") === "1" || options.disabled) {
31
77
  initialized = true;
32
78
  return;
33
79
  }
34
80
  const token = options.token ?? env("METERGRAPH_APP_TOKEN");
35
- const ingestUrl = options.ingestUrl ?? env("METERGRAPH_INGEST_URL") ?? DEFAULT_INGEST_URL;
81
+ const ingestUrl = options.ingestUrl ?? env("METERGRAPH_INGEST_URL") ?? exports.DEFAULT_INGEST_URL;
36
82
  if (!token || !ingestUrl) {
37
83
  // Stay uninitialized so a later init() that supplies a token succeeds.
38
84
  if (!warnedNoToken) {
@@ -41,49 +87,57 @@ export function init(options = {}) {
41
87
  }
42
88
  return;
43
89
  }
44
- initialized = true;
45
90
  try {
46
91
  const appRoot = options.appRoot ?? (typeof process === "undefined" ? "" : process.cwd());
47
- const repoConfig = ensureRepoConfig(appRoot);
92
+ const repoConfig = repositoryConfig(options, appRoot);
93
+ initialized = true;
94
+ if (!repoConfig && !warnedNoRepository) {
95
+ warnedNoRepository = true;
96
+ console.warn("Metergraph repository identity is not configured; set init({ repository: \"owner/repository\" }), METERGRAPH_REPOSITORY, or provide .metergraph/config.json. Continuing with legacy ingestion.");
97
+ }
48
98
  sessionManager = repoConfig
49
- ? new SessionManager(token, ingestUrl, repoConfig.repository, SDK_VERSION)
99
+ ? new session_js_1.SessionManager(token, ingestUrl, repoConfig.repository, version_js_1.SDK_VERSION)
50
100
  : undefined;
51
- transport = new Transport(token, ingestUrl, {
101
+ const configuredTextMaxBytes = options.textMaxBytes
102
+ ?? Number(env("METERGRAPH_TEXT_MAX_BYTES") ?? capture_js_1.DEFAULT_TEXT_MAX_BYTES);
103
+ transport = new transport_js_1.Transport(token, ingestUrl, {
52
104
  queueSize: options.queueSize ?? Number(env("METERGRAPH_QUEUE_SIZE") ?? 2_000),
53
105
  batchSize: options.batchSize ?? Number(env("METERGRAPH_BATCH_SIZE") ?? 100),
54
106
  flushMs: options.flushMs ?? Number(env("METERGRAPH_FLUSH_MS") ?? 5_000),
55
107
  mode: options.transport ?? "auto",
56
108
  session: sessionManager,
57
109
  });
58
- setCaptureRuntime(new CaptureRuntime(transport, {
110
+ (0, wrap_js_1.setCaptureRuntime)(new capture_js_1.CaptureRuntime(transport, {
59
111
  captureText: options.captureText ?? envBool("METERGRAPH_CAPTURE_TEXT", true),
60
112
  redact: options.redact,
61
113
  appRoot,
62
114
  repoRoot: repoConfig?.repoRoot,
63
115
  skipFrames: options.skipFrames ?? [],
64
116
  environment: options.environment ?? env("METERGRAPH_ENV"),
65
- textMaxBytes: Math.min(100 * 1024, Math.max(1, Number(env("METERGRAPH_TEXT_MAX_BYTES") ?? 100 * 1024))),
117
+ textMaxBytes: Number.isFinite(configuredTextMaxBytes)
118
+ ? Math.max(1, Math.floor(configuredTextMaxBytes))
119
+ : capture_js_1.DEFAULT_TEXT_MAX_BYTES,
66
120
  }));
67
- config = new ConfigPoller(token, ingestUrl, options.configPollMs, options.configHardTtlMs);
121
+ config = new config_js_1.ConfigPoller(token, ingestUrl, options.configPollMs, options.configHardTtlMs);
68
122
  }
69
123
  catch {
70
124
  transport = undefined;
71
125
  config = undefined;
72
126
  sessionManager = undefined;
73
- setCaptureRuntime();
127
+ (0, wrap_js_1.setCaptureRuntime)();
74
128
  console.warn("Metergraph initialization failed; application is running uninstrumented");
75
129
  }
76
130
  }
77
- export function modelFor(routeName, options) {
131
+ function modelFor(routeName, options) {
78
132
  if (typeof options?.default !== "string" || !options.default) {
79
133
  throw new TypeError("modelFor requires options.default to be a non-empty string");
80
134
  }
81
- return config?.modelFor(routeName, options.default, options.sessionKey ?? contextSnapshot().sessionId) ?? options.default;
135
+ return config?.modelFor(routeName, options.default, options.sessionKey ?? (0, context_js_1.contextSnapshot)().sessionId) ?? options.default;
82
136
  }
83
- export function recordOutcome(routeName, options) {
137
+ function recordOutcome(routeName, options) {
84
138
  const routeNameClean = String(routeName).trim().slice(0, 512);
85
139
  const model = String(options.model).trim().slice(0, 512);
86
- const sessionKey = String(options.sessionKey ?? contextSnapshot().sessionId ?? "").trim().slice(0, 512);
140
+ const sessionKey = String(options.sessionKey ?? (0, context_js_1.contextSnapshot)().sessionId ?? "").trim().slice(0, 512);
87
141
  const randomId = globalThis.crypto?.randomUUID?.()
88
142
  ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
89
143
  const eventId = String(options.eventId ?? randomId).trim().slice(0, 128);
@@ -118,22 +172,22 @@ export function recordOutcome(routeName, options) {
118
172
  regeneration_count: options.regenerationCount,
119
173
  });
120
174
  }
121
- export function bindWaitUntil(value) {
175
+ function bindWaitUntil(value) {
122
176
  transport?.bindWaitUntil(value);
123
177
  }
124
- export async function flush(timeoutMs = 3_000) {
178
+ async function flush(timeoutMs = 3_000) {
125
179
  return transport?.flush(timeoutMs) ?? true;
126
180
  }
127
- export async function shutdown() {
181
+ async function shutdown() {
128
182
  config?.stop();
129
183
  config = undefined;
130
184
  await transport?.shutdown();
131
185
  transport = undefined;
132
186
  sessionManager?.stop();
133
187
  sessionManager = undefined;
134
- setCaptureRuntime();
188
+ (0, wrap_js_1.setCaptureRuntime)();
135
189
  }
136
- export function wrapHandler(handler) {
190
+ function wrapHandler(handler) {
137
191
  return async (...args) => {
138
192
  try {
139
193
  return await handler(...args);
@@ -149,21 +203,14 @@ export function wrapHandler(handler) {
149
203
  * Calls init() automatically, so with env-var configuration this is the
150
204
  * only setup line needed. Call init(...) first to pass options in code.
151
205
  */
152
- export function wrap(client, provider) {
153
- init();
154
- return wrapProvider(client, provider);
206
+ function wrap(client, provider) {
207
+ if (!initialized)
208
+ init();
209
+ return (0, wrap_js_1.wrap)(client, provider);
155
210
  }
156
- export const wrapClient = wrap;
157
- export function vercelAISDKMiddleware(options = {}) {
158
- init();
159
- return createVercelAISDKMiddleware(options);
211
+ exports.wrapClient = wrap;
212
+ function vercelAISDKMiddleware(options = {}) {
213
+ if (!initialized)
214
+ init(options);
215
+ return (0, vercel_ai_js_1.createVercelAISDKMiddleware)(options);
160
216
  }
161
- export { route, setSession, setTags, trace, track };
162
- /**
163
- * Explicit, opt-in batch-first execution over a provider's Batch API —
164
- * never enabled by wrap()/capture defaults or by an environment variable.
165
- * See BatchFirstPolicy for the required, explicit acknowledgements
166
- * (acceptDuplicateProviderExecution, and allowDuplicateToolCallPlans for
167
- * requests that include tools).
168
- */
169
- export { batchFirst, BatchFirstIneligibleError };
package/dist/index.mjs ADDED
@@ -0,0 +1,51 @@
1
+ import metergraph from "./index.js";
2
+
3
+ const {
4
+ BatchFirstIneligibleError,
5
+ DEFAULT_INGEST_URL,
6
+ batchFirst,
7
+ bindWaitUntil,
8
+ flush,
9
+ init,
10
+ modelFor,
11
+ recordOutcome,
12
+ route,
13
+ setDefaultTags,
14
+ setSession,
15
+ setTags,
16
+ shutdown,
17
+ trace,
18
+ track,
19
+ withContext,
20
+ withSession,
21
+ withTags,
22
+ vercelAISDKMiddleware,
23
+ wrap,
24
+ wrapClient,
25
+ wrapHandler,
26
+ } = metergraph;
27
+
28
+ export {
29
+ BatchFirstIneligibleError,
30
+ DEFAULT_INGEST_URL,
31
+ batchFirst,
32
+ bindWaitUntil,
33
+ flush,
34
+ init,
35
+ modelFor,
36
+ recordOutcome,
37
+ route,
38
+ setDefaultTags,
39
+ setSession,
40
+ setTags,
41
+ shutdown,
42
+ trace,
43
+ track,
44
+ withContext,
45
+ withSession,
46
+ withTags,
47
+ vercelAISDKMiddleware,
48
+ wrap,
49
+ wrapClient,
50
+ wrapHandler,
51
+ };
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  /**
2
3
  * The narrow adapter boundary batchFirst() drives, plus a worker-only OpenAI
3
4
  * Batch API implementation. Deliberately duck-typed against the openai
@@ -12,6 +13,11 @@
12
13
  * method inspects or logs a provider error body, a credential, or a raw
13
14
  * prompt.
14
15
  */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ProviderBatchError = void 0;
18
+ exports.createOpenAIBatchAdapter = createOpenAIBatchAdapter;
19
+ exports.createAnthropicBatchAdapter = createAnthropicBatchAdapter;
20
+ exports.createGoogleBatchAdapter = createGoogleBatchAdapter;
15
21
  const OPENAI_BATCH_ENDPOINT = "/v1/responses";
16
22
  const OPENAI_COMPLETION_WINDOW = "24h";
17
23
  // "validating" | "in_progress" | "finalizing" | "cancelling" all fall
@@ -32,9 +38,10 @@ function randomCustomId() {
32
38
  return globalThis.crypto.randomUUID();
33
39
  return `batch-first-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
34
40
  }
35
- export class ProviderBatchError extends Error {
41
+ class ProviderBatchError extends Error {
36
42
  }
37
- export function createOpenAIBatchAdapter(client) {
43
+ exports.ProviderBatchError = ProviderBatchError;
44
+ function createOpenAIBatchAdapter(client) {
38
45
  return {
39
46
  eligibility(request) {
40
47
  if (request.stream === true) {
@@ -118,7 +125,7 @@ function hasToolUse(message) {
118
125
  return false;
119
126
  return content.some((block) => get(block, "type") === "tool_use");
120
127
  }
121
- export function createAnthropicBatchAdapter(client) {
128
+ function createAnthropicBatchAdapter(client) {
122
129
  return {
123
130
  eligibility(request) {
124
131
  if (request.stream === true) {
@@ -187,7 +194,7 @@ function hasFunctionCallPart(response) {
187
194
  return parts.some((part) => get(part, "functionCall") != null || get(part, "function_call") != null);
188
195
  });
189
196
  }
190
- export function createGoogleBatchAdapter(client) {
197
+ function createGoogleBatchAdapter(client) {
191
198
  return {
192
199
  eligibility(request) {
193
200
  if (request.stream === true) {
@@ -5,18 +5,5 @@ export interface RepoConfig {
5
5
  repository: string;
6
6
  repoRoot: string;
7
7
  }
8
- /** Return 'owner/repo' from a GitHub SSH or HTTPS remote URL, or undefined
9
- * if the URL isn't a recognized GitHub origin. */
10
- export declare function normalizeGithubRemote(url: string): string | undefined;
11
- /** Walk upward from appRoot looking for .metergraph/config.json. Returns
12
- * undefined -- silently, the normal v1 state -- when nothing is found. */
8
+ /** Walk upward from appRoot looking for .metergraph/config.json. */
13
9
  export declare function discoverRepoConfig(appRoot: string): RepoConfig | undefined;
14
- /** Create .metergraph/config.json if -- and only if -- it doesn't already
15
- * exist. Uses O_CREAT|O_EXCL ("wx") for an atomic create-only-if-absent; a
16
- * concurrent writer (or a file that appeared between discovery and this
17
- * call) always wins over us, and we simply read back whatever is there. */
18
- export declare function writeConfigAtomically(repoRoot: string, repository: string): RepoConfig | undefined;
19
- /** Discover an existing repo config, or detect+write one once at the git top
20
- * level. Fail-open: any detection or write failure returns undefined
21
- * (legacy protocol v1), never throws. */
22
- export declare function ensureRepoConfig(appRoot: string): RepoConfig | undefined;
@@ -1,48 +1,28 @@
1
- /**
2
- * Repository-aware ingest protocol v2: discover, detect, and write
3
- * .metergraph/config.json.
4
- *
5
- * Discovery is purely file-based (never shells out to git), so a committed
6
- * config is honored in production without needing a .git directory at all.
7
- * Detection + write only ever runs when discovery finds nothing: it shells
8
- * out to git to find the repo's top level and GitHub origin, then writes the
9
- * config there exactly once. An existing file is always authoritative and is
10
- * never overwritten. Every failure mode here is fail-open -- callers get
11
- * undefined and fall back to legacy protocol v1, never a thrown error.
12
- */
13
- import { closeSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, writeSync } from "node:fs";
14
- import { dirname, isAbsolute, join, resolve } from "node:path";
15
- export const CONFIG_DIRNAME = ".metergraph";
16
- export const CONFIG_FILENAME = "config.json";
17
- export const SUPPORTED_CONFIG_VERSION = 2;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SUPPORTED_CONFIG_VERSION = exports.CONFIG_FILENAME = exports.CONFIG_DIRNAME = void 0;
4
+ exports.discoverRepoConfig = discoverRepoConfig;
5
+ /** Read-only discovery of repository identity configuration. */
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ exports.CONFIG_DIRNAME = ".metergraph";
9
+ exports.CONFIG_FILENAME = "config.json";
10
+ exports.SUPPORTED_CONFIG_VERSION = 2;
18
11
  const MAX_WALK_UP = 64;
19
- const REMOTE_PATTERNS = [
20
- /^git@github\.com:([^/]+\/[^/]+?)(\.git)?\/?$/,
21
- /^https:\/\/github\.com\/([^/]+\/[^/]+?)(\.git)?\/?$/,
22
- /^ssh:\/\/git@github\.com\/([^/]+\/[^/]+?)(\.git)?\/?$/,
23
- ];
24
- /** Return 'owner/repo' from a GitHub SSH or HTTPS remote URL, or undefined
25
- * if the URL isn't a recognized GitHub origin. */
26
- export function normalizeGithubRemote(url) {
27
- const trimmed = url.trim();
28
- for (const pattern of REMOTE_PATTERNS) {
29
- const match = pattern.exec(trimmed);
30
- if (match)
31
- return match[1];
32
- }
33
- return undefined;
34
- }
35
12
  function load(path, repoRoot) {
36
13
  let doc;
37
14
  try {
38
- doc = JSON.parse(readFileSync(path, "utf8"));
15
+ doc = JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
39
16
  }
40
17
  catch (error) {
41
18
  console.warn(`metergraph: found ${path} but could not read it: ${error instanceof Error ? error.message : String(error)}`);
42
19
  return undefined;
43
20
  }
44
- if (typeof doc !== "object" || doc === null || doc.version !== SUPPORTED_CONFIG_VERSION) {
45
- console.warn(`metergraph: ${path} has an unsupported schema version; ignoring (expected version ${SUPPORTED_CONFIG_VERSION})`);
21
+ if (typeof doc !== "object"
22
+ || doc === null
23
+ || (doc.version ?? exports.SUPPORTED_CONFIG_VERSION)
24
+ !== exports.SUPPORTED_CONFIG_VERSION) {
25
+ console.warn(`metergraph: ${path} has an unsupported schema version; ignoring (expected version ${exports.SUPPORTED_CONFIG_VERSION})`);
46
26
  return undefined;
47
27
  }
48
28
  const repository = doc.repository;
@@ -52,163 +32,28 @@ function load(path, repoRoot) {
52
32
  }
53
33
  return { repository, repoRoot };
54
34
  }
55
- /** Walk upward from appRoot looking for .metergraph/config.json. Returns
56
- * undefined -- silently, the normal v1 state -- when nothing is found. */
57
- export function discoverRepoConfig(appRoot) {
35
+ /** Walk upward from appRoot looking for .metergraph/config.json. */
36
+ function discoverRepoConfig(appRoot) {
58
37
  let current;
59
38
  try {
60
- current = realpathSync(appRoot);
39
+ current = (0, node_fs_1.realpathSync)(appRoot);
61
40
  }
62
41
  catch {
63
42
  return undefined;
64
43
  }
65
44
  for (let i = 0; i < MAX_WALK_UP; i += 1) {
66
- const candidate = join(current, CONFIG_DIRNAME, CONFIG_FILENAME);
45
+ const candidate = (0, node_path_1.join)(current, exports.CONFIG_DIRNAME, exports.CONFIG_FILENAME);
67
46
  try {
68
- readFileSync(candidate);
47
+ (0, node_fs_1.readFileSync)(candidate);
69
48
  return load(candidate, current);
70
49
  }
71
50
  catch {
72
- // no config at this level; keep walking up
51
+ // No config at this level; keep walking upward.
73
52
  }
74
- const parent = dirname(current);
53
+ const parent = (0, node_path_1.dirname)(current);
75
54
  if (parent === current)
76
55
  break;
77
56
  current = parent;
78
57
  }
79
58
  return undefined;
80
59
  }
81
- function gitDirectory(repoRoot) {
82
- const marker = join(repoRoot, ".git");
83
- try {
84
- if (statSync(marker).isDirectory())
85
- return marker;
86
- const match = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, "utf8"));
87
- const path = match?.[1];
88
- if (!path)
89
- return undefined;
90
- return isAbsolute(path) ? path : resolve(repoRoot, path);
91
- }
92
- catch {
93
- return undefined;
94
- }
95
- }
96
- function ownedByCurrentUser(path) {
97
- if (typeof process.getuid !== "function")
98
- return true;
99
- try {
100
- return statSync(path).uid === process.getuid();
101
- }
102
- catch {
103
- return false;
104
- }
105
- }
106
- function gitTopLevel(appRoot) {
107
- try {
108
- let current = realpathSync(appRoot);
109
- for (let i = 0; i < MAX_WALK_UP; i += 1) {
110
- const gitDir = gitDirectory(current);
111
- if (gitDir) {
112
- // Match Git's safe-directory default: never trust repository metadata
113
- // owned by another Unix user. Unsupported platforms retain v1's
114
- // existing fail-open behavior.
115
- return ownedByCurrentUser(current) && ownedByCurrentUser(gitDir)
116
- ? current
117
- : undefined;
118
- }
119
- const parent = dirname(current);
120
- if (parent === current)
121
- break;
122
- current = parent;
123
- }
124
- }
125
- catch {
126
- // Fall through to the normal v1 path.
127
- }
128
- return undefined;
129
- }
130
- function gitOriginUrl(repoRoot) {
131
- try {
132
- const gitDir = gitDirectory(repoRoot);
133
- if (!gitDir)
134
- return undefined;
135
- let commonDir = gitDir;
136
- try {
137
- const relative = readFileSync(join(gitDir, "commondir"), "utf8").trim();
138
- if (relative)
139
- commonDir = resolve(gitDir, relative);
140
- }
141
- catch {
142
- // Normal repositories keep config directly in .git.
143
- }
144
- const config = readFileSync(join(commonDir, "config"), "utf8");
145
- let inOrigin = false;
146
- for (const line of config.split(/\r?\n/)) {
147
- const section = /^\s*\[remote\s+"([^"]+)"\]\s*$/.exec(line);
148
- if (section) {
149
- inOrigin = section[1] === "origin";
150
- continue;
151
- }
152
- if (/^\s*\[/.test(line))
153
- inOrigin = false;
154
- if (inOrigin) {
155
- const url = /^\s*url\s*=\s*(.+?)\s*$/.exec(line);
156
- if (url)
157
- return url[1];
158
- }
159
- }
160
- }
161
- catch {
162
- // Missing or unreadable Git metadata is the normal production fallback.
163
- }
164
- return undefined;
165
- }
166
- /** Create .metergraph/config.json if -- and only if -- it doesn't already
167
- * exist. Uses O_CREAT|O_EXCL ("wx") for an atomic create-only-if-absent; a
168
- * concurrent writer (or a file that appeared between discovery and this
169
- * call) always wins over us, and we simply read back whatever is there. */
170
- export function writeConfigAtomically(repoRoot, repository) {
171
- const configDir = join(repoRoot, CONFIG_DIRNAME);
172
- const configPath = join(configDir, CONFIG_FILENAME);
173
- const payload = `${JSON.stringify({ version: SUPPORTED_CONFIG_VERSION, repository })}\n`;
174
- try {
175
- mkdirSync(configDir, { recursive: true });
176
- const fd = openSync(configPath, "wx", 0o644);
177
- try {
178
- writeSync(fd, payload);
179
- }
180
- finally {
181
- closeSync(fd);
182
- }
183
- }
184
- catch (error) {
185
- if (error.code !== "EEXIST") {
186
- console.warn(`metergraph: could not write ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
187
- return undefined;
188
- }
189
- }
190
- return load(configPath, repoRoot);
191
- }
192
- /** Discover an existing repo config, or detect+write one once at the git top
193
- * level. Fail-open: any detection or write failure returns undefined
194
- * (legacy protocol v1), never throws. */
195
- export function ensureRepoConfig(appRoot) {
196
- const existing = discoverRepoConfig(appRoot);
197
- if (existing)
198
- return existing;
199
- try {
200
- const repoRoot = gitTopLevel(appRoot);
201
- if (!repoRoot)
202
- return undefined;
203
- const origin = gitOriginUrl(repoRoot);
204
- if (!origin)
205
- return undefined;
206
- const repository = normalizeGithubRemote(origin);
207
- if (!repository)
208
- return undefined;
209
- return writeConfigAtomically(repoRoot, repository);
210
- }
211
- catch {
212
- return undefined;
213
- }
214
- }