@scwrap/client 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jakob Kruse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @scwrap/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An Effect-first HTTP client for a private Scwrap instance. Input and item types come directly from the scraper Definition; there is no generated client or second registry. Import the scraper's schema-only module, not its deployment or implementation.
4
+
5
+ ```ts
6
+ import { createClient } from "@scwrap/client";
7
+ import { Earthquakes } from "@scwrap/earthquakes/schema";
8
+ import { Effect, Redacted, Stream } from "effect";
9
+ import { FetchHttpClient } from "effect/http";
10
+
11
+ const program = Effect.gen(function* () {
12
+ const client = yield* createClient({
13
+ instance: "https://your-instance.example",
14
+ token: Redacted.make(runToken),
15
+ });
16
+ return yield* Stream.runCollect(client.scraper(Earthquakes).stream(query));
17
+ }).pipe(Effect.provide(FetchHttpClient.layer));
18
+ ```
19
+
20
+ `runToken` and the typed `query` come from your application.
21
+
22
+ ## Operations
23
+
24
+ - `client.catalog()` reads installed identities and generation.
25
+ - `client.scraper(Definition).stream(input)` runs, then streams the items decoded with the output schema, then fails with the Run's `failure` decoded against the error schema; an undecodable failure becomes `ClientFailure` with the record's `error` string.
26
+ - `.start(input)` takes the encoded input, sends it as raw JSON, and returns the `running` result record from the instance's 202 answer. `run(input)` starts the same way, then polls the result record every 2 seconds until it is `completed` or `failed`; a failed Run is a result, not an error.
27
+ - `.result(resultId)` reads metadata and checks the result ID and scraper ID.
28
+ - `.items(resultId)` checks metadata first, then incrementally decodes NDJSON with the output schema. Terminal streams must contain the recorded count. An interrupted or malformed stream fails even if earlier items were valid.
29
+
30
+ Output and error decoding services remain in the inferred Effect/Stream requirements. The caller supplies an `effect/http` HttpClient. The codecs' wire values must be JSON. Errors use `ClientFailure`, with HTTP status when available; `stream` also fails with the Definition's declared errors.
31
+
32
+ ## Defaults and boundaries
33
+
34
+ Items are checked against your Definition and fail on anything it does not accept, including unknown fields. The result record names the build that produced it in `revision`, `digest` and `implementationDigest`.
35
+
36
+ Failed runs can expose valid partial items. Successfully reading those items does not mean the scrape succeeded. Running-result reads are snapshots, not live tails; their count can change between metadata and item requests.
37
+
38
+ Use a trusted HTTPS origin and the instance's run token, never the deployer token or Cloudflare or Runner credentials. Fetch redirects are disabled. Supply a plain HttpClient without retry or redirect middleware: retrying a start whose answer was lost can execute it twice. Interrupting `run` stops polling, not the Run. `runs({ cursor, limit })` lists a Scraper's result records newest first. This package adds no retries or cancellation. Server-side applications and Workers are the target; do not expose the run token to browsers. There is no Promise facade in this initial API.
39
+
40
+ `@scwrap/client/protocol` exports the neutral `ResultRecord`, `ReleaseIdentity`, `ScraperCatalog` and `RunList` schemas, depending only on Effect. The Worker and MCP share these contracts without making HTTP calls to themselves. Deployment admission constraints and deployment status stay in `@scwrap/deploy/protocol`.
@@ -0,0 +1,93 @@
1
+ import type { ScraperDefinition } from "@scwrap/domain";
2
+ import type { Redacted } from "effect";
3
+ import { Effect, Schema, Stream } from "effect";
4
+ import { HttpClient } from "effect/http";
5
+ declare const ClientFailure_base: Schema.Class<ClientFailure, Schema.TaggedStruct<"ClientFailure", {
6
+ readonly reason: Schema.String;
7
+ readonly status: Schema.optionalKey<Schema.Int>;
8
+ }>, import("effect/Cause").YieldableError>;
9
+ export declare class ClientFailure extends ClientFailure_base {
10
+ }
11
+ interface Connection {
12
+ readonly instance: string;
13
+ readonly token: Redacted.Redacted;
14
+ }
15
+ export declare const createClient: (options: Connection) => Effect.Effect<{
16
+ catalog: () => Effect.Effect<{
17
+ readonly generation: string | null;
18
+ readonly scrapers: readonly {
19
+ readonly digest: string;
20
+ readonly id: string;
21
+ readonly nodeDigest?: string | undefined;
22
+ readonly revision: string;
23
+ }[];
24
+ }, ClientFailure, HttpClient.HttpClient>;
25
+ scraper: <Tag extends string, Input extends Schema.Top, Output extends Schema.Top, Error extends Schema.Top>(definition: ScraperDefinition<Tag, Input, Output, Error>) => {
26
+ items: (resultId: string) => Stream.Stream<Output["Type"], ClientFailure, HttpClient.HttpClient | Output["DecodingServices"]>;
27
+ result: (resultId: string) => Effect.Effect<{
28
+ readonly count: number;
29
+ readonly digest: string;
30
+ readonly endedAt: number | null;
31
+ readonly error: string | null;
32
+ readonly failure?: Schema.Json;
33
+ readonly implementationDigest: string;
34
+ readonly input: Schema.Json;
35
+ readonly resultId: string;
36
+ readonly revision: string;
37
+ readonly scraper: string;
38
+ readonly startedAt: number;
39
+ readonly status: "completed" | "failed" | "running";
40
+ }, ClientFailure, HttpClient.HttpClient>;
41
+ run: (input: Input["Encoded"]) => Effect.Effect<{
42
+ readonly count: number;
43
+ readonly digest: string;
44
+ readonly endedAt: number | null;
45
+ readonly error: string | null;
46
+ readonly failure?: Schema.Json;
47
+ readonly implementationDigest: string;
48
+ readonly input: Schema.Json;
49
+ readonly resultId: string;
50
+ readonly revision: string;
51
+ readonly scraper: string;
52
+ readonly startedAt: number;
53
+ readonly status: "completed" | "failed" | "running";
54
+ }, ClientFailure, HttpClient.HttpClient>;
55
+ runs: (page?: {
56
+ readonly cursor?: string;
57
+ readonly limit?: number;
58
+ } | undefined) => Effect.Effect<{
59
+ readonly nextCursor: string | null;
60
+ readonly runs: readonly {
61
+ readonly count: number;
62
+ readonly digest: string;
63
+ readonly endedAt: number | null;
64
+ readonly error: string | null;
65
+ readonly failure?: Schema.Json;
66
+ readonly implementationDigest: string;
67
+ readonly input: Schema.Json;
68
+ readonly resultId: string;
69
+ readonly revision: string;
70
+ readonly scraper: string;
71
+ readonly startedAt: number;
72
+ readonly status: "completed" | "failed" | "running";
73
+ }[];
74
+ }, ClientFailure, HttpClient.HttpClient>;
75
+ start: (input: Input["Encoded"]) => Effect.Effect<{
76
+ readonly count: number;
77
+ readonly digest: string;
78
+ readonly endedAt: number | null;
79
+ readonly error: string | null;
80
+ readonly failure?: Schema.Json;
81
+ readonly implementationDigest: string;
82
+ readonly input: Schema.Json;
83
+ readonly resultId: string;
84
+ readonly revision: string;
85
+ readonly scraper: string;
86
+ readonly startedAt: number;
87
+ readonly status: "completed" | "failed" | "running";
88
+ }, ClientFailure, HttpClient.HttpClient>;
89
+ stream: (input: Input["Encoded"]) => Stream.Stream<Output["Type"], ClientFailure | Error["Type"], HttpClient.HttpClient | Error["DecodingServices"] | Output["DecodingServices"]>;
90
+ };
91
+ }, ClientFailure, never>;
92
+ export {};
93
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,MAAM,EAAiB,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE/D,OAAO,EAEL,UAAU,EAGX,MAAM,aAAa,CAAC;;;;;AAIrB,qBAAa,aAAc,SAAQ,kBAGlC;CAAG;AAEJ,UAAU,UAAU;IAClB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC;CACnC;AAED,eAAO,MAAM,YAAY;;;;;;;;;;cA6CrB,GAAG,SAAS,MAAM,EAClB,KAAK,SAAS,MAAM,CAAC,GAAG,EACxB,MAAM,SAAS,MAAM,CAAC,GAAG,EACzB,KAAK,SAAS,MAAM,CAAC,GAAG,cAEZ,iBAAiB,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC;0BAmJpC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BAKI,MAAM;6BAAmB,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAgC3C,KAAK,CAAC,SAAS,CAAC;;wBAiCpC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,116 @@
1
+ import { Scraper } from "@scwrap/domain";
2
+ import { Effect, Ref, Schedule, Schema, Stream } from "effect";
3
+ import { Ndjson } from "effect/encoding";
4
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse, } from "effect/http";
5
+ import { ResultRecord, RunList, ScraperCatalog } from "./protocol.js";
6
+ export class ClientFailure extends Schema.TaggedError()("ClientFailure", { reason: Schema.String, status: Schema.optionalKey(Schema.Int) }) {
7
+ }
8
+ export const createClient = Effect.fn("Client.make")(function* createClient(options) {
9
+ const url = yield* Effect.try({
10
+ catch: () => new ClientFailure({ reason: "Invalid instance URL" }),
11
+ try: () => new URL(options.instance),
12
+ });
13
+ if (url.protocol !== "https:" ||
14
+ url.username !== "" ||
15
+ url.password !== "" ||
16
+ url.pathname !== "/" ||
17
+ url.search !== "" ||
18
+ url.hash !== "") {
19
+ return yield* new ClientFailure({
20
+ reason: "Instance must be an HTTPS origin without credentials",
21
+ });
22
+ }
23
+ const send = Effect.fn("Client.request")(function* send(request, accepted) {
24
+ const response = yield* HttpClient.execute(request.pipe(HttpClientRequest.bearerToken(options.token))).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), Effect.mapError(() => new ClientFailure({ reason: "HTTP request failed" })));
25
+ if (response.status !== (accepted === true ? 202 : 200)) {
26
+ return yield* new ClientFailure({
27
+ reason: "Instance rejected request",
28
+ status: response.status,
29
+ });
30
+ }
31
+ return response;
32
+ });
33
+ const scraper = (definition) => {
34
+ const target = Scraper.rpc(definition);
35
+ const check = Effect.fn("Client.checkResult")(function* check(record) {
36
+ const rpc = yield* target;
37
+ if (record.scraper !== rpc._tag) {
38
+ return yield* new ClientFailure({ reason: "Result identity mismatch" });
39
+ }
40
+ return record;
41
+ });
42
+ const result = Effect.fn("Client.result")(function* result(resultId) {
43
+ const response = yield* send(HttpClientRequest.get(`${url.origin}/results/${encodeURIComponent(resultId)}`));
44
+ const record = yield* HttpClientResponse.schemaBodyJson(ResultRecord)(response).pipe(Effect.mapError(() => new ClientFailure({ reason: "Invalid result record" })));
45
+ if (record.resultId !== resultId) {
46
+ return yield* new ClientFailure({ reason: "Result ID mismatch" });
47
+ }
48
+ return yield* check(record);
49
+ });
50
+ const start = Effect.fn("Client.start")(function* start(input) {
51
+ const rpc = yield* target;
52
+ const encoded = yield* Schema.decodeUnknownEffect(Schema.Json)(input).pipe(Effect.mapError(() => new ClientFailure({ reason: "Invalid scraper input" })));
53
+ const request = yield* HttpClientRequest.post(`${url.origin}/scrapers/${encodeURIComponent(rpc._tag)}/run`).pipe(HttpClientRequest.bodyJson(encoded), Effect.mapError(() => new ClientFailure({ reason: "Input is not JSON encodable" })));
54
+ const response = yield* send(request, true);
55
+ const record = yield* HttpClientResponse.schemaBodyJson(ResultRecord)(response).pipe(Effect.mapError(() => new ClientFailure({ reason: "Invalid result record" })));
56
+ if (record.status !== "running") {
57
+ return yield* new ClientFailure({ reason: "Invalid started status" });
58
+ }
59
+ return yield* check(record);
60
+ });
61
+ const run = Effect.fn("Client.run")(function* run(input) {
62
+ const started = yield* start(input);
63
+ return yield* result(started.resultId).pipe(Effect.repeat({
64
+ schedule: Schedule.spaced("2 seconds"),
65
+ until: ({ status }) => status !== "running",
66
+ }));
67
+ });
68
+ const itemsOf = (record) => Stream.unwrap(Effect.gen(function* readItems() {
69
+ const rpc = yield* target;
70
+ const count = yield* Ref.make(0);
71
+ const response = yield* send(HttpClientRequest.get(`${url.origin}/results/${encodeURIComponent(record.resultId)}/items`));
72
+ return response.stream.pipe(Stream.pipeThroughChannel(Ndjson.decode()), Stream.mapEffect((item) => Schema.decodeUnknownEffect(rpc.successSchema.success, {
73
+ onExcessProperty: "error",
74
+ })(item)), Stream.mapError(() => new ClientFailure({ reason: "Invalid item stream" })), Stream.tap(() => Ref.update(count, (n) => n + 1)), Stream.concat(Stream.fromEffect(Ref.get(count).pipe(Effect.flatMap((actual) => record.status === "running" || actual === record.count
75
+ ? Effect.void
76
+ : Effect.fail(new ClientFailure({ reason: "Item count mismatch" }))))).pipe(Stream.drain)));
77
+ }));
78
+ const failed = Effect.fn("Client.failure")(function* failed(record) {
79
+ const rpc = yield* target;
80
+ const error = yield* Schema.decodeUnknownEffect(rpc.successSchema.error)(record.failure).pipe(Effect.mapError(() => new ClientFailure({ reason: record.error ?? "Run failed" })));
81
+ return yield* Effect.fail(error);
82
+ });
83
+ return {
84
+ items: (resultId) => Stream.unwrap(Effect.map(result(resultId), itemsOf)),
85
+ result,
86
+ run,
87
+ runs: Effect.fn("Client.runs")(function* runs(page = {}) {
88
+ const rpc = yield* target;
89
+ const query = new URLSearchParams({ limit: String(page.limit ?? 50) });
90
+ if (page.cursor !== undefined) {
91
+ query.set("cursor", page.cursor);
92
+ }
93
+ const response = yield* send(HttpClientRequest.get(`${url.origin}/scrapers/${encodeURIComponent(rpc._tag)}/runs?${query.toString()}`));
94
+ const listed = yield* HttpClientResponse.schemaBodyJson(RunList)(response).pipe(Effect.mapError(() => new ClientFailure({ reason: "Invalid run list" })));
95
+ if (listed.runs.some((record) => record.scraper !== rpc._tag)) {
96
+ return yield* new ClientFailure({
97
+ reason: "Result identity mismatch",
98
+ });
99
+ }
100
+ return listed;
101
+ }),
102
+ start,
103
+ stream: (input) => Stream.unwrap(run(input).pipe(Effect.map((record) => itemsOf(record).pipe(Stream.concat(record.status === "failed"
104
+ ? Stream.drain(Stream.fromEffect(failed(record)))
105
+ : Stream.empty))))),
106
+ };
107
+ };
108
+ return {
109
+ catalog: Effect.fn("Client.catalog")(function* catalog() {
110
+ const response = yield* send(HttpClientRequest.get(`${url.origin}/scrapers`));
111
+ return yield* HttpClientResponse.schemaBodyJson(ScraperCatalog)(response).pipe(Effect.mapError(() => new ClientFailure({ reason: "Invalid scraper catalog" })));
112
+ }),
113
+ scraper,
114
+ };
115
+ });
116
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAGzC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,eAAe,EACf,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEtE,MAAM,OAAO,aAAc,SAAQ,MAAM,CAAC,WAAW,EAAiB,CACpE,eAAe,EACf,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAA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C1B,iBAAiB,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,MAAM,WAAW,CAAC,CAChD,CAAC;YAEF,OAAO,KAAK,CAAC,CAAC,kBAAkB,CAAC,cAAc,CAAC,cAAc,CAAC,CAC7D,QAAQ,CACT,CAAC,IAAI,CACJ,MAAM,CAAC,QAAQ,CACb,GAAG,EAAE,CAAC,IAAI,aAAa,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,CAC/D,CACF,CAAC;QACJ,CAAC,CAAC;QACF,OAAO;KACR,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -0,0 +1,48 @@
1
+ import { Schema } from "effect";
2
+ export declare const ReleaseIdentity: Schema.Struct<{
3
+ readonly digest: Schema.String;
4
+ readonly id: Schema.String;
5
+ readonly nodeDigest: Schema.optional<Schema.String>;
6
+ readonly revision: Schema.String;
7
+ }>;
8
+ export declare const ScraperCatalog: Schema.Struct<{
9
+ readonly generation: Schema.NullOr<Schema.String>;
10
+ readonly scrapers: Schema.$Array<Schema.Struct<{
11
+ readonly digest: Schema.String;
12
+ readonly id: Schema.String;
13
+ readonly nodeDigest: Schema.optional<Schema.String>;
14
+ readonly revision: Schema.String;
15
+ }>>;
16
+ }>;
17
+ export declare const ResultRecord: Schema.Struct<{
18
+ readonly count: Schema.Int;
19
+ readonly digest: Schema.String;
20
+ readonly endedAt: Schema.NullOr<Schema.Finite>;
21
+ readonly error: Schema.NullOr<Schema.String>;
22
+ readonly failure: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
23
+ readonly implementationDigest: Schema.String;
24
+ readonly input: Schema.Codec<Schema.Json, Schema.Json, never, never>;
25
+ readonly resultId: Schema.String;
26
+ readonly revision: Schema.String;
27
+ readonly scraper: Schema.String;
28
+ readonly startedAt: Schema.Finite;
29
+ readonly status: Schema.Literals<readonly ["running", "completed", "failed"]>;
30
+ }>;
31
+ export declare const RunList: Schema.Struct<{
32
+ readonly nextCursor: Schema.NullOr<Schema.String>;
33
+ readonly runs: Schema.$Array<Schema.Struct<{
34
+ readonly count: Schema.Int;
35
+ readonly digest: Schema.String;
36
+ readonly endedAt: Schema.NullOr<Schema.Finite>;
37
+ readonly error: Schema.NullOr<Schema.String>;
38
+ readonly failure: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
39
+ readonly implementationDigest: Schema.String;
40
+ readonly input: Schema.Codec<Schema.Json, Schema.Json, never, never>;
41
+ readonly resultId: Schema.String;
42
+ readonly revision: Schema.String;
43
+ readonly scraper: Schema.String;
44
+ readonly startedAt: Schema.Finite;
45
+ readonly status: Schema.Literals<readonly ["running", "completed", "failed"]>;
46
+ }>>;
47
+ }>;
48
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,eAAe;;;;;EAK1B,CAAC;AAEH,eAAO,MAAM,cAAc;;;;;;;;EAGzB,CAAC;AAEH,eAAO,MAAM,YAAY;;;;;;;;;;;;;EAavB,CAAC;AAEH,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;;EAGlB,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { Schema } from "effect";
2
+ export const ReleaseIdentity = Schema.Struct({
3
+ digest: Schema.String,
4
+ id: Schema.String,
5
+ nodeDigest: Schema.optional(Schema.String),
6
+ revision: Schema.String,
7
+ });
8
+ export const ScraperCatalog = Schema.Struct({
9
+ generation: Schema.NullOr(Schema.String),
10
+ scrapers: Schema.Array(ReleaseIdentity),
11
+ });
12
+ export const ResultRecord = Schema.Struct({
13
+ count: Schema.Int,
14
+ digest: Schema.String,
15
+ endedAt: Schema.NullOr(Schema.Finite),
16
+ error: Schema.NullOr(Schema.String),
17
+ failure: Schema.optionalKey(Schema.Json),
18
+ implementationDigest: Schema.String,
19
+ input: Schema.Json,
20
+ resultId: Schema.String,
21
+ revision: Schema.String,
22
+ scraper: Schema.String,
23
+ startedAt: Schema.Finite,
24
+ status: Schema.Literals(["running", "completed", "failed"]),
25
+ });
26
+ export const RunList = Schema.Struct({
27
+ nextCursor: Schema.NullOr(Schema.String),
28
+ runs: Schema.Array(ResultRecord),
29
+ });
30
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC;IAC3C,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,EAAE,EAAE,MAAM,CAAC,MAAM;IACjB,UAAU,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1C,QAAQ,EAAE,MAAM,CAAC,MAAM;CACxB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IACxC,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC;CACxC,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;IACxC,KAAK,EAAE,MAAM,CAAC,GAAG;IACjB,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IACrC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC;IACxC,oBAAoB,EAAE,MAAM,CAAC,MAAM;IACnC,KAAK,EAAE,MAAM,CAAC,IAAI;IAClB,QAAQ,EAAE,MAAM,CAAC,MAAM;IACvB,QAAQ,EAAE,MAAM,CAAC,MAAM;IACvB,OAAO,EAAE,MAAM,CAAC,MAAM;IACtB,SAAS,EAAE,MAAM,CAAC,MAAM;IACxB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;CAC5D,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;IACnC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IACxC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC;CACjC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@scwrap/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Typed client for a Scwrap instance: run Scrapers and read their results.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/J4K4-Dev/scwrap.git",
9
+ "directory": "packages/client"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./protocol": {
24
+ "types": "./dist/protocol.d.ts",
25
+ "import": "./dist/protocol.js",
26
+ "default": "./dist/protocol.js"
27
+ }
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@scwrap/domain": "0.1.0"
34
+ },
35
+ "devDependencies": {
36
+ "@effect/vitest": "4.0.5",
37
+ "@types/node": "24.13.6",
38
+ "effect": "4.0.5",
39
+ "typescript": "7.0.2",
40
+ "vitest": "5.0.1"
41
+ },
42
+ "peerDependencies": {
43
+ "effect": "4.0.5"
44
+ },
45
+ "scripts": {
46
+ "typecheck": "tsc --noEmit -p tsconfig.json",
47
+ "test": "vitest run",
48
+ "build": "tsc -p tsconfig.build.json"
49
+ }
6
50
  }
