@jini-ai/capability-providers 0.1.2 → 0.4.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/CHANGELOG.md +95 -0
- package/README.md +174 -0
- package/dist/adapters/blob-storage/index.d.ts +67 -0
- package/dist/adapters/blob-storage/index.js +62 -0
- package/dist/adapters/jwt-auth/index.d.ts +53 -0
- package/dist/adapters/jwt-auth/index.js +182 -0
- package/dist/adapters/sqlite/index.d.ts +56 -0
- package/dist/adapters/sqlite/index.js +83 -0
- package/dist/adapters/stripe/index.d.ts +94 -0
- package/dist/adapters/stripe/index.js +167 -0
- package/dist/adapters/ws/index.d.ts +95 -0
- package/dist/adapters/ws/index.js +161 -0
- package/dist/auth.d.ts +22 -47
- package/dist/auth.js +10 -173
- package/dist/db.d.ts +11 -48
- package/dist/db.js +15 -79
- package/dist/index.d.ts +54 -1
- package/dist/index.js +54 -1
- package/dist/payments.d.ts +21 -74
- package/dist/payments.js +13 -175
- package/dist/realtime.d.ts +24 -73
- package/dist/realtime.js +14 -140
- package/dist/storage.d.ts +23 -49
- package/dist/storage.js +13 -57
- package/dist/tokens.js +6 -6
- package/dist/unsafe-reference/auth.d.ts +1 -1
- package/dist/unsafe-reference/auth.js +3 -3
- package/dist/unsafe-reference/db.d.ts +2 -2
- package/dist/unsafe-reference/index.d.ts +1 -1
- package/dist/unsafe-reference/index.js +1 -1
- package/dist/unsafe-reference/payments.d.ts +3 -1
- package/dist/unsafe-reference/payments.js +6 -5
- package/dist/unsafe-reference/realtime.d.ts +1 -1
- package/dist/unsafe-reference/realtime.js +4 -4
- package/dist/unsafe-reference/storage.d.ts +3 -1
- package/dist/unsafe-reference/storage.js +7 -6
- package/dist/visitor-auth/definitions.d.ts +32 -0
- package/dist/visitor-auth/definitions.js +57 -0
- package/dist/visitor-auth/index.d.ts +17 -0
- package/dist/visitor-auth/index.js +17 -0
- package/dist/visitor-auth/lifecycle.d.ts +101 -0
- package/dist/visitor-auth/lifecycle.js +326 -0
- package/dist/visitor-auth/ports.d.ts +134 -0
- package/dist/visitor-auth/ports.js +2 -0
- package/dist/visitor-auth/registry.d.ts +38 -0
- package/dist/visitor-auth/registry.js +78 -0
- package/dist/visitor-auth/tokens.d.ts +10 -0
- package/dist/visitor-auth/tokens.js +9 -0
- package/package.json +66 -9
- package/dist/auth.d.ts.map +0 -1
- package/dist/auth.js.map +0 -1
- package/dist/db.d.ts.map +0 -1
- package/dist/db.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/payments.d.ts.map +0 -1
- package/dist/payments.js.map +0 -1
- package/dist/realtime.d.ts.map +0 -1
- package/dist/realtime.js.map +0 -1
- package/dist/storage.d.ts.map +0 -1
- package/dist/storage.js.map +0 -1
- package/dist/tokens.d.ts.map +0 -1
- package/dist/tokens.js.map +0 -1
- package/dist/unsafe-reference/auth.d.ts.map +0 -1
- package/dist/unsafe-reference/auth.js.map +0 -1
- package/dist/unsafe-reference/db.d.ts.map +0 -1
- package/dist/unsafe-reference/db.js.map +0 -1
- package/dist/unsafe-reference/index.d.ts.map +0 -1
- package/dist/unsafe-reference/index.js.map +0 -1
- package/dist/unsafe-reference/payments.d.ts.map +0 -1
- package/dist/unsafe-reference/payments.js.map +0 -1
- package/dist/unsafe-reference/realtime.d.ts.map +0 -1
- package/dist/unsafe-reference/realtime.js.map +0 -1
- package/dist/unsafe-reference/storage.d.ts.map +0 -1
- package/dist/unsafe-reference/storage.js.map +0 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@jini-ai/capability-providers/adapters/sqlite` — the one real,
|
|
3
|
+
* production-quality `DbProvider` adapter this package ships, backed directly
|
|
4
|
+
* by `better-sqlite3`, following `@jini-ai/sqlite-chat`'s `createSqliteEventLog`
|
|
5
|
+
* DI/schema conventions (an injected, already-open `Database` handle;
|
|
6
|
+
* idempotent `CREATE TABLE IF NOT EXISTS`; multi-statement writes wrapped in
|
|
7
|
+
* `db.transaction()`).
|
|
8
|
+
*
|
|
9
|
+
* Lives at this separate entry point (not the package's main
|
|
10
|
+
* `@jini-ai/capability-providers` barrel) so importing the port
|
|
11
|
+
* interface/types/DI tokens never forces a consumer to resolve
|
|
12
|
+
* `better-sqlite3` — including in its emitted `.d.ts`, where the
|
|
13
|
+
* `Database.Database` type reference would otherwise make the main barrel
|
|
14
|
+
* unresolvable for a TypeScript consumer who never installed the optional
|
|
15
|
+
* peer. Import from here only when you actually want this concrete adapter.
|
|
16
|
+
*
|
|
17
|
+
* The in-memory reference implementation (`createInMemoryDbProvider`) is a
|
|
18
|
+
* separate, non-production stub under `src/unsafe-reference/` — see that
|
|
19
|
+
* directory's `index.ts` header for the full warning.
|
|
20
|
+
*/
|
|
21
|
+
import type Database from 'better-sqlite3';
|
|
22
|
+
import type { DbProvider, DbQuery, DbRecord } from '../../db.js';
|
|
23
|
+
/** Alias for a `better-sqlite3` `Database` handle, matching `@jini-ai/sqlite-chat`'s own `SqliteDb` alias (`packages/sqlite-chat/src/db/core/types.ts`). */
|
|
24
|
+
type SqliteDatabase = Database.Database;
|
|
25
|
+
/**
|
|
26
|
+
* `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
|
|
27
|
+
* Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
|
|
28
|
+
* `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
|
|
29
|
+
* client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
|
|
30
|
+
* deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
|
|
31
|
+
* framing and the in-memory reference adapter's identical semantics, so behavior is identical
|
|
32
|
+
* between the two adapters for every input.
|
|
33
|
+
*
|
|
34
|
+
* Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
|
|
35
|
+
* — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
|
|
36
|
+
* re-run against an already-migrated handle) and never opens or closes a connection itself,
|
|
37
|
+
* mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
|
|
38
|
+
* convention for tests.
|
|
39
|
+
*/
|
|
40
|
+
export declare class SqliteDbProvider implements DbProvider {
|
|
41
|
+
private readonly getStmt;
|
|
42
|
+
private readonly insertStmt;
|
|
43
|
+
private readonly updateStmt;
|
|
44
|
+
private readonly deleteStmt;
|
|
45
|
+
private readonly queryStmt;
|
|
46
|
+
private readonly insertTxn;
|
|
47
|
+
private readonly updateTxn;
|
|
48
|
+
constructor(db: SqliteDatabase);
|
|
49
|
+
insert(collection: string, record: DbRecord): Promise<DbRecord>;
|
|
50
|
+
get(collection: string, id: string): Promise<DbRecord | null>;
|
|
51
|
+
update(collection: string, id: string, patch: Readonly<Record<string, unknown>>): Promise<DbRecord | null>;
|
|
52
|
+
delete(collection: string, id: string): Promise<void>;
|
|
53
|
+
query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
|
|
54
|
+
}
|
|
55
|
+
export {};
|
|
56
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** Exact-match filter used by both `query()` here and the in-memory reference adapter's own `matchesWhere` — kept as an independent, self-contained copy rather than a shared import so this adapter has no dependency on `src/unsafe-reference/`. */
|
|
2
|
+
function matchesWhere(record, where) {
|
|
3
|
+
if (!where)
|
|
4
|
+
return true;
|
|
5
|
+
return Object.entries(where).every(([key, value]) => record[key] === value);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
|
|
9
|
+
* Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
|
|
10
|
+
* `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
|
|
11
|
+
* client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
|
|
12
|
+
* deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
|
|
13
|
+
* framing and the in-memory reference adapter's identical semantics, so behavior is identical
|
|
14
|
+
* between the two adapters for every input.
|
|
15
|
+
*
|
|
16
|
+
* Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
|
|
17
|
+
* — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
|
|
18
|
+
* re-run against an already-migrated handle) and never opens or closes a connection itself,
|
|
19
|
+
* mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
|
|
20
|
+
* convention for tests.
|
|
21
|
+
*/
|
|
22
|
+
export class SqliteDbProvider {
|
|
23
|
+
getStmt;
|
|
24
|
+
insertStmt;
|
|
25
|
+
updateStmt;
|
|
26
|
+
deleteStmt;
|
|
27
|
+
queryStmt;
|
|
28
|
+
insertTxn;
|
|
29
|
+
updateTxn;
|
|
30
|
+
constructor(db) {
|
|
31
|
+
db.exec(`
|
|
32
|
+
CREATE TABLE IF NOT EXISTS jini_capability_db_records (
|
|
33
|
+
collection TEXT NOT NULL,
|
|
34
|
+
id TEXT NOT NULL,
|
|
35
|
+
data TEXT NOT NULL,
|
|
36
|
+
PRIMARY KEY (collection, id)
|
|
37
|
+
);
|
|
38
|
+
`);
|
|
39
|
+
this.getStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ? AND id = ?');
|
|
40
|
+
this.insertStmt = db.prepare('INSERT INTO jini_capability_db_records (collection, id, data) VALUES (?, ?, ?)');
|
|
41
|
+
this.updateStmt = db.prepare('UPDATE jini_capability_db_records SET data = ? WHERE collection = ? AND id = ?');
|
|
42
|
+
this.deleteStmt = db.prepare('DELETE FROM jini_capability_db_records WHERE collection = ? AND id = ?');
|
|
43
|
+
this.queryStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ?');
|
|
44
|
+
// Wrapped in db.transaction() for the same reason createSqliteEventLog wraps its
|
|
45
|
+
// dedupe-check + insert: a single atomic unit of work at the SQL level, not a JS-level race
|
|
46
|
+
// guard (better-sqlite3 is synchronous, so no other JS can run between the get() and run()
|
|
47
|
+
// calls within one process either way).
|
|
48
|
+
this.insertTxn = db.transaction((collection, record) => {
|
|
49
|
+
const existing = this.getStmt.get(collection, record.id);
|
|
50
|
+
if (existing) {
|
|
51
|
+
throw new Error(`record already exists: ${collection}/${record.id}`);
|
|
52
|
+
}
|
|
53
|
+
this.insertStmt.run(collection, record.id, JSON.stringify(record));
|
|
54
|
+
return record;
|
|
55
|
+
});
|
|
56
|
+
this.updateTxn = db.transaction((collection, id, patch) => {
|
|
57
|
+
const row = this.getStmt.get(collection, id);
|
|
58
|
+
if (!row)
|
|
59
|
+
return null;
|
|
60
|
+
const updated = { ...JSON.parse(row.data), ...patch, id };
|
|
61
|
+
this.updateStmt.run(JSON.stringify(updated), collection, id);
|
|
62
|
+
return updated;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
async insert(collection, record) {
|
|
66
|
+
return this.insertTxn(collection, record);
|
|
67
|
+
}
|
|
68
|
+
async get(collection, id) {
|
|
69
|
+
const row = this.getStmt.get(collection, id);
|
|
70
|
+
return row ? JSON.parse(row.data) : null;
|
|
71
|
+
}
|
|
72
|
+
async update(collection, id, patch) {
|
|
73
|
+
return this.updateTxn(collection, id, patch);
|
|
74
|
+
}
|
|
75
|
+
async delete(collection, id) {
|
|
76
|
+
this.deleteStmt.run(collection, id);
|
|
77
|
+
}
|
|
78
|
+
async query(collection, query = {}) {
|
|
79
|
+
const rows = this.queryStmt.all(collection);
|
|
80
|
+
return rows.map((row) => JSON.parse(row.data)).filter((record) => matchesWhere(record, query.where));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@jini-ai/capability-providers/adapters/stripe` — the one real,
|
|
3
|
+
* production-quality `PaymentsProvider` adapter this package ships, against
|
|
4
|
+
* Stripe's real, documented Charges/Refunds REST API
|
|
5
|
+
* (`https://docs.stripe.com/api/charges`, `https://docs.stripe.com/api/refunds`)
|
|
6
|
+
* — verified against Stripe's own docs while building this, not guessed from
|
|
7
|
+
* memory (request shape, Basic auth over the secret key, form-encoded body,
|
|
8
|
+
* JSON error envelope).
|
|
9
|
+
*
|
|
10
|
+
* Lives at this separate entry point (not the package's main
|
|
11
|
+
* `@jini-ai/capability-providers` barrel) so importing the port
|
|
12
|
+
* interface/types/DI tokens never pulls a vendor-specific HTTP client into a
|
|
13
|
+
* consumer that only wanted the `PaymentsProvider` interface to implement
|
|
14
|
+
* itself against a different processor. Import from here only when you actually
|
|
15
|
+
* want this concrete adapter.
|
|
16
|
+
*
|
|
17
|
+
* The in-memory reference implementation (`createInMemoryPaymentsProvider`) is
|
|
18
|
+
* a separate, non-production stub under `src/unsafe-reference/` — see that
|
|
19
|
+
* directory's `index.ts` header for the full warning.
|
|
20
|
+
*/
|
|
21
|
+
import type { Charge, ChargeInput, PaymentsProvider } from '../../payments.js';
|
|
22
|
+
/** Error thrown by {@link StripePaymentsProvider}, carrying Stripe's own error envelope fields (`https://docs.stripe.com/api/errors`) when the failure came from a Stripe API response. */
|
|
23
|
+
export declare class StripePaymentsProviderError extends Error {
|
|
24
|
+
/** The HTTP status Stripe (or a local pre-flight check) returned. */
|
|
25
|
+
readonly status: number;
|
|
26
|
+
/** Stripe's `error.type` — one of `api_error`, `card_error`, `idempotency_error`, `invalid_request_error`. Undefined for a local pre-flight rejection (e.g. a non-positive amount) that never reached Stripe. */
|
|
27
|
+
readonly stripeType?: string;
|
|
28
|
+
/** Stripe's `error.code`, when present. */
|
|
29
|
+
readonly stripeCode?: string;
|
|
30
|
+
constructor({ message, status }: {
|
|
31
|
+
message: string;
|
|
32
|
+
status: number;
|
|
33
|
+
}, { stripeType, stripeCode }?: {
|
|
34
|
+
stripeType?: string;
|
|
35
|
+
stripeCode?: string;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export interface StripePaymentsProviderOptions {
|
|
39
|
+
/** Stripe secret key (`sk_live_...`/`sk_test_...`). Required and explicit — never read from an environment variable inside this adapter. */
|
|
40
|
+
readonly secretKey: string;
|
|
41
|
+
}
|
|
42
|
+
export interface StripePaymentsProviderOptionalArgs {
|
|
43
|
+
/** Clock used when a response omits its creation timestamp. */
|
|
44
|
+
readonly now?: () => number;
|
|
45
|
+
/** Pluggable fetch for tests. Defaults to `globalThis.fetch`, matching `S3BlobStorage`/`netlify.ts`'s precedent in this repo. */
|
|
46
|
+
readonly fetchFn?: typeof fetch;
|
|
47
|
+
/** Overrides Stripe's API base URL. Tests only — production leaves this unset. */
|
|
48
|
+
readonly apiBase?: string;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* `PaymentsProvider` adapter against Stripe's real Charges/Refunds REST API. No mock/simulated
|
|
52
|
+
* money movement — every `charge`/`getCharge`/`refund` call is a real HTTP request to
|
|
53
|
+
* `api.stripe.com` (or `optional.apiBase` in tests), authenticated the way Stripe's own docs
|
|
54
|
+
* specify: HTTP Basic auth with the secret key as the username and an empty password
|
|
55
|
+
* (`Authorization: Basic base64("sk_...:")`), request bodies form-encoded
|
|
56
|
+
* (`application/x-www-form-urlencoded`), not JSON.
|
|
57
|
+
*
|
|
58
|
+
* `ChargeInput.customerRef` is sent as Stripe's `customer` parameter — this adapter always
|
|
59
|
+
* charges an existing Stripe Customer (who must already have a default/attached payment method),
|
|
60
|
+
* never a one-off `source`/token; `ChargeInput` has no field for a raw card token, and inventing
|
|
61
|
+
* one wasn't part of this port's brief.
|
|
62
|
+
*/
|
|
63
|
+
export declare class StripePaymentsProvider implements PaymentsProvider {
|
|
64
|
+
private readonly options;
|
|
65
|
+
private readonly fetchFn;
|
|
66
|
+
private readonly apiBase;
|
|
67
|
+
private readonly now;
|
|
68
|
+
constructor(options: StripePaymentsProviderOptions, optional?: StripePaymentsProviderOptionalArgs);
|
|
69
|
+
charge(input: ChargeInput, optional?: {
|
|
70
|
+
description?: string;
|
|
71
|
+
}): Promise<Charge>;
|
|
72
|
+
getCharge({ id }: {
|
|
73
|
+
id: string;
|
|
74
|
+
}): Promise<Charge | null>;
|
|
75
|
+
/**
|
|
76
|
+
* `PaymentsProvider.refund` returns a completed `Charge`, but a real Stripe `Refund` object's
|
|
77
|
+
* own `status` can be `'succeeded'`, `'pending'` (common for bank-sourced refunds that settle
|
|
78
|
+
* over days), `'failed'`, or `'canceled'` — a richer state machine than this port's
|
|
79
|
+
* `ChargeStatus` has room for. Since `ChargeStatus` has no "refund in flight" state, `'pending'`
|
|
80
|
+
* is treated the same as `'succeeded'` here (Stripe accepted the refund; it will settle) and
|
|
81
|
+
* only `'failed'`/`'canceled'` reject. A host that needs to distinguish "refund accepted" from
|
|
82
|
+
* "refund settled" should track Stripe's own refund object separately — out of scope for this
|
|
83
|
+
* port's `Charge`-shaped return value.
|
|
84
|
+
*/
|
|
85
|
+
refund({ id }: {
|
|
86
|
+
id: string;
|
|
87
|
+
}): Promise<Charge>;
|
|
88
|
+
private authHeader;
|
|
89
|
+
private request;
|
|
90
|
+
private safeJson;
|
|
91
|
+
private toError;
|
|
92
|
+
private toCharge;
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
const STRIPE_API_BASE = 'https://api.stripe.com/v1';
|
|
2
|
+
/** Error thrown by {@link StripePaymentsProvider}, carrying Stripe's own error envelope fields (`https://docs.stripe.com/api/errors`) when the failure came from a Stripe API response. */
|
|
3
|
+
export class StripePaymentsProviderError extends Error {
|
|
4
|
+
/** The HTTP status Stripe (or a local pre-flight check) returned. */
|
|
5
|
+
status;
|
|
6
|
+
/** Stripe's `error.type` — one of `api_error`, `card_error`, `idempotency_error`, `invalid_request_error`. Undefined for a local pre-flight rejection (e.g. a non-positive amount) that never reached Stripe. */
|
|
7
|
+
stripeType;
|
|
8
|
+
/** Stripe's `error.code`, when present. */
|
|
9
|
+
stripeCode;
|
|
10
|
+
constructor({ message, status }, { stripeType, stripeCode } = {}) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'StripePaymentsProviderError';
|
|
13
|
+
this.status = status;
|
|
14
|
+
if (stripeType !== undefined)
|
|
15
|
+
this.stripeType = stripeType;
|
|
16
|
+
if (stripeCode !== undefined)
|
|
17
|
+
this.stripeCode = stripeCode;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Maps a raw Stripe Charge JSON object's `status` (`'succeeded' | 'pending' | 'failed'` per
|
|
22
|
+
* Stripe's documented Charge object) plus its separate `refunded` boolean onto this port's
|
|
23
|
+
* `ChargeStatus`. `refunded: true` always wins — Stripe leaves `status` at `'succeeded'` even
|
|
24
|
+
* after a full refund, but this port's `ChargeStatus` models "refunded" as its own terminal
|
|
25
|
+
* state distinct from "succeeded", so a charge this adapter itself refunded (or that was
|
|
26
|
+
* refunded directly in Stripe) reports as `'refunded'` here.
|
|
27
|
+
*/
|
|
28
|
+
function mapStripeChargeStatus(raw, refunded) {
|
|
29
|
+
if (refunded === true)
|
|
30
|
+
return 'refunded';
|
|
31
|
+
if (raw === 'succeeded' || raw === 'pending' || raw === 'failed')
|
|
32
|
+
return raw;
|
|
33
|
+
// Stripe's Charge.status is documented as exactly succeeded | pending | failed — this branch
|
|
34
|
+
// has no real reachable path against Stripe's actual contract, but keeps the mapping total
|
|
35
|
+
// against `unknown` JSON (an arbitrary HTTP response body) rather than asserting.
|
|
36
|
+
return 'pending';
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* `PaymentsProvider` adapter against Stripe's real Charges/Refunds REST API. No mock/simulated
|
|
40
|
+
* money movement — every `charge`/`getCharge`/`refund` call is a real HTTP request to
|
|
41
|
+
* `api.stripe.com` (or `optional.apiBase` in tests), authenticated the way Stripe's own docs
|
|
42
|
+
* specify: HTTP Basic auth with the secret key as the username and an empty password
|
|
43
|
+
* (`Authorization: Basic base64("sk_...:")`), request bodies form-encoded
|
|
44
|
+
* (`application/x-www-form-urlencoded`), not JSON.
|
|
45
|
+
*
|
|
46
|
+
* `ChargeInput.customerRef` is sent as Stripe's `customer` parameter — this adapter always
|
|
47
|
+
* charges an existing Stripe Customer (who must already have a default/attached payment method),
|
|
48
|
+
* never a one-off `source`/token; `ChargeInput` has no field for a raw card token, and inventing
|
|
49
|
+
* one wasn't part of this port's brief.
|
|
50
|
+
*/
|
|
51
|
+
export class StripePaymentsProvider {
|
|
52
|
+
options;
|
|
53
|
+
fetchFn;
|
|
54
|
+
apiBase;
|
|
55
|
+
now;
|
|
56
|
+
constructor(options, optional = {}) {
|
|
57
|
+
this.options = options;
|
|
58
|
+
if (!options.secretKey) {
|
|
59
|
+
throw new StripePaymentsProviderError({ message: 'StripePaymentsProvider requires a non-empty options.secretKey', status: 401 });
|
|
60
|
+
}
|
|
61
|
+
const fn = optional.fetchFn ?? globalThis.fetch;
|
|
62
|
+
if (!fn) {
|
|
63
|
+
throw new StripePaymentsProviderError({ message: 'StripePaymentsProvider requires a fetch implementation', status: 500 });
|
|
64
|
+
}
|
|
65
|
+
this.fetchFn = fn;
|
|
66
|
+
this.now = optional.now ?? Date.now;
|
|
67
|
+
this.apiBase = (optional.apiBase ?? STRIPE_API_BASE).replace(/\/+$/, '');
|
|
68
|
+
}
|
|
69
|
+
async charge(input, optional = {}) {
|
|
70
|
+
if (input.amountCents <= 0) {
|
|
71
|
+
throw new StripePaymentsProviderError({ message: 'amountCents must be positive', status: 400 });
|
|
72
|
+
}
|
|
73
|
+
const body = new URLSearchParams({
|
|
74
|
+
amount: String(input.amountCents),
|
|
75
|
+
currency: input.currency,
|
|
76
|
+
customer: input.customerRef,
|
|
77
|
+
});
|
|
78
|
+
if (optional.description !== undefined)
|
|
79
|
+
body.set('description', optional.description);
|
|
80
|
+
const json = await this.request('POST', '/charges', body);
|
|
81
|
+
return this.toCharge(json);
|
|
82
|
+
}
|
|
83
|
+
async getCharge({ id }) {
|
|
84
|
+
try {
|
|
85
|
+
const json = await this.request('GET', `/charges/${encodeURIComponent(id)}`);
|
|
86
|
+
return this.toCharge(json);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err instanceof StripePaymentsProviderError && err.status === 404)
|
|
90
|
+
return null;
|
|
91
|
+
throw err;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* `PaymentsProvider.refund` returns a completed `Charge`, but a real Stripe `Refund` object's
|
|
96
|
+
* own `status` can be `'succeeded'`, `'pending'` (common for bank-sourced refunds that settle
|
|
97
|
+
* over days), `'failed'`, or `'canceled'` — a richer state machine than this port's
|
|
98
|
+
* `ChargeStatus` has room for. Since `ChargeStatus` has no "refund in flight" state, `'pending'`
|
|
99
|
+
* is treated the same as `'succeeded'` here (Stripe accepted the refund; it will settle) and
|
|
100
|
+
* only `'failed'`/`'canceled'` reject. A host that needs to distinguish "refund accepted" from
|
|
101
|
+
* "refund settled" should track Stripe's own refund object separately — out of scope for this
|
|
102
|
+
* port's `Charge`-shaped return value.
|
|
103
|
+
*/
|
|
104
|
+
async refund({ id }) {
|
|
105
|
+
const existing = await this.getCharge({ id });
|
|
106
|
+
if (!existing) {
|
|
107
|
+
throw new StripePaymentsProviderError({ message: `unknown charge: ${id}`, status: 404 });
|
|
108
|
+
}
|
|
109
|
+
if (existing.status !== 'succeeded') {
|
|
110
|
+
throw new StripePaymentsProviderError({ message: `charge ${id} is not refundable from status "${existing.status}"`, status: 400 });
|
|
111
|
+
}
|
|
112
|
+
const json = await this.request('POST', '/refunds', new URLSearchParams({ charge: id }));
|
|
113
|
+
const refundStatus = json.status;
|
|
114
|
+
if (refundStatus === 'failed' || refundStatus === 'canceled') {
|
|
115
|
+
throw new StripePaymentsProviderError({ message: `Stripe refund ${String(refundStatus)} for charge ${id}`, status: 402 }, { stripeType: 'api_error' });
|
|
116
|
+
}
|
|
117
|
+
return { ...existing, status: 'refunded' };
|
|
118
|
+
}
|
|
119
|
+
authHeader() {
|
|
120
|
+
const bytes = new TextEncoder().encode(`${this.options.secretKey}:`);
|
|
121
|
+
return `Basic ${btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''))}`;
|
|
122
|
+
}
|
|
123
|
+
async request(method, path, formBody) {
|
|
124
|
+
const headers = { Authorization: this.authHeader() };
|
|
125
|
+
const init = { method, headers };
|
|
126
|
+
if (formBody) {
|
|
127
|
+
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
128
|
+
init.body = formBody.toString();
|
|
129
|
+
}
|
|
130
|
+
const res = await this.fetchFn(`${this.apiBase}${path}`, init);
|
|
131
|
+
const json = await this.safeJson(res);
|
|
132
|
+
if (!res.ok)
|
|
133
|
+
throw this.toError(res.status, json);
|
|
134
|
+
return json;
|
|
135
|
+
}
|
|
136
|
+
async safeJson(res) {
|
|
137
|
+
try {
|
|
138
|
+
const parsed = await res.json();
|
|
139
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return {};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
toError(status, json) {
|
|
146
|
+
const errorObj = json.error && typeof json.error === 'object' ? json.error : {};
|
|
147
|
+
const message = typeof errorObj.message === 'string' && errorObj.message ? errorObj.message : `Stripe request failed (${status}).`;
|
|
148
|
+
const stripeType = typeof errorObj.type === 'string' ? errorObj.type : undefined;
|
|
149
|
+
const stripeCode = typeof errorObj.code === 'string' ? errorObj.code : undefined;
|
|
150
|
+
return new StripePaymentsProviderError({ message, status }, {
|
|
151
|
+
...(stripeType === undefined ? {} : { stripeType }),
|
|
152
|
+
...(stripeCode === undefined ? {} : { stripeCode }),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
toCharge(json) {
|
|
156
|
+
return {
|
|
157
|
+
id: typeof json.id === 'string' ? json.id : '',
|
|
158
|
+
status: mapStripeChargeStatus(json.status, json.refunded),
|
|
159
|
+
amountCents: typeof json.amount === 'number' ? json.amount : 0,
|
|
160
|
+
currency: typeof json.currency === 'string' ? json.currency : '',
|
|
161
|
+
customerRef: typeof json.customer === 'string' ? json.customer : '',
|
|
162
|
+
// Stripe's `created` is Unix seconds; this port's `createdAt` is epoch milliseconds.
|
|
163
|
+
createdAt: typeof json.created === 'number' ? json.created * 1000 : this.now(),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@jini-ai/capability-providers/adapters/ws` — the one real, production-quality
|
|
3
|
+
* `RealtimeProvider` adapter this package ships, using WebSockets (the `ws`
|
|
4
|
+
* package): a self-contained pub/sub server, no external hosted-realtime-service
|
|
5
|
+
* dependency (no Pusher/Ably/Supabase Realtime).
|
|
6
|
+
*
|
|
7
|
+
* Lives at this separate entry point (not the package's main
|
|
8
|
+
* `@jini-ai/capability-providers` barrel) so importing the port
|
|
9
|
+
* interface/types/DI tokens never forces a consumer — or a bundler that
|
|
10
|
+
* can't resolve Node-only packages — to also resolve `ws`. Import from here
|
|
11
|
+
* only when you actually want this concrete adapter.
|
|
12
|
+
*/
|
|
13
|
+
import { WebSocketServer, type ServerOptions } from 'ws';
|
|
14
|
+
import type { RealtimeHandler, RealtimeProvider, RealtimeUnsubscribe } from '../../realtime.js';
|
|
15
|
+
/**
|
|
16
|
+
* The minimal structural subset of a `ws` `WebSocket` connection this adapter depends on. A native socket is adapted by the factory; tests construct a plain fake
|
|
17
|
+
* (an `EventEmitter`-backed object) satisfying the same shape, so `WebSocketRealtimeProvider`'s
|
|
18
|
+
* core logic is fully unit-testable with zero real sockets/ports.
|
|
19
|
+
*/
|
|
20
|
+
export interface RealtimeWebSocketLike {
|
|
21
|
+
readonly readyState: number;
|
|
22
|
+
send(required: {
|
|
23
|
+
data: string;
|
|
24
|
+
}): void;
|
|
25
|
+
on(required: {
|
|
26
|
+
event: 'message';
|
|
27
|
+
listener: (data: unknown) => void;
|
|
28
|
+
}): void;
|
|
29
|
+
on(required: {
|
|
30
|
+
event: 'close';
|
|
31
|
+
listener: () => void;
|
|
32
|
+
}): void;
|
|
33
|
+
on(required: {
|
|
34
|
+
event: 'error';
|
|
35
|
+
listener: (err: Error) => void;
|
|
36
|
+
}): void;
|
|
37
|
+
}
|
|
38
|
+
/** The minimal structural subset of a `ws` `WebSocketServer` this adapter depends on. */
|
|
39
|
+
export interface RealtimeWebSocketServerLike {
|
|
40
|
+
on(required: {
|
|
41
|
+
event: 'connection';
|
|
42
|
+
listener: (socket: RealtimeWebSocketLike) => void;
|
|
43
|
+
}): void;
|
|
44
|
+
}
|
|
45
|
+
export interface WebSocketRealtimeProviderOptions {
|
|
46
|
+
/** The (real or fake) WebSocket server to accept subscriber connections from. */
|
|
47
|
+
readonly server: RealtimeWebSocketServerLike;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* `RealtimeProvider` adapter using WebSockets: a self-contained pub/sub server, no external
|
|
51
|
+
* hosted-realtime-service dependency. Two subscriber shapes fan out from the same `publish()`:
|
|
52
|
+
*
|
|
53
|
+
* 1. **In-process** subscribers registered via `subscribe()` — called synchronously, exactly
|
|
54
|
+
* like the in-memory reference adapter (same handler-Set-per-channel bookkeeping).
|
|
55
|
+
* 2. **Remote WebSocket clients** — connect through the injected server, then send
|
|
56
|
+
* `{"type":"subscribe","channel":"..."}` / `{"type":"unsubscribe","channel":"..."}` JSON
|
|
57
|
+
* messages to opt in/out of channels. `publish()` sends each currently-subscribed, still-open
|
|
58
|
+
* socket a `{"type":"event","channel":"...","event":...}` JSON message. A closed connection is
|
|
59
|
+
* cleaned out of every channel it was subscribed to.
|
|
60
|
+
*
|
|
61
|
+
* The constructor takes a `RealtimeWebSocketServerLike` — structurally satisfied by a real
|
|
62
|
+
* `ws.WebSocketServer` (see `createWebSocketRealtimeProvider` below) or, in tests, a fake with no
|
|
63
|
+
* real socket/port — so the channel-routing/subscription-bookkeeping core here is fully
|
|
64
|
+
* unit-testable without any real network I/O.
|
|
65
|
+
*/
|
|
66
|
+
export declare class WebSocketRealtimeProvider implements RealtimeProvider {
|
|
67
|
+
private readonly handlersByChannel;
|
|
68
|
+
private readonly socketsByChannel;
|
|
69
|
+
constructor(options: WebSocketRealtimeProviderOptions);
|
|
70
|
+
private handleConnection;
|
|
71
|
+
private socketsFor;
|
|
72
|
+
private handlersFor;
|
|
73
|
+
publish<T>({ channel, event }: {
|
|
74
|
+
channel: string;
|
|
75
|
+
event: T;
|
|
76
|
+
}): Promise<void>;
|
|
77
|
+
subscribe<T>({ channel, handler }: {
|
|
78
|
+
channel: string;
|
|
79
|
+
handler: RealtimeHandler<T>;
|
|
80
|
+
}): RealtimeUnsubscribe;
|
|
81
|
+
}
|
|
82
|
+
export interface CreateWebSocketRealtimeProviderOptions {
|
|
83
|
+
/** Passed straight through to `ws`'s `WebSocketServer` constructor — e.g. `{ port: 8080 }` to listen standalone, or `{ server: httpServer }`/`{ noServer: true }` to share an existing HTTP server's upgrade handling. */
|
|
84
|
+
readonly wsOptions: ServerOptions;
|
|
85
|
+
}
|
|
86
|
+
/** The optional createServer port injects server construction; native ws is the default adapter. The real, production entry point: constructs an actual `ws.WebSocketServer` and wires a `WebSocketRealtimeProvider` to it. Callers that want to inject a fake server for tests should construct `WebSocketRealtimeProvider` directly instead. */
|
|
87
|
+
export declare function createWebSocketRealtimeProvider(options: CreateWebSocketRealtimeProviderOptions, optional?: {
|
|
88
|
+
createServer?: (required: {
|
|
89
|
+
wsOptions: ServerOptions;
|
|
90
|
+
}) => WebSocketServer;
|
|
91
|
+
}): {
|
|
92
|
+
readonly provider: WebSocketRealtimeProvider;
|
|
93
|
+
readonly server: WebSocketServer;
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@jini-ai/capability-providers/adapters/ws` — the one real, production-quality
|
|
3
|
+
* `RealtimeProvider` adapter this package ships, using WebSockets (the `ws`
|
|
4
|
+
* package): a self-contained pub/sub server, no external hosted-realtime-service
|
|
5
|
+
* dependency (no Pusher/Ably/Supabase Realtime).
|
|
6
|
+
*
|
|
7
|
+
* Lives at this separate entry point (not the package's main
|
|
8
|
+
* `@jini-ai/capability-providers` barrel) so importing the port
|
|
9
|
+
* interface/types/DI tokens never forces a consumer — or a bundler that
|
|
10
|
+
* can't resolve Node-only packages — to also resolve `ws`. Import from here
|
|
11
|
+
* only when you actually want this concrete adapter.
|
|
12
|
+
*/
|
|
13
|
+
import { WebSocketServer } from 'ws';
|
|
14
|
+
/** WebSocket `readyState` value meaning "open and ready to communicate" (WHATWG WebSocket spec; `ws`'s `WebSocket.OPEN` is the same constant `1`). Spelled out locally so `WebSocketRealtimeProvider`'s core class has no runtime import of `ws` — only the `RealtimeWebSocketLike`/`RealtimeWebSocketServerLike` structural types below, and the `createWebSocketRealtimeProvider` factory, actually touch the real package. */
|
|
15
|
+
const WEBSOCKET_OPEN_STATE = 1;
|
|
16
|
+
/** Parses one inbound client message. Returns `null` for anything not shaped like `{type: 'subscribe'|'unsubscribe', channel: string}` — malformed/unrecognized messages are silently ignored rather than closing the connection, matching a pub/sub transport's normal tolerance for unknown message shapes (e.g. a future protocol version). */
|
|
17
|
+
function parseClientMessage(raw) {
|
|
18
|
+
let text;
|
|
19
|
+
if (typeof raw === 'string') {
|
|
20
|
+
text = raw;
|
|
21
|
+
}
|
|
22
|
+
else if (Buffer.isBuffer(raw)) {
|
|
23
|
+
text = raw.toString('utf8');
|
|
24
|
+
}
|
|
25
|
+
else if (raw instanceof ArrayBuffer) {
|
|
26
|
+
text = Buffer.from(raw).toString('utf8');
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(text);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (!parsed || typeof parsed !== 'object')
|
|
39
|
+
return null;
|
|
40
|
+
const obj = parsed;
|
|
41
|
+
if ((obj.type !== 'subscribe' && obj.type !== 'unsubscribe') || typeof obj.channel !== 'string')
|
|
42
|
+
return null;
|
|
43
|
+
return { type: obj.type, channel: obj.channel };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* `RealtimeProvider` adapter using WebSockets: a self-contained pub/sub server, no external
|
|
47
|
+
* hosted-realtime-service dependency. Two subscriber shapes fan out from the same `publish()`:
|
|
48
|
+
*
|
|
49
|
+
* 1. **In-process** subscribers registered via `subscribe()` — called synchronously, exactly
|
|
50
|
+
* like the in-memory reference adapter (same handler-Set-per-channel bookkeeping).
|
|
51
|
+
* 2. **Remote WebSocket clients** — connect through the injected server, then send
|
|
52
|
+
* `{"type":"subscribe","channel":"..."}` / `{"type":"unsubscribe","channel":"..."}` JSON
|
|
53
|
+
* messages to opt in/out of channels. `publish()` sends each currently-subscribed, still-open
|
|
54
|
+
* socket a `{"type":"event","channel":"...","event":...}` JSON message. A closed connection is
|
|
55
|
+
* cleaned out of every channel it was subscribed to.
|
|
56
|
+
*
|
|
57
|
+
* The constructor takes a `RealtimeWebSocketServerLike` — structurally satisfied by a real
|
|
58
|
+
* `ws.WebSocketServer` (see `createWebSocketRealtimeProvider` below) or, in tests, a fake with no
|
|
59
|
+
* real socket/port — so the channel-routing/subscription-bookkeeping core here is fully
|
|
60
|
+
* unit-testable without any real network I/O.
|
|
61
|
+
*/
|
|
62
|
+
export class WebSocketRealtimeProvider {
|
|
63
|
+
handlersByChannel = new Map();
|
|
64
|
+
socketsByChannel = new Map();
|
|
65
|
+
constructor(options) {
|
|
66
|
+
options.server.on({ event: 'connection', listener: (socket) => this.handleConnection(socket) });
|
|
67
|
+
}
|
|
68
|
+
handleConnection(socket) {
|
|
69
|
+
const subscribedChannels = new Set();
|
|
70
|
+
socket.on({ event: 'message', listener: (raw) => {
|
|
71
|
+
const message = parseClientMessage(raw);
|
|
72
|
+
if (!message)
|
|
73
|
+
return;
|
|
74
|
+
if (message.type === 'subscribe') {
|
|
75
|
+
subscribedChannels.add(message.channel);
|
|
76
|
+
this.socketsFor(message.channel).add(socket);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
subscribedChannels.delete(message.channel);
|
|
80
|
+
this.socketsByChannel.get(message.channel)?.delete(socket);
|
|
81
|
+
}
|
|
82
|
+
} });
|
|
83
|
+
socket.on({ event: 'close', listener: () => {
|
|
84
|
+
for (const channel of subscribedChannels) {
|
|
85
|
+
this.socketsByChannel.get(channel)?.delete(socket);
|
|
86
|
+
}
|
|
87
|
+
} });
|
|
88
|
+
// Swallow — `ws` always follows an 'error' with a 'close' for the same socket, which already
|
|
89
|
+
// performs the subscription cleanup above; there is nothing additional to do here.
|
|
90
|
+
socket.on({ event: 'error', listener: () => { } });
|
|
91
|
+
}
|
|
92
|
+
socketsFor(channel) {
|
|
93
|
+
let sockets = this.socketsByChannel.get(channel);
|
|
94
|
+
if (!sockets) {
|
|
95
|
+
sockets = new Set();
|
|
96
|
+
this.socketsByChannel.set(channel, sockets);
|
|
97
|
+
}
|
|
98
|
+
return sockets;
|
|
99
|
+
}
|
|
100
|
+
handlersFor(channel) {
|
|
101
|
+
let handlers = this.handlersByChannel.get(channel);
|
|
102
|
+
if (!handlers) {
|
|
103
|
+
handlers = new Set();
|
|
104
|
+
this.handlersByChannel.set(channel, handlers);
|
|
105
|
+
}
|
|
106
|
+
return handlers;
|
|
107
|
+
}
|
|
108
|
+
async publish({ channel, event }) {
|
|
109
|
+
const handlers = this.handlersByChannel.get(channel);
|
|
110
|
+
if (handlers) {
|
|
111
|
+
for (const handler of [...handlers])
|
|
112
|
+
handler({ event });
|
|
113
|
+
}
|
|
114
|
+
const sockets = this.socketsByChannel.get(channel);
|
|
115
|
+
if (sockets && sockets.size > 0) {
|
|
116
|
+
const payload = JSON.stringify({ type: 'event', channel, event });
|
|
117
|
+
for (const socket of [...sockets]) {
|
|
118
|
+
if (socket.readyState === WEBSOCKET_OPEN_STATE)
|
|
119
|
+
socket.send({ data: payload });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
subscribe({ channel, handler }) {
|
|
124
|
+
const handlers = this.handlersFor(channel);
|
|
125
|
+
handlers.add(handler);
|
|
126
|
+
let unsubscribed = false;
|
|
127
|
+
return () => {
|
|
128
|
+
if (unsubscribed)
|
|
129
|
+
return;
|
|
130
|
+
unsubscribed = true;
|
|
131
|
+
handlers.delete(handler);
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** The optional createServer port injects server construction; native ws is the default adapter. The real, production entry point: constructs an actual `ws.WebSocketServer` and wires a `WebSocketRealtimeProvider` to it. Callers that want to inject a fake server for tests should construct `WebSocketRealtimeProvider` directly instead. */
|
|
136
|
+
export function createWebSocketRealtimeProvider(options, optional = {}) {
|
|
137
|
+
const server = (optional.createServer ?? (({ wsOptions }) => new WebSocketServer(wsOptions)))({ wsOptions: options.wsOptions });
|
|
138
|
+
const provider = new WebSocketRealtimeProvider({
|
|
139
|
+
server: {
|
|
140
|
+
on({ listener }) {
|
|
141
|
+
server.on('connection', (socket) => listener(adaptWebSocket(socket)));
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
return { provider, server };
|
|
146
|
+
}
|
|
147
|
+
function adaptWebSocket(socket) {
|
|
148
|
+
return {
|
|
149
|
+
get readyState() { return socket.readyState; },
|
|
150
|
+
send: ({ data }) => socket.send(data),
|
|
151
|
+
on(required) {
|
|
152
|
+
if (required.event === 'message')
|
|
153
|
+
socket.on('message', required.listener);
|
|
154
|
+
else if (required.event === 'close')
|
|
155
|
+
socket.on('close', required.listener);
|
|
156
|
+
else
|
|
157
|
+
socket.on('error', required.listener);
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//# sourceMappingURL=index.js.map
|