@sifr-dev/loom 0.0.0-stage → 1.0.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/LICENSE +21 -0
  3. package/README.ar.md +253 -0
  4. package/README.md +262 -2
  5. package/dist/browser.js +2717 -0
  6. package/dist/cli.js +15 -0
  7. package/dist/index.js +4854 -0
  8. package/dist/types/args.d.ts +14 -0
  9. package/dist/types/base64.d.ts +9 -0
  10. package/dist/types/browser.d.ts +57 -0
  11. package/dist/types/canonical.d.ts +20 -0
  12. package/dist/types/cli.d.ts +12 -0
  13. package/dist/types/commands/context.d.ts +30 -0
  14. package/dist/types/commands/diff.d.ts +18 -0
  15. package/dist/types/commands/doctor.d.ts +19 -0
  16. package/dist/types/commands/export.d.ts +30 -0
  17. package/dist/types/commands/migrate.d.ts +9 -0
  18. package/dist/types/commands/serve.d.ts +18 -0
  19. package/dist/types/commands/snapshot.d.ts +15 -0
  20. package/dist/types/commands/sync.d.ts +17 -0
  21. package/dist/types/commands/verify.d.ts +9 -0
  22. package/dist/types/commands/watch.d.ts +25 -0
  23. package/dist/types/compute.d.ts +49 -0
  24. package/dist/types/concurrency.d.ts +31 -0
  25. package/dist/types/config.d.ts +132 -0
  26. package/dist/types/diff.d.ts +57 -0
  27. package/dist/types/digest.d.ts +11 -0
  28. package/dist/types/entities.d.ts +27 -0
  29. package/dist/types/errors.d.ts +37 -0
  30. package/dist/types/fs.d.ts +23 -0
  31. package/dist/types/github/cache.d.ts +44 -0
  32. package/dist/types/github/client.d.ts +91 -0
  33. package/dist/types/github/collect.d.ts +36 -0
  34. package/dist/types/github/discovery.d.ts +39 -0
  35. package/dist/types/github/fixture.d.ts +26 -0
  36. package/dist/types/github/guard.d.ts +14 -0
  37. package/dist/types/github/memory-cache.d.ts +34 -0
  38. package/dist/types/index.d.ts +44 -0
  39. package/dist/types/log.d.ts +16 -0
  40. package/dist/types/metrics.d.ts +21 -0
  41. package/dist/types/migrate.d.ts +24 -0
  42. package/dist/types/pipeline.d.ts +73 -0
  43. package/dist/types/queue.d.ts +33 -0
  44. package/dist/types/sdk.d.ts +165 -0
  45. package/dist/types/secrets.d.ts +28 -0
  46. package/dist/types/serve-handler.d.ts +46 -0
  47. package/dist/types/sha256.d.ts +13 -0
  48. package/dist/types/site-module.d.ts +23 -0
  49. package/dist/types/site.d.ts +135 -0
  50. package/dist/types/snapshot.d.ts +16 -0
  51. package/dist/types/store.d.ts +119 -0
  52. package/dist/types/triggers.d.ts +67 -0
  53. package/dist/types/types.d.ts +176 -0
  54. package/dist/types/version.d.ts +7 -0
  55. package/dist/types/webhook/delivery.d.ts +45 -0
  56. package/dist/types/webhook/receiver.d.ts +46 -0
  57. package/dist/types/webhook/signature.d.ts +43 -0
  58. package/docs/CONFIGURATION.md +213 -0
  59. package/docs/DEPLOYMENT.md +316 -0
  60. package/docs/SDK.md +351 -0
  61. package/docs/SITE_CONTRACT.md +318 -0
  62. package/docs/VERIFICATION.md +130 -0
  63. package/package.json +83 -4
  64. package/schema/site@1.json +188 -0
