@jini-ai/capability-providers 0.7.2 → 0.7.3-next.1
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 +1 -7
- package/dist/adapters/blob-storage/index.d.ts +1 -1
- package/dist/adapters/blob-storage/index.js +1 -1
- package/dist/unsafe-reference/auth.js +14 -10
- package/dist/unsafe-reference/index.d.ts +1 -1
- package/dist/unsafe-reference/index.js +1 -1
- package/dist/visitor-auth/lifecycle.js +22 -19
- package/package.json +5 -11
- package/dist/adapters/stripe/index.d.ts +0 -94
- package/dist/adapters/stripe/index.js +0 -167
package/CHANGELOG.md
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
# @jini-ai/capability-providers
|
|
2
2
|
|
|
3
|
-
## 0.7.2
|
|
4
|
-
|
|
5
|
-
### Patch Changes
|
|
6
|
-
|
|
7
|
-
- @jini-ai/core@0.7.2
|
|
8
|
-
|
|
9
3
|
## 0.7.1
|
|
10
4
|
|
|
11
5
|
### Patch Changes
|
|
@@ -86,7 +80,7 @@
|
|
|
86
80
|
|
|
87
81
|
### Patch Changes
|
|
88
82
|
|
|
89
|
-
-
|
|
83
|
+
- Host clean-up release (2026-10-08): code the first host moved into Jini, plus the Jini clean-up (see the commit log since 0.4.0).
|
|
90
84
|
|
|
91
85
|
## 0.4.0 — 2026-10-02
|
|
92
86
|
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* separate, non-production stub under `src/unsafe-reference/` — see that
|
|
16
16
|
* directory's `index.ts` header for the full warning.
|
|
17
17
|
*/
|
|
18
|
-
import type { BlobStorage } from '@jini-ai/
|
|
18
|
+
import type { BlobStorage } from '@jini-ai/core/contracts/blob';
|
|
19
19
|
import type { StorageObjectMeta, StorageProvider, StoragePutOptions } from '../../storage.js';
|
|
20
20
|
export interface BlobStorageProviderOptions {
|
|
21
21
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { StorageError as BlobStorageError } from '@jini-ai/
|
|
1
|
+
import { StorageError as BlobStorageError } from '@jini-ai/core/contracts/blob';
|
|
2
2
|
/**
|
|
3
3
|
* `StorageProvider` adapter that delegates to an injected `BlobStorage` instance
|
|
4
4
|
* (`@jini-ai/platform`'s real, tested port — `LocalBlobStorage` or `S3BlobStorage`). A thin
|
|
@@ -1,19 +1,11 @@
|
|
|
1
1
|
const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;
|
|
2
|
-
|
|
3
|
-
export function createInMemoryAuthProvider(_required, options = {}) {
|
|
4
|
-
const sessionTtlMs = options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;
|
|
5
|
-
const now = options.now ?? Date.now;
|
|
6
|
-
const usersByEmail = new Map();
|
|
7
|
-
const sessions = new Map();
|
|
8
|
-
let nextId = 1;
|
|
9
|
-
let nextToken = 1;
|
|
2
|
+
function createMemorySignUp(usersByEmail, now, allocateId) {
|
|
10
3
|
return {
|
|
11
4
|
async signUp(credentials) {
|
|
12
5
|
if (usersByEmail.has(credentials.email)) {
|
|
13
6
|
throw new Error(`email already registered: ${credentials.email}`);
|
|
14
7
|
}
|
|
15
|
-
const id =
|
|
16
|
-
nextId += 1;
|
|
8
|
+
const id = allocateId();
|
|
17
9
|
const user = {
|
|
18
10
|
id: `user-${id}`,
|
|
19
11
|
email: credentials.email,
|
|
@@ -23,6 +15,18 @@ export function createInMemoryAuthProvider(_required, options = {}) {
|
|
|
23
15
|
usersByEmail.set(credentials.email, user);
|
|
24
16
|
return { id: user.id, email: user.email, createdAt: user.createdAt };
|
|
25
17
|
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** Creates the in-memory reference `AuthProvider`. No persistence — state is lost on process exit. */
|
|
21
|
+
export function createInMemoryAuthProvider(_required, options = {}) {
|
|
22
|
+
const sessionTtlMs = options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;
|
|
23
|
+
const now = options.now ?? Date.now;
|
|
24
|
+
const usersByEmail = new Map();
|
|
25
|
+
const sessions = new Map();
|
|
26
|
+
let nextId = 1;
|
|
27
|
+
let nextToken = 1;
|
|
28
|
+
return {
|
|
29
|
+
...createMemorySignUp(usersByEmail, now, () => { const id = nextId; nextId += 1; return id; }),
|
|
26
30
|
async signIn(credentials) {
|
|
27
31
|
const user = usersByEmail.get(credentials.email);
|
|
28
32
|
if (!user || user.password !== credentials.password) {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
* requires opting in to this path by name, so they can't be pulled in by
|
|
38
38
|
* accident alongside the port interfaces/types and typed DI tokens (which
|
|
39
39
|
* *are* stable, safe-to-depend-on exports of the normal entry point). See
|
|
40
|
-
* `packages/capability-providers/
|
|
40
|
+
* `070311a07^:packages/capability-providers/source-map.md` and
|
|
41
41
|
* `ADS-memory/reports/security/SEC-remaining-backend-audit-2026-07-21.md`
|
|
42
42
|
* finding SEC-RB-006 for the audit that prompted this split.
|
|
43
43
|
*/
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
* requires opting in to this path by name, so they can't be pulled in by
|
|
38
38
|
* accident alongside the port interfaces/types and typed DI tokens (which
|
|
39
39
|
* *are* stable, safe-to-depend-on exports of the normal entry point). See
|
|
40
|
-
* `packages/capability-providers/
|
|
40
|
+
* `070311a07^:packages/capability-providers/source-map.md` and
|
|
41
41
|
* `ADS-memory/reports/security/SEC-remaining-backend-audit-2026-07-21.md`
|
|
42
42
|
* finding SEC-RB-006 for the audit that prompted this split.
|
|
43
43
|
*/
|
|
@@ -123,6 +123,27 @@ function configuredAuthorizationUrl(required) {
|
|
|
123
123
|
authorizationUrl.searchParams.set('nonce', required.oidcNonce);
|
|
124
124
|
return authorizationUrl.toString();
|
|
125
125
|
}
|
|
126
|
+
function createAuthorizationTransaction(required, { oidcNonce, redirectUri, tokenEndpoint, ttlMs }) {
|
|
127
|
+
return Object.freeze({
|
|
128
|
+
tenantId: required.registration.tenantId,
|
|
129
|
+
providerId: required.provider.id,
|
|
130
|
+
flowBinding: required.flowBinding,
|
|
131
|
+
protocol: required.provider.protocol,
|
|
132
|
+
state: required.security.state,
|
|
133
|
+
...(oidcNonce ? { nonce: oidcNonce } : {}),
|
|
134
|
+
codeVerifier: required.security.codeVerifier,
|
|
135
|
+
redirectUri,
|
|
136
|
+
clientId: required.registration.clientId,
|
|
137
|
+
...(required.registration.clientSecretRef
|
|
138
|
+
? { clientSecretRef: required.registration.clientSecretRef }
|
|
139
|
+
: {}),
|
|
140
|
+
tokenEndpoint: tokenEndpoint.toString(),
|
|
141
|
+
...(required.server.issuer ? { expectedIssuer: required.server.issuer } : {}),
|
|
142
|
+
requiresAuthorizationResponseIssuer: required.server.requiresAuthorizationResponseIssuer ?? false,
|
|
143
|
+
createdAtMs: required.nowMs,
|
|
144
|
+
expiresAtMs: required.nowMs + ttlMs,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
126
147
|
/**
|
|
127
148
|
* Produces a side-effect-free authorization plan. The host persists the
|
|
128
149
|
* returned transaction before redirecting and must later consume it through
|
|
@@ -153,25 +174,7 @@ export function planVisitorAuthAuthorization(required, optional = {}) {
|
|
|
153
174
|
});
|
|
154
175
|
return {
|
|
155
176
|
authorizationUrl,
|
|
156
|
-
transaction:
|
|
157
|
-
tenantId: required.registration.tenantId,
|
|
158
|
-
providerId: required.provider.id,
|
|
159
|
-
flowBinding: required.flowBinding,
|
|
160
|
-
protocol: required.provider.protocol,
|
|
161
|
-
state: required.security.state,
|
|
162
|
-
...(oidcNonce ? { nonce: oidcNonce } : {}),
|
|
163
|
-
codeVerifier: required.security.codeVerifier,
|
|
164
|
-
redirectUri,
|
|
165
|
-
clientId: required.registration.clientId,
|
|
166
|
-
...(required.registration.clientSecretRef
|
|
167
|
-
? { clientSecretRef: required.registration.clientSecretRef }
|
|
168
|
-
: {}),
|
|
169
|
-
tokenEndpoint: tokenEndpoint.toString(),
|
|
170
|
-
...(required.server.issuer ? { expectedIssuer: required.server.issuer } : {}),
|
|
171
|
-
requiresAuthorizationResponseIssuer: required.server.requiresAuthorizationResponseIssuer ?? false,
|
|
172
|
-
createdAtMs: required.nowMs,
|
|
173
|
-
expiresAtMs: required.nowMs + ttlMs,
|
|
174
|
-
}),
|
|
177
|
+
transaction: createAuthorizationTransaction(required, { oidcNonce, redirectUri, tokenEndpoint, ttlMs }),
|
|
175
178
|
};
|
|
176
179
|
}
|
|
177
180
|
function callbackContextRejection(required) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/capability-providers",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3-next.1",
|
|
4
4
|
"description": "Swappable capability-provider ports (auth, storage, payments, db, realtime) as interfaces and DI tokens only; concrete adapters live behind ./adapters/* subpaths.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -32,8 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"optionalPeers": {
|
|
34
34
|
"better-sqlite3": "opt-in: sqlite storage — SQLite storage could not load better-sqlite3. Install better-sqlite3 to enable this feature, or check its installed version and native binaries.",
|
|
35
|
-
"ws": "opt-in: websocket realtime adapter; import @jini-ai/capability-providers/adapters/ws — WebSocket realtime adapter could not load ws. Install ws to enable this feature, or check its installed version and native binaries."
|
|
36
|
-
"@jini-ai/platform": "opt-in: platform-backed adapters; import @jini-ai/capability-providers/adapters/blob-storage — Platform-backed adapters could not load @jini-ai/platform. Install @jini-ai/platform to enable this feature, or check its installed version and native binaries."
|
|
35
|
+
"ws": "opt-in: websocket realtime adapter; import @jini-ai/capability-providers/adapters/ws — WebSocket realtime adapter could not load ws. Install ws to enable this feature, or check its installed version and native binaries."
|
|
37
36
|
}
|
|
38
37
|
},
|
|
39
38
|
"type": "module",
|
|
@@ -99,12 +98,11 @@
|
|
|
99
98
|
"registry": "https://registry.npmjs.org"
|
|
100
99
|
},
|
|
101
100
|
"dependencies": {
|
|
102
|
-
"@jini-ai/core": "^0.7.
|
|
101
|
+
"@jini-ai/core": "^0.7.3-next.1"
|
|
103
102
|
},
|
|
104
103
|
"peerDependencies": {
|
|
105
104
|
"better-sqlite3": "^13.0.0",
|
|
106
|
-
"ws": "^8.18.0"
|
|
107
|
-
"@jini-ai/platform": "^0.7.0"
|
|
105
|
+
"ws": "^8.18.0"
|
|
108
106
|
},
|
|
109
107
|
"devDependencies": {
|
|
110
108
|
"@types/better-sqlite3": "^7.6.11",
|
|
@@ -112,8 +110,7 @@
|
|
|
112
110
|
"@vitest/coverage-v8": "^2.1.9",
|
|
113
111
|
"better-sqlite3": "^13.0.0",
|
|
114
112
|
"ws": "^8.18.0",
|
|
115
|
-
"@jini-ai/core": "0.7.
|
|
116
|
-
"@jini-ai/platform": "0.7.2"
|
|
113
|
+
"@jini-ai/core": "0.7.3-next.1"
|
|
117
114
|
},
|
|
118
115
|
"peerDependenciesMeta": {
|
|
119
116
|
"better-sqlite3": {
|
|
@@ -121,9 +118,6 @@
|
|
|
121
118
|
},
|
|
122
119
|
"ws": {
|
|
123
120
|
"optional": true
|
|
124
|
-
},
|
|
125
|
-
"@jini-ai/platform": {
|
|
126
|
-
"optional": true
|
|
127
121
|
}
|
|
128
122
|
},
|
|
129
123
|
"scripts": {
|
|
@@ -1,94 +0,0 @@
|
|
|
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
|
|
@@ -1,167 +0,0 @@
|
|
|
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
|