package/src/index.ts ADDED
@@ -0,0 +1,292 @@
1
+ import { Scraper } from "@scwrap/domain";
2
+ import type { ScraperDefinition } from "@scwrap/domain";
3
+ import type { Redacted } from "effect";
4
+ import { Effect, Ref, Schedule, Schema, Stream } from "effect";
5
+ import { Ndjson } from "effect/encoding";
6
+ import {
7
+ FetchHttpClient,
8
+ HttpClient,
9
+ HttpClientRequest,
10
+ HttpClientResponse,
11
+ } from "effect/http";
12
+
13
+ import { ResultRecord, RunList, ScraperCatalog } from "./protocol.js";
14
+
15
+ export class ClientFailure extends Schema.TaggedError<ClientFailure>()(
16
+ "ClientFailure",
17
+ { reason: Schema.String, status: Schema.optionalKey(Schema.Int) }
18
+ ) {}
19
+
20
+ interface Connection {
21
+ readonly instance: string;
22
+ readonly token: Redacted.Redacted;
23
+ }
24
+
25
+ export const createClient = Effect.fn("Client.make")(function* createClient(
26
+ options: Connection
27
+ ) {
28
+ const url = yield* Effect.try({
29
+ catch: () => new ClientFailure({ reason: "Invalid instance URL" }),
30
+ try: () => new URL(options.instance),
31
+ });
32
+
33
+ if (
34
+ url.protocol !== "https:" ||
35
+ url.username !== "" ||
36
+ url.password !== "" ||
37
+ url.pathname !== "/" ||
38
+ url.search !== "" ||
39
+ url.hash !== ""
40
+ ) {
41
+ return yield* new ClientFailure({
42
+ reason: "Instance must be an HTTPS origin without credentials",
43
+ });
44
+ }
45
+
46
+ const send = Effect.fn("Client.request")(function* send(
47
+ request: HttpClientRequest.HttpClientRequest,
48
+ accepted?: boolean
49
+ ) {
50
+ const response = yield* HttpClient.execute(
51
+ request.pipe(HttpClientRequest.bearerToken(options.token))
52
+ ).pipe(
53
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
54
+ Effect.mapError(
55
+ () => new ClientFailure({ reason: "HTTP request failed" })
56
+ )
57
+ );
58
+
59
+ if (response.status !== (accepted === true ? 202 : 200)) {
60
+ return yield* new ClientFailure({
61
+ reason: "Instance rejected request",
62
+ status: response.status,
63
+ });
64
+ }
65
+
66
+ return response;
67
+ });
68
+
69
+ const scraper = <
70
+ Tag extends string,
71
+ Input extends Schema.Top,
72
+ Output extends Schema.Top,
73
+ Error extends Schema.Top,
74
+ >(
75
+ definition: ScraperDefinition<Tag, Input, Output, Error>
76
+ ) => {
77
+ const target = Scraper.rpc(definition);
78
+
79
+ const check = Effect.fn("Client.checkResult")(function* check(
80
+ record: typeof ResultRecord.Type
81
+ ) {
82
+ const rpc = yield* target;
83
+
84
+ if (record.scraper !== rpc._tag) {
85
+ return yield* new ClientFailure({ reason: "Result identity mismatch" });
86
+ }
87
+
88
+ return record;
89
+ });
90
+
91
+ const result = Effect.fn("Client.result")(function* result(
92
+ resultId: string
93
+ ) {
94
+ const response = yield* send(
95
+ HttpClientRequest.get(
96
+ `${url.origin}/results/${encodeURIComponent(resultId)}`
97
+ )
98
+ );
99
+
100
+ const record = yield* HttpClientResponse.schemaBodyJson(ResultRecord)(
101
+ response
102
+ ).pipe(
103
+ Effect.mapError(
104
+ () => new ClientFailure({ reason: "Invalid result record" })
105
+ )
106
+ );
107
+
108
+ if (record.resultId !== resultId) {
109
+ return yield* new ClientFailure({ reason: "Result ID mismatch" });
110
+ }
111
+
112
+ return yield* check(record);
113
+ });
114
+
115
+ const start = Effect.fn("Client.start")(function* start(
116
+ input: Input["Encoded"]
117
+ ) {
118
+ const rpc = yield* target;
119
+
120
+ const encoded = yield* Schema.decodeUnknownEffect(Schema.Json)(
121
+ input
122
+ ).pipe(
123
+ Effect.mapError(
124
+ () => new ClientFailure({ reason: "Invalid scraper input" })
125
+ )
126
+ );
127
+
128
+ const request = yield* HttpClientRequest.post(
129
+ `${url.origin}/scrapers/${encodeURIComponent(rpc._tag)}/run`
130
+ ).pipe(
131
+ HttpClientRequest.bodyJson(encoded),
132
+ Effect.mapError(
133
+ () => new ClientFailure({ reason: "Input is not JSON encodable" })
134
+ )
135
+ );
136
+
137
+ const response = yield* send(request, true);
138
+
139
+ const record = yield* HttpClientResponse.schemaBodyJson(ResultRecord)(
140
+ response
141
+ ).pipe(
142
+ Effect.mapError(
143
+ () => new ClientFailure({ reason: "Invalid result record" })
144
+ )
145
+ );
146
+
147
+ if (record.status !== "running") {
148
+ return yield* new ClientFailure({ reason: "Invalid started status" });
149
+ }
150
+
151
+ return yield* check(record);
152
+ });
153
+
154
+ const run = Effect.fn("Client.run")(function* run(input: Input["Encoded"]) {
155
+ const started = yield* start(input);
156
+
157
+ return yield* result(started.resultId).pipe(
158
+ Effect.repeat({
159
+ schedule: Schedule.spaced("2 seconds"),
160
+ until: ({ status }) => status !== "running",
161
+ })
162
+ );
163
+ });
164
+
165
+ const itemsOf = (record: typeof ResultRecord.Type) =>
166
+ Stream.unwrap(
167
+ Effect.gen(function* readItems() {
168
+ const rpc = yield* target;
169
+ const count = yield* Ref.make(0);
170
+
171
+ const response = yield* send(
172
+ HttpClientRequest.get(
173
+ `${url.origin}/results/${encodeURIComponent(record.resultId)}/items`
174
+ )
175
+ );
176
+
177
+ return response.stream.pipe(
178
+ Stream.pipeThroughChannel(Ndjson.decode()),
179
+ Stream.mapEffect((item) =>
180
+ Schema.decodeUnknownEffect(rpc.successSchema.success, {
181
+ onExcessProperty: "error",
182
+ })(item)
183
+ ),
184
+ Stream.mapError(
185
+ () => new ClientFailure({ reason: "Invalid item stream" })
186
+ ),
187
+ Stream.tap(() => Ref.update(count, (n) => n + 1)),
188
+ Stream.concat(
189
+ Stream.fromEffect(
190
+ Ref.get(count).pipe(
191
+ Effect.flatMap((actual) =>
192
+ record.status === "running" || actual === record.count
193
+ ? Effect.void
194
+ : Effect.fail(
195
+ new ClientFailure({ reason: "Item count mismatch" })
196
+ )
197
+ )
198
+ )
199
+ ).pipe(Stream.drain)
200
+ )
201
+ );
202
+ })
203
+ );
204
+
205
+ const failed = Effect.fn("Client.failure")(function* failed(
206
+ record: typeof ResultRecord.Type
207
+ ) {
208
+ const rpc = yield* target;
209
+
210
+ const error = yield* Schema.decodeUnknownEffect(rpc.successSchema.error)(
211
+ record.failure
212
+ ).pipe(
213
+ Effect.mapError(
214
+ () => new ClientFailure({ reason: record.error ?? "Run failed" })
215
+ )
216
+ );
217
+
218
+ return yield* Effect.fail(error);
219
+ });
220
+
221
+ return {
222
+ items: (resultId: string) =>
223
+ Stream.unwrap(Effect.map(result(resultId), itemsOf)),
224
+ result,
225
+ run,
226
+ runs: Effect.fn("Client.runs")(function* runs(
227
+ page: { readonly cursor?: string; readonly limit?: number } = {}
228
+ ) {
229
+ const rpc = yield* target;
230
+ const query = new URLSearchParams({ limit: String(page.limit ?? 50) });
231
+
232
+ if (page.cursor !== undefined) {
233
+ query.set("cursor", page.cursor);
234
+ }
235
+
236
+ const response = yield* send(
237
+ HttpClientRequest.get(
238
+ `${url.origin}/scrapers/${encodeURIComponent(rpc._tag)}/runs?${query.toString()}`
239
+ )
240
+ );
241
+
242
+ const listed = yield* HttpClientResponse.schemaBodyJson(RunList)(
243
+ response
244
+ ).pipe(
245
+ Effect.mapError(
246
+ () => new ClientFailure({ reason: "Invalid run list" })
247
+ )
248
+ );
249
+
250
+ if (listed.runs.some((record) => record.scraper !== rpc._tag)) {
251
+ return yield* new ClientFailure({
252
+ reason: "Result identity mismatch",
253
+ });
254
+ }
255
+
256
+ return listed;
257
+ }),
258
+ start,
259
+ stream: (input: Input["Encoded"]) =>
260
+ Stream.unwrap(
261
+ run(input).pipe(
262
+ Effect.map((record) =>
263
+ itemsOf(record).pipe(
264
+ Stream.concat(
265
+ record.status === "failed"
266
+ ? Stream.drain(Stream.fromEffect(failed(record)))
267
+ : Stream.empty
268
+ )
269
+ )
270
+ )
271
+ )
272
+ ),
273
+ };
274
+ };
275
+
276
+ return {
277
+ catalog: Effect.fn("Client.catalog")(function* catalog() {
278
+ const response = yield* send(
279
+ HttpClientRequest.get(`${url.origin}/scrapers`)
280
+ );
281
+
282
+ return yield* HttpClientResponse.schemaBodyJson(ScraperCatalog)(
283
+ response
284
+ ).pipe(
285
+ Effect.mapError(
286
+ () => new ClientFailure({ reason: "Invalid scraper catalog" })
287
+ )
288
+ );
289
+ }),
290
+ scraper,
291
+ };
292
+ });
@@ -0,0 +1,33 @@
1
+ import { Schema } from "effect";
2
+
3
+ export const ReleaseIdentity = Schema.Struct({
4
+ digest: Schema.String,
5
+ id: Schema.String,
6
+ nodeDigest: Schema.optional(Schema.String),
7
+ revision: Schema.String,
8
+ });
9
+
10
+ export const ScraperCatalog = Schema.Struct({
11
+ generation: Schema.NullOr(Schema.String),
12
+ scrapers: Schema.Array(ReleaseIdentity),
13
+ });
14
+
15
+ export const ResultRecord = Schema.Struct({
16
+ count: Schema.Int,
17
+ digest: Schema.String,
18
+ endedAt: Schema.NullOr(Schema.Finite),
19
+ error: Schema.NullOr(Schema.String),
20
+ failure: Schema.optionalKey(Schema.Json),
21
+ implementationDigest: Schema.String,
22
+ input: Schema.Json,
23
+ resultId: Schema.String,
24
+ revision: Schema.String,
25
+ scraper: Schema.String,
26
+ startedAt: Schema.Finite,
27
+ status: Schema.Literals(["running", "completed", "failed"]),
28
+ });
29
+
30
+ export const RunList = Schema.Struct({
31
+ nextCursor: Schema.NullOr(Schema.String),
32
+ runs: Schema.Array(ResultRecord),
33
+ });