@@ -0,0 +1,37 @@
1
+ export declare const EXIT: {
2
+ readonly ok: 0;
3
+ readonly failure: 1;
4
+ readonly usage: 2;
5
+ readonly verifyFailed: 3;
6
+ readonly guardViolation: 4;
7
+ readonly unauthorized: 5;
8
+ /** Some configured repositories could not be read and no previous copy existed. */
9
+ readonly partial: 6;
10
+ readonly unchanged: 7;
11
+ /** Another process holds the store lock. Safe to retry. */
12
+ readonly busy: 8;
13
+ };
14
+ export type ExitCode = (typeof EXIT)[keyof typeof EXIT];
15
+ export type LoomErrorCode = "usage" | "config_invalid" | "github_error" | "rate_limit_exhausted" | "repo_not_public" | "repo_invalid" | "store_corrupt" | "snapshot_missing" | "verify_failed" | "signature_invalid" | "payload_invalid" | "trigger_failed" | "secret_missing" | "secret_detected" | "network_error" | "cancelled" | "partial_failure" | "queue_full" | "lock_busy" | "schema_unsupported";
16
+ export declare class LoomError extends Error {
17
+ name: string;
18
+ readonly code: LoomErrorCode;
19
+ readonly detail: Readonly<Record<string, unknown>>;
20
+ constructor(code: LoomErrorCode, message: string, detail?: Record<string, unknown>);
21
+ get exitCode(): ExitCode;
22
+ /** One sentence an operator can act on, without repeating the error text. */
23
+ get hint(): string | null;
24
+ toJSON(): Record<string, unknown>;
25
+ }
26
+ export declare function hintFor(code: LoomErrorCode): string | null;
27
+ export declare function isLoomError(value: unknown): value is LoomError;
28
+ export declare function usageError(message: string, detail?: Record<string, unknown>): LoomError;
29
+ export declare function configError(message: string, detail?: Record<string, unknown>): LoomError;
30
+ export declare function guardError(message: string, detail?: Record<string, unknown>): LoomError;
31
+ /** Convert anything thrown into a reportable object without leaking secrets. */
32
+ export declare function describeError(error: unknown): {
33
+ code: string;
34
+ message: string;
35
+ detail: Record<string, unknown>;
36
+ hint?: string;
37
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Durable write: write a sibling temp file, fsync it, rename over the target,
3
+ * then fsync the directory. A reader never observes a partially written blob,
4
+ * and a crash leaves either the old file or the new one.
5
+ */
6
+ export declare function writeFileAtomic(path: string, data: string | Uint8Array): Promise<void>;
7
+ export declare function readTextIfExists(path: string): Promise<string | null>;
8
+ export declare function readJsonIfExists<T>(path: string): Promise<T | null>;
9
+ export declare function exists(path: string): Promise<boolean>;
10
+ export declare function ensureDir(path: string): Promise<void>;
11
+ /** Remove a directory tree. Used by tests and by `snapshot --clean`. */
12
+ export declare function removeTree(path: string): Promise<void>;
13
+ /** Write a JSON file with a trailing newline, atomically. */
14
+ export declare function writeJsonAtomic(path: string, value: unknown): Promise<void>;
15
+ /** Plain write used for temp fixtures inside tests. */
16
+ export declare function writeText(path: string, value: string): Promise<void>;
17
+ /**
18
+ * Move a damaged file aside instead of deleting it. Recovery must be
19
+ * inspectable: a corrupt cache should cost an ETag, never an operator's data.
20
+ */
21
+ export declare function quarantineFile(path: string, reason?: string): Promise<string | null>;
22
+ /** Remove leftover sibling temp files older than `maxAgeMs` (crash debris). */
23
+ export declare function removeStaleTempFiles(dir: string, maxAgeMs?: number): Promise<number>;
@@ -0,0 +1,44 @@
1
+ import type { CacheEntry, ResponseCache } from "./memory-cache.js";
2
+ export { MemoryCache } from "./memory-cache.js";
3
+ export type { CacheEntry, ResponseCache } from "./memory-cache.js";
4
+ export declare const CACHE_SCHEMA = "loom/http-cache@1";
5
+ /** Read-only compatibility with the pre-release layout. */
6
+ export declare const LEGACY_CACHE_SCHEMAS: readonly ["loom/http-cache@0"];
7
+ export type CacheFile = {
8
+ schema: string;
9
+ entries: Record<string, CacheEntry>;
10
+ };
11
+ export type CacheOpenResult = {
12
+ cache: FileCache;
13
+ recovered: boolean;
14
+ quarantined: string | null;
15
+ };
16
+ /**
17
+ * ETag cache persisted as one JSON file. Keys are URLs, values are the last
18
+ * body and its validator, so a 304 can be answered without a network payload.
19
+ *
20
+ * A cache is an optimisation, never a source of truth. A corrupt or unreadable
21
+ * file is quarantined and replaced with an empty cache, which costs one full
22
+ * fetch and never blocks a sync. Schema misses are treated the same way, but
23
+ * only after `loom migrate` has had a chance to run.
24
+ */
25
+ export declare class FileCache implements ResponseCache {
26
+ #private;
27
+ private constructor();
28
+ static open(path: string): Promise<FileCache>;
29
+ static openWithRecovery(path: string): Promise<CacheOpenResult>;
30
+ get(key: string): CacheEntry | undefined;
31
+ set(key: string, entry: CacheEntry): void;
32
+ delete(key: string): boolean;
33
+ save(): Promise<void>;
34
+ size(): number;
35
+ /** Drop entries whose validators are older than `maxAgeMs`. */
36
+ prune(maxAgeMs: number, nowMs?: number): number;
37
+ /** Read without creating a cache instance; used by `loom doctor`. */
38
+ static inspect(path: string): Promise<{
39
+ present: boolean;
40
+ valid: boolean;
41
+ entries: number;
42
+ schema: string | null;
43
+ }>;
44
+ }
@@ -0,0 +1,91 @@
1
+ import type { ResponseCache } from "./memory-cache.js";
2
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
3
+ export type RateLimit = {
4
+ limit: number | null;
5
+ remaining: number | null;
6
+ used: number | null;
7
+ resetAt: string | null;
8
+ retryAfterSeconds: number | null;
9
+ };
10
+ export type GitHubClientOptions = {
11
+ baseUrl?: string;
12
+ /** Optional; public reads work without it. Never logged or stored. */
13
+ token?: string | null;
14
+ userAgent?: string;
15
+ cache?: ResponseCache;
16
+ fetch?: FetchLike;
17
+ sleep?: (ms: number) => Promise<void>;
18
+ now?: () => number;
19
+ /** Retries after the first attempt, for 5xx, rate limits, and transport errors. */
20
+ maxRetries?: number;
21
+ retryBaseMs?: number;
22
+ retryMaxMs?: number;
23
+ /** Add randomised jitter so parallel clients do not retry in lockstep. */
24
+ jitter?: boolean;
25
+ random?: () => number;
26
+ /** A rate-limit reset beyond this is reported instead of slept through. */
27
+ maxRateLimitWaitMs?: number;
28
+ /** Start no request when the advertised remaining budget is at or below this. */
29
+ rateLimitReserve?: number;
30
+ requestTimeoutMs?: number;
31
+ perPage?: number;
32
+ maxPages?: number;
33
+ /** Caller-owned cancellation, combined with the per-request timeout. */
34
+ signal?: AbortSignal;
35
+ logger?: (message: string, detail?: Record<string, unknown>) => void;
36
+ };
37
+ export type GetOptions = {
38
+ /** Accept a 304 without a cached body (returns `null`). */
39
+ allowUncached304?: boolean;
40
+ signal?: AbortSignal;
41
+ };
42
+ export type GetResult<T> = {
43
+ status: 200;
44
+ body: T;
45
+ etag: string | null;
46
+ fromCache: false;
47
+ next: string | null;
48
+ } | {
49
+ status: 304;
50
+ body: T | null;
51
+ etag: string | null;
52
+ fromCache: true;
53
+ next: string | null;
54
+ };
55
+ export type GetAllResult<T> = {
56
+ items: T[];
57
+ pages: number;
58
+ notModified: boolean;
59
+ };
60
+ /**
61
+ * Parse GitHub's rate-limit headers. `Retry-After` may be delta-seconds or an
62
+ * HTTP date; both are normalised to seconds so callers do not need to care.
63
+ */
64
+ export declare function parseRateLimit(headers: Headers, nowMs?: number): RateLimit;
65
+ /** Extract and absolutise the `rel="next"` URL from a GitHub Link header. */
66
+ export declare function nextLink(header: string | null, baseUrl: string): string | null;
67
+ export type ClientStats = {
68
+ requests: number;
69
+ notModified: number;
70
+ retries: number;
71
+ rateLimitWaits: number;
72
+ waitMs: number;
73
+ lastRateLimit: RateLimit | null;
74
+ statuses: Record<string, number>;
75
+ };
76
+ export declare class GitHubClient {
77
+ #private;
78
+ readonly baseUrl: string;
79
+ constructor(options?: GitHubClientOptions);
80
+ get stats(): ClientStats;
81
+ url(pathOrUrl: string): string;
82
+ /** GET a single JSON document, using the ETag cache when present. */
83
+ get<T>(pathOrUrl: string, options?: GetOptions): Promise<GetResult<T>>;
84
+ /**
85
+ * GET every page of a collection by following `Link: rel="next"`.
86
+ * `notModified` is true only when every page answered 304. A repeated or
87
+ * self-referential cursor is a GitHub bug, not an infinite loop: it is
88
+ * reported as an error rather than followed forever.
89
+ */
90
+ getAll<T>(pathOrUrl: string, options?: GetOptions): Promise<GetAllResult<T>>;
91
+ }
@@ -0,0 +1,36 @@
1
+ import type { GitHubClient } from "./client.js";
2
+ import type { SnapshotPayload, SnapshotSource } from "../types.js";
3
+ import type { CollectConfig } from "../config.js";
4
+ export type CollectOptions = {
5
+ client: GitHubClient;
6
+ repos: readonly string[];
7
+ /** Releases per repository; zero disables the releases endpoint. */
8
+ releases?: number;
9
+ includeLatestCommit?: boolean;
10
+ /** Opt-in enrichment sources; every list is bounded by its limit. */
11
+ collect?: CollectConfig;
12
+ /** Old owner login -> current login, applied before any request. */
13
+ ownerAliases?: Record<string, string>;
14
+ /** Authenticated login when `discovery.owners` contained `me`. */
15
+ identity?: string | null;
16
+ /** Keep going when a repository fails, recording the failure in `errors`. */
17
+ tolerateErrors?: boolean;
18
+ /** Previous payload, used to retain a good copy when a fetch fails. */
19
+ previous?: SnapshotPayload | null;
20
+ /** Maximum repository fan-out. GitHub limits are per token, not per socket. */
21
+ concurrency?: number;
22
+ signal?: AbortSignal;
23
+ /** Provenance for owner discovery, when it contributed to `repos`. */
24
+ discovery?: SnapshotSource["discovery"];
25
+ logger?: (message: string, detail?: Record<string, unknown>) => void;
26
+ };
27
+ /**
28
+ * Read public GitHub state for every configured repository into one payload.
29
+ *
30
+ * Failure is per repository. With tolerance enabled, a failed repository is
31
+ * either carried forward from the previous good payload (so a transient 502 is
32
+ * never mistaken for a deletion) or reported as missing. Without a previous
33
+ * copy the error is recorded and the repository is omitted; the pipeline sees
34
+ * no diff and therefore commits and deploys nothing.
35
+ */
36
+ export declare function collectSnapshot(options: CollectOptions): Promise<SnapshotPayload>;
@@ -0,0 +1,39 @@
1
+ import { type DiscoveryConfig } from "../config.js";
2
+ import type { GitHubClient } from "./client.js";
3
+ export type DiscoverySkipReason = "not-public" | "archived" | "fork" | "excluded" | "not-included" | "invalid" | "wrong-owner";
4
+ export type DiscoveryResult = {
5
+ /** Selected `owner/name` values, sorted and de-duplicated. */
6
+ repos: string[];
7
+ /** Canonical owner logins that produced the selection. */
8
+ owners: string[];
9
+ /** Old owner login -> resolved login, including a redirect after a rename. */
10
+ ownerAliases: {
11
+ from: string;
12
+ to: string;
13
+ }[];
14
+ /** Login resolved from `GET /user` when `discovery.owners` contained `me`. */
15
+ identity: string | null;
16
+ /** Per-owner policy counters, useful in logs and tests. */
17
+ counts: Record<DiscoverySkipReason | "selected", number>;
18
+ };
19
+ export type DiscoveryOptions = {
20
+ client: GitHubClient;
21
+ config: DiscoveryConfig;
22
+ /** Configured owner aliases, applied before any request. */
23
+ ownerAliases?: Record<string, string>;
24
+ signal?: AbortSignal;
25
+ logger?: (message: string, detail?: Record<string, unknown>) => void;
26
+ };
27
+ /**
28
+ * Discover every public repository for the configured owners.
29
+ *
30
+ * `me` resolves through `GET /user` (PAT required); a renamed owner is
31
+ * canonicalised through `ownerAliases` or the redirect/login in `/users/{old}`,
32
+ * and the old->new mapping is returned for the snapshot and site record.
33
+ *
34
+ * The listing is paginated by the shared client (Link: rel="next", loop and
35
+ * page guards, conditional requests). Any owner/listing failure aborts the
36
+ * whole discovery: a partial list would look like repositories disappeared and
37
+ * must never cause a deletion commit.
38
+ */
39
+ export declare function discoverRepositories(options: DiscoveryOptions): Promise<DiscoveryResult>;
@@ -0,0 +1,26 @@
1
+ import type { FetchLike } from "./client.js";
2
+ export declare const FIXTURE_SCHEMA = "loom/fixtures@1";
3
+ export type FixtureResponse = {
4
+ status?: number;
5
+ body?: unknown;
6
+ etag?: string | null;
7
+ link?: string | null;
8
+ headers?: Record<string, string>;
9
+ };
10
+ export type FixtureRoute = FixtureResponse | FixtureResponse[];
11
+ export type FixtureFile = {
12
+ schema?: string;
13
+ routes: Record<string, FixtureRoute>;
14
+ };
15
+ export type FixtureTransport = {
16
+ fetch: FetchLike;
17
+ requests: string[];
18
+ /** Paths that were requested but not present in the fixture file. */
19
+ missing: string[];
20
+ };
21
+ /**
22
+ * A `fetch` implementation backed by a recorded fixture file. It supports the
23
+ * same conditional semantics as GitHub (If-None-Match -> 304) so offline runs
24
+ * exercise the real client code path, cache included.
25
+ */
26
+ export declare function createFixtureTransport(file: FixtureFile): FixtureTransport;
@@ -0,0 +1,14 @@
1
+ export type PublicRepo = {
2
+ id: number;
3
+ fullName: string;
4
+ private: boolean;
5
+ visibility?: string;
6
+ archived: boolean;
7
+ };
8
+ /**
9
+ * Loom reads public state only. A token may be present to raise the rate limit,
10
+ * but a response that is private (or not explicitly public) is never stored.
11
+ */
12
+ export declare function assertPublicRepo(requested: string, payload: unknown): PublicRepo;
13
+ /** True when `owner/name` is syntactically acceptable as a public repo target. */
14
+ export declare function assertRepoRequest(value: string): string;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The response cache contract and an in-memory implementation.
3
+ *
4
+ * Kept separate from `cache.ts` because that module persists to disk through
5
+ * `node:fs`; the browser-safe data path imports only this file.
6
+ */
7
+ export type CacheEntry = {
8
+ /** Strong ETag from GitHub. */
9
+ etag: string;
10
+ /** Parsed response body, replayed on 304. */
11
+ body: unknown;
12
+ /** ISO timestamp of the fetch that produced the entry. */
13
+ fetchedAt: string;
14
+ /** Next-page URL from the Link header, so a 304 can continue pagination. */
15
+ next?: string | null;
16
+ };
17
+ export interface ResponseCache {
18
+ get(key: string): CacheEntry | undefined;
19
+ set(key: string, entry: CacheEntry): void;
20
+ save(): Promise<void>;
21
+ size(): number;
22
+ }
23
+ /**
24
+ * A cache that lives for one process or one page view. It still answers `304`
25
+ * responses with the previous body, so a repeated read inside one session is
26
+ * cheap without any storage permission.
27
+ */
28
+ export declare class MemoryCache implements ResponseCache {
29
+ #private;
30
+ get(key: string): CacheEntry | undefined;
31
+ set(key: string, entry: CacheEntry): void;
32
+ save(): Promise<void>;
33
+ size(): number;
34
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `@sifr-dev/loom` - public entry point.
3
+ *
4
+ * Import the framework class for embedded use, or the individual pieces when
5
+ * you only need one layer (a GitHub client, the diff engine, the site module).
6
+ * Nothing here reads the environment at import time.
7
+ */
8
+ export { Loom, createLoom, createGitHubClient, SUPPORTED_CONFIG_SCHEMAS, } from "./sdk.js";
9
+ export type { LoomEvent, LoomListener, LoomOptions, LoomPlugin, LoomPluginContext, LoomSyncOptions, SiteExportOptions, } from "./sdk.js";
10
+ export { CONFIG_SCHEMA, DEFAULT_CONFIG, isRepoGlob, isRepoName, loadConfig, parseConfig, repoGlobMatches, repoKey, } from "./config.js";
11
+ export type { CollectConfig, DiscoveryConfig, LoomConfig, ServeConfig, TriggerConfig, WatchConfig, WebhookConfig, } from "./config.js";
12
+ export { GitHubClient, nextLink, parseRateLimit } from "./github/client.js";
13
+ export type { ClientStats, FetchLike, GetAllResult, GetOptions, GetResult, GitHubClientOptions, RateLimit, } from "./github/client.js";
14
+ export { FileCache, MemoryCache } from "./github/cache.js";
15
+ export type { CacheEntry, ResponseCache } from "./github/cache.js";
16
+ export { createFixtureTransport } from "./github/fixture.js";
17
+ export type { FixtureFile, FixtureTransport } from "./github/fixture.js";
18
+ export { discoverRepositories } from "./github/discovery.js";
19
+ export type { DiscoveryOptions, DiscoveryResult, DiscoverySkipReason, } from "./github/discovery.js";
20
+ export { describeEvent, diffSnapshots, resolveRepoAlias } from "./diff.js";
21
+ export type { DiffEvent, DiffEventKind, DiffOptions, DiffResult, DiffSummary } from "./diff.js";
22
+ export { buildSiteRecord, SITE_SCHEMA, siteDigest, siteProject } from "./site.js";
23
+ export type { SiteBranch, SiteCi, SiteComment, SiteHead, SiteProject, SiteReadme, SiteRecord, SiteRelease, SiteWorkflow, } from "./site.js";
24
+ export { renderSiteModule, siteModuleDigest } from "./site-module.js";
25
+ export type { CuratedEntry, CuratedValue, SiteModuleOptions } from "./site-module.js";
26
+ export { computeSnapshot, loadFixture, runSync } from "./pipeline.js";
27
+ export type { ComputedSnapshot, Logger, RunSyncOptions, SourceOptions, SyncOutcome, } from "./pipeline.js";
28
+ export { SnapshotStore } from "./store.js";
29
+ export type { Manifest, Outbox, PutResult, StoreLock, VerifyReport } from "./store.js";
30
+ export { EXIT, LoomError } from "./errors.js";
31
+ export type { ExitCode, LoomErrorCode } from "./errors.js";
32
+ export { SNAPSHOT_SCHEMA, snapshotStats } from "./types.js";
33
+ export type { BranchSnapshot, CiSnapshot, CommitCommentSnapshot, HeadSnapshot, IssueCommentSnapshot, ReleaseSnapshot, ReadmeSnapshot, RepoSnapshot, Snapshot, SnapshotError, SnapshotPayload, SnapshotSource, SnapshotStats, WorkflowSnapshot, } from "./types.js";
34
+ export { WebhookReceiver } from "./webhook/receiver.js";
35
+ export type { WebhookDecision, WebhookInput, WebhookKind, WebhookReceiverOptions, } from "./webhook/receiver.js";
36
+ export { DeliveryLog } from "./webhook/delivery.js";
37
+ export { signBody, verifySignature } from "./webhook/signature.js";
38
+ export type { SignatureMode } from "./webhook/signature.js";
39
+ export { createHandler } from "./serve-handler.js";
40
+ export type { ServeHandler, ServeHandlerDeps } from "./serve-handler.js";
41
+ export { SyncQueue } from "./queue.js";
42
+ export type { QueueStats } from "./queue.js";
43
+ export { Metrics } from "./metrics.js";
44
+ export { VERSION } from "./version.js";
@@ -0,0 +1,16 @@
1
+ export type LogFormat = "text" | "json";
2
+ export type LoomLogger = (message: string, detail?: Record<string, unknown>) => void;
3
+ export type LoggerOptions = {
4
+ format?: LogFormat;
5
+ write?: (line: string) => void;
6
+ level?: "debug" | "info" | "warn" | "error";
7
+ now?: () => Date;
8
+ };
9
+ /**
10
+ * Structured-or-text logging with two invariants: every line is redacted, and
11
+ * JSON mode is one object per line so a collector can parse it without a
12
+ * multi-line regex. Text mode stays readable in a terminal.
13
+ */
14
+ export declare function createLogger(options?: LoggerOptions): LoomLogger;
15
+ /** Resolve `--log-format` without accepting an unknown value silently. */
16
+ export declare function parseLogFormat(value: string | null): LogFormat;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A tiny, dependency-free metrics registry with Prometheus text output.
3
+ * Counters and gauges only: Loom is a batch/polling sync engine, so a
4
+ * histogram would add ceremony without answering an operational question.
5
+ */
6
+ export type Labels = Record<string, string | number | boolean | null | undefined>;
7
+ type Sample = {
8
+ labels: Labels;
9
+ value: number;
10
+ };
11
+ export declare class Metrics {
12
+ #private;
13
+ increment(name: string, labels?: Labels, by?: number): void;
14
+ gauge(name: string, value: number, labels?: Labels): void;
15
+ observeDuration(name: string, startMs: number, labels?: Labels): void;
16
+ snapshot(): Record<string, Sample[]>;
17
+ render(): string;
18
+ }
19
+ /** Prometheus text accepts double-quoted label values; keep them valid. */
20
+ export declare function prometheusLabel(value: string): string;
21
+ export {};
@@ -0,0 +1,24 @@
1
+ import { SnapshotStore } from "./store.js";
2
+ export type MigrationStep = {
3
+ component: "manifest" | "http-cache" | "webhook-state" | "store";
4
+ from: string;
5
+ to: string;
6
+ action: "rewritten" | "quarantined" | "unchanged" | "created";
7
+ detail?: string;
8
+ };
9
+ export type MigrationReport = {
10
+ schema: "loom/migrate@1";
11
+ ok: boolean;
12
+ store: string;
13
+ steps: MigrationStep[];
14
+ };
15
+ /**
16
+ * Bring an on-disk store forward without reinterpreting data silently.
17
+ *
18
+ * Current layout is v1. The known legacy manifest (`loom/manifest@0`) is
19
+ * upgraded by reading the snapshot it points at and rebuilding stats/source;
20
+ * cache and webhook state are validated by their normal recovery readers,
21
+ * which rewrite the current schema or quarantine unreadable bytes. An unknown
22
+ * future schema is refused (`schema_unsupported`) rather than guessed.
23
+ */
24
+ export declare function migrateStore(store: SnapshotStore): Promise<MigrationReport>;
@@ -0,0 +1,73 @@
1
+ import { ownerAliasesOf, type ComputedSnapshot, type Logger, type SourceOptions as ComputeSourceOptions } from "./compute.js";
2
+ import { type DiffResult } from "./diff.js";
3
+ import type { FetchLike } from "./github/client.js";
4
+ import { type FixtureTransport } from "./github/fixture.js";
5
+ import { type Manifest, type SnapshotStore } from "./store.js";
6
+ import { type PublicTriggerPlan, type TriggerEnv, type TriggerResult } from "./triggers.js";
7
+ import type { Snapshot, SnapshotError, SnapshotStats } from "./types.js";
8
+ export { ownerAliasesOf };
9
+ export type { ComputedSnapshot, Logger };
10
+ export type SourceOptions = ComputeSourceOptions & {
11
+ /** Directory holding `responses.json`; when set, no network is used. */
12
+ fixtureDir?: string | null;
13
+ };
14
+ /** Read a recorded fixture from disk. Requires a Bun runtime. */
15
+ export declare function loadFixture(dir: string): Promise<{
16
+ transport: FixtureTransport;
17
+ baseUrl: string;
18
+ }>;
19
+ /**
20
+ * Read the configured source. A `fixtureDir` is read from disk here; callers
21
+ * that already hold recorded responses pass `fixture` directly and stay free of
22
+ * file access.
23
+ */
24
+ export declare function computeSnapshot(options: SourceOptions): Promise<ComputedSnapshot>;
25
+ export type RunSyncOptions = SourceOptions & {
26
+ store: SnapshotStore;
27
+ dryRun?: boolean;
28
+ /** Dispatch trigger adapters after a committed change. */
29
+ dispatch?: boolean;
30
+ allowMissingTriggers?: boolean;
31
+ env?: TriggerEnv;
32
+ dispatchFetch?: FetchLike;
33
+ clock?: () => Date;
34
+ /** Cross-process store lock; the CLI enables it. */
35
+ lock?: boolean;
36
+ };
37
+ export type OutboxStatus = {
38
+ pending: boolean;
39
+ snapshot: string | null;
40
+ attempts: number;
41
+ nextAttemptAt: string | null;
42
+ };
43
+ export type SyncOutcome = {
44
+ status: "created" | "unchanged" | "would-change" | "partial";
45
+ snapshot: Snapshot;
46
+ previous: Snapshot | null;
47
+ diff: DiffResult;
48
+ manifest: Manifest | null;
49
+ stats: SnapshotStats;
50
+ errors: SnapshotError[];
51
+ triggers: {
52
+ plans: PublicTriggerPlan[];
53
+ results: TriggerResult[];
54
+ deferred: boolean;
55
+ };
56
+ outbox: OutboxStatus;
57
+ requests: number;
58
+ notModified: number;
59
+ retries: number;
60
+ rateLimitWaits: number;
61
+ durationMs: number;
62
+ fixtureMissing: string[];
63
+ };
64
+ /**
65
+ * One sync:
66
+ * 1. read public state (conditional requests when a cache exists),
67
+ * 2. diff it against the committed head,
68
+ * 3. commit only when something actually changed and every repository is known,
69
+ * 4. write a durable outbox before dispatching, and clear it only after every
70
+ * trigger acknowledges. A crash between outbox, commit, and dispatch
71
+ * retries on the next run instead of silently losing the deploy.
72
+ */
73
+ export declare function runSync(options: RunSyncOptions): Promise<SyncOutcome>;
@@ -0,0 +1,33 @@
1
+ export type QueueState = "accepted" | "duplicate" | "full" | "closed";
2
+ export type QueueEnqueue<T> = {
3
+ state: QueueState;
4
+ /** Resolves with the job result; rejects with the job error. */
5
+ promise: Promise<T>;
6
+ };
7
+ export type QueueStats = {
8
+ depth: number;
9
+ active: number;
10
+ enqueued: number;
11
+ completed: number;
12
+ failed: number;
13
+ rejectedFull: number;
14
+ deduped: number;
15
+ closed: boolean;
16
+ };
17
+ export type QueueOptions = {
18
+ maxDepth?: number;
19
+ onDepth?: (depth: number, active: number) => void;
20
+ };
21
+ export declare class SyncQueue {
22
+ #private;
23
+ constructor(options?: QueueOptions);
24
+ get stats(): QueueStats;
25
+ enqueue<T>(key: string, job: () => Promise<T>): QueueEnqueue<T>;
26
+ /** Wait until every accepted job settles, or the deadline expires. */
27
+ drain(timeoutMs?: number): Promise<{
28
+ drained: boolean;
29
+ stats: QueueStats;
30
+ }>;
31
+ /** Stop accepting new work; queued work still runs. */
32
+ close(): void;
33
+ }