@usagekit/providers 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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/dist/budget.d.ts +15 -0
- package/dist/budget.js +50 -0
- package/dist/catalog.d.ts +59 -0
- package/dist/catalog.js +149 -0
- package/dist/dataforseo/descriptor.d.ts +10 -0
- package/dist/dataforseo/descriptor.js +106 -0
- package/dist/dataforseo/extractors.d.ts +8 -0
- package/dist/dataforseo/extractors.js +145 -0
- package/dist/dataforseo/index.d.ts +4 -0
- package/dist/dataforseo/index.js +5 -0
- package/dist/eslint.d.ts +8 -0
- package/dist/eslint.js +70 -0
- package/dist/execute.d.ts +36 -0
- package/dist/execute.js +81 -0
- package/dist/fixtures.d.ts +45 -0
- package/dist/fixtures.js +96 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +10 -0
- package/dist/match.d.ts +7 -0
- package/dist/match.js +55 -0
- package/dist/pointer.d.ts +2 -0
- package/dist/pointer.js +13 -0
- package/dist/prices.d.ts +11 -0
- package/dist/prices.js +25 -0
- package/dist/receipts.d.ts +10 -0
- package/dist/receipts.js +32 -0
- package/dist/serpapi/descriptor.d.ts +8 -0
- package/dist/serpapi/descriptor.js +97 -0
- package/dist/serpapi/extractors.d.ts +2 -0
- package/dist/serpapi/extractors.js +46 -0
- package/dist/serpapi/index.d.ts +3 -0
- package/dist/serpapi/index.js +4 -0
- package/dist/testing/conformance.d.ts +11 -0
- package/dist/testing/conformance.js +33 -0
- package/dist/testing/example.d.ts +10 -0
- package/dist/testing/example.js +146 -0
- package/dist/testing/index.d.ts +3 -0
- package/dist/testing/index.js +3 -0
- package/dist/types.d.ts +48 -0
- package/dist/types.js +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { BalanceSnapshot, Budget, ProviderPlan } from "@usagekit/core";
|
|
2
|
+
export type BudgetTarget = {
|
|
3
|
+
namespace: string;
|
|
4
|
+
connection: string;
|
|
5
|
+
probe?: BalanceSnapshot;
|
|
6
|
+
now?: Date;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The connection budget a plan implies. A plan with an allowance becomes a provider_cycle budget
|
|
10
|
+
* in the allowance unit, ending at the probe's reset date (or one month from today). A prepaid
|
|
11
|
+
* plan bounds the probed remaining balance since now. Hard plans block; soft plans allow past the
|
|
12
|
+
* allowance with a proposed hard cap at twice the allowance, because a soft limit without a cap
|
|
13
|
+
* is a known way to get an unwanted bill. The user accepts or edits the proposal.
|
|
14
|
+
*/
|
|
15
|
+
export declare function proposePlanBudget(plan: ProviderPlan, target: BudgetTarget): Budget;
|
package/dist/budget.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const day = (d) => d.toISOString().slice(0, 10);
|
|
2
|
+
const midnight = (d) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
3
|
+
const addMonths = (d, months) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + months, d.getUTCDate()));
|
|
4
|
+
/**
|
|
5
|
+
* The connection budget a plan implies. A plan with an allowance becomes a provider_cycle budget
|
|
6
|
+
* in the allowance unit, ending at the probe's reset date (or one month from today). A prepaid
|
|
7
|
+
* plan bounds the probed remaining balance since now. Hard plans block; soft plans allow past the
|
|
8
|
+
* allowance with a proposed hard cap at twice the allowance, because a soft limit without a cap
|
|
9
|
+
* is a known way to get an unwanted bill. The user accepts or edits the proposal.
|
|
10
|
+
*/
|
|
11
|
+
export function proposePlanBudget(plan, target) {
|
|
12
|
+
const now = target.now ?? new Date(), base = {
|
|
13
|
+
id: `${target.connection}:plan:${plan.id}`,
|
|
14
|
+
version: 1,
|
|
15
|
+
scope: {
|
|
16
|
+
kind: "connection",
|
|
17
|
+
namespace: target.namespace,
|
|
18
|
+
connection: target.connection,
|
|
19
|
+
},
|
|
20
|
+
surface: "any",
|
|
21
|
+
};
|
|
22
|
+
let limit = null, window;
|
|
23
|
+
if (plan.allowance) {
|
|
24
|
+
limit = { value: plan.allowance.value, scale: 0, unit: plan.allowance.unit };
|
|
25
|
+
const endsAt = target.probe?.resetsAt
|
|
26
|
+
? new Date(target.probe.resetsAt)
|
|
27
|
+
: addMonths(midnight(now), 1), startsAt = addMonths(endsAt, -1);
|
|
28
|
+
window = {
|
|
29
|
+
kind: "provider_cycle",
|
|
30
|
+
cycleId: `${plan.id}:${day(startsAt)}`,
|
|
31
|
+
startsAt: startsAt.toISOString(),
|
|
32
|
+
endsAt: endsAt.toISOString(),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
limit = target.probe?.remaining ?? null;
|
|
37
|
+
window = { kind: "since_reset", epoch: `${plan.id}:${day(now)}`, startsAt: now.toISOString() };
|
|
38
|
+
}
|
|
39
|
+
const unit = limit?.unit ?? plan.allowance?.unit ?? "units";
|
|
40
|
+
const soft = plan.allowanceMode === "soft" && limit !== null;
|
|
41
|
+
return {
|
|
42
|
+
...base,
|
|
43
|
+
unit,
|
|
44
|
+
limit,
|
|
45
|
+
window,
|
|
46
|
+
onExceed: soft ? "allow" : "block",
|
|
47
|
+
...(soft ? { hardLimit: { ...limit, value: limit.value * 2n } } : {}),
|
|
48
|
+
...(limit ? { alerts: [{ at: { percent: 80 } }] } : {}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BalanceSnapshot, Budget, EstimateSource, OperationId, ProviderDescriptor, ProviderId, ProviderOperation, ProviderPlan, Quantity } from "@usagekit/core";
|
|
2
|
+
import type { Extractors, ProviderModule, ProviderRequest, ProviderResponse, ReceiptDraft } from "./types.js";
|
|
3
|
+
import type { BudgetTarget } from "./budget.js";
|
|
4
|
+
export type { EstimateSource };
|
|
5
|
+
/** Connection data the catalog needs; the catalog itself stays storage-free. */
|
|
6
|
+
export type CatalogConnection = {
|
|
7
|
+
id: string;
|
|
8
|
+
provider: ProviderId;
|
|
9
|
+
plan?: string;
|
|
10
|
+
/** Per-call manual price for (connection, operation). */
|
|
11
|
+
manualPrices?: Readonly<Record<OperationId, Quantity>>;
|
|
12
|
+
/** Median of this connection's settled receipts for the operation, with its sample size. */
|
|
13
|
+
measured?: (operation: OperationId) => {
|
|
14
|
+
quantity: Quantity;
|
|
15
|
+
samples: number;
|
|
16
|
+
} | undefined;
|
|
17
|
+
/** The plan allowance is exhausted: only overage rows apply. */
|
|
18
|
+
overage?: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type CatalogEstimate = {
|
|
21
|
+
/** Always includes one request for a billable operation; empty for a free operation. */
|
|
22
|
+
quantities: Quantity[];
|
|
23
|
+
source: EstimateSource;
|
|
24
|
+
/** "<provider>:<validFrom>" of the list row, when the source is list. */
|
|
25
|
+
priceVersion?: string;
|
|
26
|
+
};
|
|
27
|
+
export type CatalogMatch = {
|
|
28
|
+
operation: ProviderOperation;
|
|
29
|
+
options: Record<string, string>;
|
|
30
|
+
} | {
|
|
31
|
+
operation: "unknown";
|
|
32
|
+
};
|
|
33
|
+
export type Catalog = ReturnType<typeof createCatalog>;
|
|
34
|
+
/** Balance snapshot from the JSON pointers a descriptor declares. Unreadable fields are omitted. */
|
|
35
|
+
export declare function probeByPointers(descriptor: ProviderDescriptor, body: unknown): BalanceSnapshot;
|
|
36
|
+
/**
|
|
37
|
+
* The set of operations usagekit can price. Hosts pass every descriptor they ship and enable an
|
|
38
|
+
* allowlist; disabled descriptors are not matched and their operations are unpriced.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createCatalog({ providers, enabled, measuredMinSamples, now, }: {
|
|
41
|
+
providers: readonly ProviderModule[];
|
|
42
|
+
enabled: readonly ProviderId[];
|
|
43
|
+
measuredMinSamples?: number;
|
|
44
|
+
now?: () => Date;
|
|
45
|
+
}): {
|
|
46
|
+
providers: () => ProviderDescriptor[];
|
|
47
|
+
match(providerId: ProviderId, request: ProviderRequest): CatalogMatch;
|
|
48
|
+
/** Resolution order: manual, measured with enough samples, list row, unknown. */
|
|
49
|
+
estimate(connection: CatalogConnection, operationId: OperationId, options: Readonly<Record<string, string>>): CatalogEstimate;
|
|
50
|
+
extract(providerId: ProviderId, operationId: OperationId | "unknown", request: ProviderRequest, response: ProviderResponse, body: unknown): ReceiptDraft;
|
|
51
|
+
/** Price list and billing export parsers of an enabled descriptor, when it has them. */
|
|
52
|
+
parsers(providerId: ProviderId): Pick<Extractors, "priceList" | "billingExport">;
|
|
53
|
+
requestId: (providerId: ProviderId, body: unknown) => string | undefined;
|
|
54
|
+
probe(providerId: ProviderId, body: unknown): BalanceSnapshot;
|
|
55
|
+
operationsOf: (providerId: ProviderId) => ProviderOperation[];
|
|
56
|
+
plansOf: (providerId: ProviderId) => ProviderPlan[];
|
|
57
|
+
/** Connection-scope budget proposed on connect; see proposePlanBudget. */
|
|
58
|
+
proposeBudget(providerId: ProviderId, planId: string, target: BudgetTarget): Budget;
|
|
59
|
+
};
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { validateDescriptor } from "@usagekit/core";
|
|
2
|
+
import { matchOperation } from "./match.js";
|
|
3
|
+
import { selectPriceRow } from "./prices.js";
|
|
4
|
+
import { pointer } from "./pointer.js";
|
|
5
|
+
import { decimalQuantity, requestsMeasured } from "./receipts.js";
|
|
6
|
+
import { proposePlanBudget } from "./budget.js";
|
|
7
|
+
const oneRequest = () => ({ value: 1n, scale: 0, unit: "requests" });
|
|
8
|
+
const withRequest = (q) => q.some((x) => x.unit === "requests") ? q : [...q, oneRequest()];
|
|
9
|
+
function isoTimestamp(value) {
|
|
10
|
+
if (typeof value !== "string" || !value)
|
|
11
|
+
return undefined;
|
|
12
|
+
const t = Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
|
|
13
|
+
return Number.isFinite(t) ? new Date(t).toISOString() : undefined;
|
|
14
|
+
}
|
|
15
|
+
function amount(value, unit) {
|
|
16
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
17
|
+
return decimalQuantity(String(value).includes("e") ? value.toFixed(18) : String(value), unit);
|
|
18
|
+
if (typeof value === "string" && /^\d+(\.\d+)?$/.test(value))
|
|
19
|
+
return decimalQuantity(value, unit);
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
/** Balance snapshot from the JSON pointers a descriptor declares. Unreadable fields are omitted. */
|
|
23
|
+
export function probeByPointers(descriptor, body) {
|
|
24
|
+
const f = descriptor.balance?.fields ?? {}, unit = f.remainingUnit ?? descriptor.billing.unit, read = (p) => (p === undefined ? undefined : pointer(body, p)), snapshot = {};
|
|
25
|
+
const remaining = amount(read(f.remaining), unit), allowance = amount(read(f.allowance), unit), used = amount(read(f.used), unit), resetsAt = isoTimestamp(read(f.resetsAt)), plan = read(f.plan), identity = read(f.accountIdentity), rate = read(f.rateLimitPerHour);
|
|
26
|
+
if (remaining)
|
|
27
|
+
snapshot.remaining = remaining;
|
|
28
|
+
if (allowance)
|
|
29
|
+
snapshot.allowance = allowance;
|
|
30
|
+
if (used)
|
|
31
|
+
snapshot.used = used;
|
|
32
|
+
if (resetsAt)
|
|
33
|
+
snapshot.resetsAt = resetsAt;
|
|
34
|
+
if (typeof plan === "string" && plan)
|
|
35
|
+
snapshot.plan = plan;
|
|
36
|
+
if (typeof identity === "string" && identity)
|
|
37
|
+
snapshot.accountIdentity = identity;
|
|
38
|
+
if (typeof rate === "number" && Number.isSafeInteger(rate))
|
|
39
|
+
snapshot.rateLimitPerHour = rate;
|
|
40
|
+
return snapshot;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The set of operations usagekit can price. Hosts pass every descriptor they ship and enable an
|
|
44
|
+
* allowlist; disabled descriptors are not matched and their operations are unpriced.
|
|
45
|
+
*/
|
|
46
|
+
export function createCatalog({ providers, enabled, measuredMinSamples = 5, now = () => new Date(), }) {
|
|
47
|
+
const modules = new Map();
|
|
48
|
+
for (const module of providers) {
|
|
49
|
+
const id = module.descriptor.id;
|
|
50
|
+
if (modules.has(id))
|
|
51
|
+
throw new Error(`DuplicateProvider: ${id}`);
|
|
52
|
+
const problems = validateDescriptor(module.descriptor);
|
|
53
|
+
if (problems.length)
|
|
54
|
+
throw new Error(`InvalidDescriptor: ${id}: ${problems.map((p) => p.kind).join(", ")}`);
|
|
55
|
+
modules.set(id, module);
|
|
56
|
+
}
|
|
57
|
+
for (const id of enabled)
|
|
58
|
+
if (!modules.has(id))
|
|
59
|
+
throw new Error(`UnknownProvider: ${id}`);
|
|
60
|
+
const active = (id) => (enabled.includes(id) ? modules.get(id) : undefined);
|
|
61
|
+
const require = (id) => {
|
|
62
|
+
const module = active(id);
|
|
63
|
+
if (!module)
|
|
64
|
+
throw new Error(`ProviderDisabled: ${id}`);
|
|
65
|
+
return module;
|
|
66
|
+
};
|
|
67
|
+
const validPrices = (d) => {
|
|
68
|
+
const today = now().toISOString().slice(0, 10);
|
|
69
|
+
return d.prices.filter((r) => r.validFrom.slice(0, 10) <= today);
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
providers: () => [...enabled].map((id) => modules.get(id).descriptor),
|
|
73
|
+
match(providerId, request) {
|
|
74
|
+
const module = active(providerId);
|
|
75
|
+
const operation = module && matchOperation(module.descriptor, request);
|
|
76
|
+
if (!module || !operation)
|
|
77
|
+
return { operation: "unknown" };
|
|
78
|
+
// Extractors always see an absolute URL, even for proxy paths.
|
|
79
|
+
const url = new URL(request.url, module.descriptor.upstream).href;
|
|
80
|
+
return { operation, options: module.extractors.options(operation, { ...request, url }) };
|
|
81
|
+
},
|
|
82
|
+
/** Resolution order: manual, measured with enough samples, list row, unknown. */
|
|
83
|
+
estimate(connection, operationId, options) {
|
|
84
|
+
const module = active(connection.provider), operation = module?.descriptor.operations.find((o) => o.id === operationId);
|
|
85
|
+
if (!module || !operation)
|
|
86
|
+
return { quantities: [oneRequest()], source: "unknown" };
|
|
87
|
+
if (!operation.billable)
|
|
88
|
+
return { quantities: [], source: "list" };
|
|
89
|
+
const manual = connection.manualPrices?.[operationId];
|
|
90
|
+
if (manual)
|
|
91
|
+
return { quantities: withRequest([manual]), source: "manual" };
|
|
92
|
+
const measured = connection.measured?.(operationId);
|
|
93
|
+
if (measured && measured.samples >= measuredMinSamples)
|
|
94
|
+
return { quantities: withRequest([measured.quantity]), source: "measured" };
|
|
95
|
+
const input = {
|
|
96
|
+
operation,
|
|
97
|
+
options,
|
|
98
|
+
prices: validPrices(module.descriptor),
|
|
99
|
+
...(connection.plan !== undefined ? { plan: connection.plan } : {}),
|
|
100
|
+
...(connection.overage ? { overage: true } : {}),
|
|
101
|
+
};
|
|
102
|
+
const listed = module.extractors.estimate(input);
|
|
103
|
+
if (!listed.length)
|
|
104
|
+
return { quantities: [oneRequest()], source: "unknown" };
|
|
105
|
+
const row = selectPriceRow(input);
|
|
106
|
+
return {
|
|
107
|
+
quantities: withRequest(listed),
|
|
108
|
+
source: "list",
|
|
109
|
+
...(row ? { priceVersion: `${module.descriptor.id}:${row.validFrom}` } : {}),
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
extract(providerId, operationId, request, response, body) {
|
|
113
|
+
const module = require(providerId), operation = module.descriptor.operations.find((o) => o.id === operationId);
|
|
114
|
+
if (!operation)
|
|
115
|
+
return {
|
|
116
|
+
measurements: [requestsMeasured()],
|
|
117
|
+
cost: { certainty: "unknown", money: null },
|
|
118
|
+
cached: false,
|
|
119
|
+
failed: response.status >= 400,
|
|
120
|
+
};
|
|
121
|
+
return module.extractors.extract(operation, request, response, body);
|
|
122
|
+
},
|
|
123
|
+
/** Price list and billing export parsers of an enabled descriptor, when it has them. */
|
|
124
|
+
parsers(providerId) {
|
|
125
|
+
const { priceList, billingExport } = require(providerId).extractors;
|
|
126
|
+
return { ...(priceList ? { priceList } : {}), ...(billingExport ? { billingExport } : {}) };
|
|
127
|
+
},
|
|
128
|
+
requestId: (providerId, body) => require(providerId).extractors.requestId(body),
|
|
129
|
+
probe(providerId, body) {
|
|
130
|
+
const { descriptor, extractors } = require(providerId);
|
|
131
|
+
if (!descriptor.balance)
|
|
132
|
+
throw new Error(`NoBalanceProbe: ${providerId}`);
|
|
133
|
+
return extractors.balance ? extractors.balance(body) : probeByPointers(descriptor, body);
|
|
134
|
+
},
|
|
135
|
+
operationsOf: (providerId) => [
|
|
136
|
+
...(active(providerId)?.descriptor.operations ?? []),
|
|
137
|
+
],
|
|
138
|
+
plansOf: (providerId) => [
|
|
139
|
+
...(active(providerId)?.descriptor.plans ?? []),
|
|
140
|
+
],
|
|
141
|
+
/** Connection-scope budget proposed on connect; see proposePlanBudget. */
|
|
142
|
+
proposeBudget(providerId, planId, target) {
|
|
143
|
+
const plan = require(providerId).descriptor.plans.find((p) => p.id === planId);
|
|
144
|
+
if (!plan)
|
|
145
|
+
throw new Error(`UnknownPlan: ${planId}`);
|
|
146
|
+
return proposePlanBudget(plan, target);
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ProviderDescriptor } from "@usagekit/core";
|
|
2
|
+
export declare const serpPricing = "https://dataforseo.com/pricing/serp/google-organic-serp-api";
|
|
3
|
+
export declare const labsPricing = "https://dataforseo.com/pricing/dataforseo-labs/dataforseo-google-api";
|
|
4
|
+
export declare const backlinksPricing = "https://dataforseo.com/pricing/backlinks/backlinks";
|
|
5
|
+
/**
|
|
6
|
+
* Provider A: cost per call in every response, prepaid money balance, basic auth. List prices
|
|
7
|
+
* are the per-task base price in cents; per-result charges, depth multipliers and paid
|
|
8
|
+
* parameters come from the receipt.
|
|
9
|
+
*/
|
|
10
|
+
export declare const descriptor: ProviderDescriptor;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const docs = "https://docs.dataforseo.com/v3/";
|
|
2
|
+
export const serpPricing = "https://dataforseo.com/pricing/serp/google-organic-serp-api";
|
|
3
|
+
export const labsPricing = "https://dataforseo.com/pricing/dataforseo-labs/dataforseo-google-api";
|
|
4
|
+
export const backlinksPricing = "https://dataforseo.com/pricing/backlinks/backlinks";
|
|
5
|
+
const checked = "2026-09-25";
|
|
6
|
+
const live = (id, label, path) => ({
|
|
7
|
+
id,
|
|
8
|
+
label,
|
|
9
|
+
billable: true,
|
|
10
|
+
match: [{ method: "POST", path }],
|
|
11
|
+
costEvidence: "response",
|
|
12
|
+
});
|
|
13
|
+
const free = (id, label, method, path) => ({
|
|
14
|
+
id,
|
|
15
|
+
label,
|
|
16
|
+
billable: false,
|
|
17
|
+
match: [{ method, path }],
|
|
18
|
+
costEvidence: "response",
|
|
19
|
+
});
|
|
20
|
+
const labs = [
|
|
21
|
+
["keyword_ideas", "Keyword ideas"],
|
|
22
|
+
["keyword_suggestions", "Keyword suggestions"],
|
|
23
|
+
["related_keywords", "Related keywords"],
|
|
24
|
+
["keyword_overview", "Keyword overview"],
|
|
25
|
+
["ranked_keywords", "Ranked keywords"],
|
|
26
|
+
["domain_rank_overview", "Domain rank overview"],
|
|
27
|
+
["historical_rank_overview", "Historical rank overview"],
|
|
28
|
+
["relevant_pages", "Relevant pages"],
|
|
29
|
+
];
|
|
30
|
+
const backlinks = [
|
|
31
|
+
["summary", "Backlinks summary"],
|
|
32
|
+
["history", "Backlinks history"],
|
|
33
|
+
["backlinks", "Backlinks live"],
|
|
34
|
+
];
|
|
35
|
+
const row = (operation, perUnit, source, option) => ({
|
|
36
|
+
validFrom: checked,
|
|
37
|
+
operation,
|
|
38
|
+
...(option ? { option } : {}),
|
|
39
|
+
unit: "cents",
|
|
40
|
+
perUnit,
|
|
41
|
+
source,
|
|
42
|
+
checkedAt: checked,
|
|
43
|
+
});
|
|
44
|
+
/**
|
|
45
|
+
* Provider A: cost per call in every response, prepaid money balance, basic auth. List prices
|
|
46
|
+
* are the per-task base price in cents; per-result charges, depth multipliers and paid
|
|
47
|
+
* parameters come from the receipt.
|
|
48
|
+
*/
|
|
49
|
+
export const descriptor = {
|
|
50
|
+
id: "dataforseo",
|
|
51
|
+
label: "DataForSEO",
|
|
52
|
+
upstream: "https://api.dataforseo.com",
|
|
53
|
+
auth: { kind: "basic" },
|
|
54
|
+
stripRequestHeaders: ["authorization"],
|
|
55
|
+
billing: { unit: "cents", cycle: "prepaid" },
|
|
56
|
+
plans: [{ id: "prepaid", label: "Prepaid balance", cycle: "prepaid", allowanceMode: "hard" }],
|
|
57
|
+
prices: [
|
|
58
|
+
row("serp.google.organic.live.advanced", "0.2", serpPricing),
|
|
59
|
+
row("serp.google.organic.task_post", "0.06", serpPricing, { priority: "normal" }),
|
|
60
|
+
row("serp.google.organic.task_post", "0.12", serpPricing, { priority: "high" }),
|
|
61
|
+
...labs.map(([name]) => row(`dataforseo_labs.google.${name}.live`, name === "historical_rank_overview" ? "12" : "1.2", labsPricing)),
|
|
62
|
+
...backlinks.map(([name]) => row(`backlinks.${name}.live`, "2.4", backlinksPricing)),
|
|
63
|
+
],
|
|
64
|
+
priceList: {
|
|
65
|
+
kind: "endpoint",
|
|
66
|
+
operation: "appendix.user_data",
|
|
67
|
+
pointer: "/tasks/0/result/0/price",
|
|
68
|
+
mapping: "provider-specific",
|
|
69
|
+
},
|
|
70
|
+
operations: [
|
|
71
|
+
live("serp.google.organic.live.advanced", "Google organic SERP, live advanced", "/v3/serp/google/organic/live/advanced"),
|
|
72
|
+
{
|
|
73
|
+
id: "serp.google.organic.task_post",
|
|
74
|
+
label: "Google organic SERP, task post",
|
|
75
|
+
billable: true,
|
|
76
|
+
match: [{ method: "POST", path: "/v3/serp/google/organic/task_post" }],
|
|
77
|
+
optionKeys: ["priority"],
|
|
78
|
+
costEvidence: "deferred",
|
|
79
|
+
},
|
|
80
|
+
free("serp.google.organic.tasks_ready", "Google organic SERP, tasks ready", "GET", "/v3/serp/google/organic/tasks_ready"),
|
|
81
|
+
free("serp.google.organic.task_get.advanced", "Google organic SERP, task get advanced", "GET", "/v3/serp/google/organic/task_get/advanced/:id"),
|
|
82
|
+
...labs.map(([name, label]) => live(`dataforseo_labs.google.${name}.live`, label, `/v3/dataforseo_labs/google/${name}/live`)),
|
|
83
|
+
...backlinks.map(([name, label]) => live(`backlinks.${name}.live`, label, `/v3/backlinks/${name}/live`)),
|
|
84
|
+
free("appendix.user_data", "User data (balance, limits, prices)", "GET", "/v3/appendix/user_data"),
|
|
85
|
+
free("dataforseo_labs.status", "Labs status", "GET", "/v3/dataforseo_labs/status"),
|
|
86
|
+
],
|
|
87
|
+
balance: {
|
|
88
|
+
operation: "appendix.user_data",
|
|
89
|
+
// money.balance is USD; the balance extractor converts it to cents. rates.limits.minute.total
|
|
90
|
+
// is per minute; the extractor reports it per hour.
|
|
91
|
+
fields: {
|
|
92
|
+
remaining: "/tasks/0/result/0/money/balance",
|
|
93
|
+
remainingUnit: "cents",
|
|
94
|
+
accountIdentity: "/tasks/0/result/0/login",
|
|
95
|
+
rateLimitPerHour: "/tasks/0/result/0/rates/limits/minute/total",
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
billingExport: {
|
|
99
|
+
kind: "task-history",
|
|
100
|
+
operation: "serp.google.organic.task_get.advanced",
|
|
101
|
+
granularity: "per-request",
|
|
102
|
+
matchKey: "providerRequestId",
|
|
103
|
+
},
|
|
104
|
+
rateLimits: [{ scope: "account", perMinute: 2000 }],
|
|
105
|
+
docs: { pricing: serpPricing, api: docs },
|
|
106
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Extractors } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Price object keys `api.func_type.func_name` to operation ids. The key layout follows the
|
|
4
|
+
* documented field schema; a recorded user_data fixture confirms it. Unmapped keys, per-result
|
|
5
|
+
* entries and free functions are skipped.
|
|
6
|
+
*/
|
|
7
|
+
export declare const priceKeys: Readonly<Record<string, string>>;
|
|
8
|
+
export declare const extractors: Extractors;
|