@base44-preview/sdk 0.8.46-pr.276.f98c3b7 → 0.8.46-pr.277.5cc15f3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/client.js +3 -0
  2. package/dist/client.types.d.ts +38 -0
  3. package/dist/index.d.ts +0 -11
  4. package/dist/utils/fetch-with-auth.d.ts +12 -0
  5. package/dist/utils/fetch-with-auth.js +49 -0
  6. package/package.json +1 -31
  7. package/dist/iap/account-token.d.ts +0 -14
  8. package/dist/iap/account-token.js +0 -43
  9. package/dist/iap/config.d.ts +0 -19
  10. package/dist/iap/config.js +0 -105
  11. package/dist/iap/errors.d.ts +0 -89
  12. package/dist/iap/errors.js +0 -66
  13. package/dist/iap/errors.types.d.ts +0 -74
  14. package/dist/iap/errors.types.js +0 -7
  15. package/dist/iap/events/emitter.d.ts +0 -28
  16. package/dist/iap/events/emitter.js +0 -33
  17. package/dist/iap/events/events.types.d.ts +0 -124
  18. package/dist/iap/events/events.types.js +0 -1
  19. package/dist/iap/iap.types.d.ts +0 -632
  20. package/dist/iap/iap.types.js +0 -1
  21. package/dist/iap/index.d.ts +0 -120
  22. package/dist/iap/index.js +0 -145
  23. package/dist/iap/ingest/device.d.ts +0 -7
  24. package/dist/iap/ingest/device.js +0 -191
  25. package/dist/iap/ingest/device.types.d.ts +0 -80
  26. package/dist/iap/ingest/device.types.js +0 -1
  27. package/dist/iap/ingest/mappers.d.ts +0 -66
  28. package/dist/iap/ingest/mappers.js +0 -248
  29. package/dist/iap/ingest/matrix.d.ts +0 -55
  30. package/dist/iap/ingest/matrix.js +0 -202
  31. package/dist/iap/ingest/notifications.d.ts +0 -70
  32. package/dist/iap/ingest/notifications.js +0 -231
  33. package/dist/iap/read/derive.d.ts +0 -40
  34. package/dist/iap/read/derive.js +0 -112
  35. package/dist/iap/read/read.d.ts +0 -47
  36. package/dist/iap/read/read.js +0 -215
  37. package/dist/iap/read/read.types.d.ts +0 -174
  38. package/dist/iap/read/read.types.js +0 -1
  39. package/dist/iap/runtime/base64.d.ts +0 -34
  40. package/dist/iap/runtime/base64.js +0 -131
  41. package/dist/iap/runtime/clock.d.ts +0 -13
  42. package/dist/iap/runtime/clock.js +0 -11
  43. package/dist/iap/runtime/webcrypto.d.ts +0 -14
  44. package/dist/iap/runtime/webcrypto.js +0 -66
  45. package/dist/iap/server-api/client.d.ts +0 -16
  46. package/dist/iap/server-api/client.js +0 -140
  47. package/dist/iap/server-api/jwt.d.ts +0 -3
  48. package/dist/iap/server-api/jwt.js +0 -70
  49. package/dist/iap/server-api/server-api.types.d.ts +0 -155
  50. package/dist/iap/server-api/server-api.types.js +0 -12
  51. package/dist/iap/store/collapse.d.ts +0 -27
  52. package/dist/iap/store/collapse.js +0 -85
  53. package/dist/iap/store/descriptors.d.ts +0 -46
  54. package/dist/iap/store/descriptors.js +0 -90
  55. package/dist/iap/store/entities-store.d.ts +0 -43
  56. package/dist/iap/store/entities-store.js +0 -348
  57. package/dist/iap/store/rows.types.d.ts +0 -233
  58. package/dist/iap/store/rows.types.js +0 -1
  59. package/dist/iap/store/schemas.d.ts +0 -68
  60. package/dist/iap/store/schemas.js +0 -214
  61. package/dist/iap/store/store-errors.d.ts +0 -52
  62. package/dist/iap/store/store-errors.js +0 -103
  63. package/dist/iap/store/store.types.d.ts +0 -193
  64. package/dist/iap/store/store.types.js +0 -1
  65. package/dist/iap/verify/apple-roots.d.ts +0 -18
  66. package/dist/iap/verify/apple-roots.js +0 -121
  67. package/dist/iap/verify/apple-verifier.d.ts +0 -13
  68. package/dist/iap/verify/apple-verifier.js +0 -154
  69. package/dist/iap/verify/asn1.d.ts +0 -102
  70. package/dist/iap/verify/asn1.js +0 -247
  71. package/dist/iap/verify/chain.d.ts +0 -40
  72. package/dist/iap/verify/chain.js +0 -112
  73. package/dist/iap/verify/ecdsa.d.ts +0 -16
  74. package/dist/iap/verify/ecdsa.js +0 -86
  75. package/dist/iap/verify/jws.d.ts +0 -50
  76. package/dist/iap/verify/jws.js +0 -159
  77. package/dist/iap/verify/payload-checks.d.ts +0 -36
  78. package/dist/iap/verify/payload-checks.js +0 -76
  79. package/dist/iap/verify/verifier.d.ts +0 -30
  80. package/dist/iap/verify/verifier.js +0 -114
  81. package/dist/iap/verify/verify.types.d.ts +0 -292
  82. package/dist/iap/verify/verify.types.js +0 -15
  83. package/dist/iap/verify/x509.d.ts +0 -83
  84. package/dist/iap/verify/x509.js +0 -156
  85. package/dist/iap/version.d.ts +0 -13
  86. package/dist/iap/version.js +0 -13
package/dist/client.js CHANGED
@@ -5,6 +5,7 @@ import { createAuthModule } from "./modules/auth.js";
5
5
  import { createSsoModule } from "./modules/sso.js";
6
6
  import { createConnectorsModule, createUserConnectorsModule, } from "./modules/connectors.js";
7
7
  import { getAccessToken } from "./utils/auth-utils.js";
8
+ import { createFetchWithAuth } from "./utils/fetch-with-auth.js";
8
9
  import { createFunctionsModule } from "./modules/functions.js";
9
10
  import { createAgentsModule } from "./modules/agents.js";
10
11
  import { createAiGatewayModule } from "./modules/ai-gateway.js";
@@ -260,6 +261,8 @@ export function createClient(config) {
260
261
  // Assemble and return the client
261
262
  const client = {
262
263
  ...userModules,
264
+ /** See {@link Base44Client.fetchWithAuth}. */
265
+ fetchWithAuth: createFetchWithAuth(axiosClient),
263
266
  /**
264
267
  * Sets a new authentication token for all subsequent requests.
265
268
  *
@@ -139,6 +139,44 @@ export interface Base44Client {
139
139
  integrations: IntegrationsModule;
140
140
  /** Cleanup function to disconnect WebSocket connections. Call when you're done with the client. */
141
141
  cleanup: () => void;
142
+ /**
143
+ * Calls one of your app's own server routes with the signed-in user's access token attached.
144
+ *
145
+ * Base44 keeps the user's access token in the browser's local storage, so a plain `fetch()` to your app's server routes arrives without it and the route sees an anonymous caller. `fetchWithAuth()` is the same `fetch()` with the `Authorization: Bearer <token>` header added, which is what lets a server route act on behalf of the signed-in user.
146
+ *
147
+ * Requests are restricted to your app's own origin so the token is never sent to a third party: pass a relative path beginning with a single `/`, such as `/api/orders`. An absolute URL, a protocol-relative `//host`, or anything else that a URL parser would read as another origin throws. To call a Base44 backend function, use {@linkcode FunctionsModule.fetch | functions.fetch()}; for another origin, use plain `fetch()`.
148
+ *
149
+ * The path is passed to `fetch` unchanged, so this also works in server code, where the runtime's `fetch` decides what a relative path means — a server-side client from {@linkcode createClientFromRequest | createClientFromRequest()} carries the caller's own token. Note that only the `Authorization` header is added: a route that builds its own client from the incoming request also needs the platform's `Base44-App-Id` and `Base44-Api-Url`, which a request you construct yourself does not have.
150
+ *
151
+ * When no user is signed in the request is sent without an `Authorization` header, so routes that allow anonymous access keep working.
152
+ *
153
+ * @param path - A relative path on your app's own origin, such as `/api/orders`.
154
+ * @param init - Optional [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) options such as `method`, `headers`, `body`, and `signal`. The auth header is added automatically; an `Authorization` header you set yourself is kept.
155
+ * @returns Promise resolving to a native [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
156
+ * @throws {Error} When `path` is not a relative path on your app's own origin.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // Call your app's own server route as the signed-in user
161
+ * const response = await base44.fetchWithAuth('/api/orders');
162
+ * const orders = await response.json();
163
+ * ```
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * // POST with a JSON body
168
+ * const response = await base44.fetchWithAuth('/api/orders', {
169
+ * method: 'POST',
170
+ * headers: { 'Content-Type': 'application/json' },
171
+ * body: JSON.stringify({ productId: 'abc', quantity: 2 }),
172
+ * });
173
+ *
174
+ * if (!response.ok) {
175
+ * throw new Error(`Request failed: ${response.status}`);
176
+ * }
177
+ * ```
178
+ */
179
+ fetchWithAuth(path: string, init?: RequestInit): Promise<Response>;
142
180
  /**
143
181
  * Sets a new authentication token for all subsequent requests.
144
182
  *
package/dist/index.d.ts CHANGED
@@ -18,14 +18,3 @@ export { Actor, type Conn } from "./actor.js";
18
18
  export type { ConnectorsModule, UserConnectorsModule, ConnectorApiRequest, ConnectorApiResponse, ConnectorApiResponsePhase, } from "./modules/connectors.types.js";
19
19
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
20
20
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
21
- export type { CreateIapClientOptions, IapInternalOptions, } from "./iap/index.js";
22
- export type { IapConfig, IapConfiguredProductType, IapModule, IapProductConfig, IapSetupReport, } from "./iap/iap.types.js";
23
- export type { IapEvent, IapEventHandler, IapEventType, IapExpiryReason, IapRenewReason, IapStartReason, } from "./iap/events/events.types.js";
24
- export type { EntitlementQuery, Entitlements, IapExpirationReason, IapRevocation, IapSubscriptionOffer, IapSubscriptionStatus, OwnedNonConsumable, OwnedNonRenewingSubscription, SubscriptionQuery, SubscriptionState, TransactionQuery, } from "./iap/read/read.types.js";
25
- export type { HandleNotificationResult } from "./iap/ingest/notifications.js";
26
- export type { RecordTransactionOptions, RecordTransactionResult, SyncPayload, SyncResult, } from "./iap/ingest/device.types.js";
27
- export type { IapConsumptionOutcome, IapConsumptionRequestRecord, IapNotificationOutcome, IapNotificationRecord, IapRecordSource, IapSubscriptionRecord, IapTransactionRecord, } from "./iap/store/rows.types.js";
28
- export type { IapEntityName, IapEntitySchema, IapSchemaField, } from "./iap/store/schemas.js";
29
- export type { ConsumptionRequestBody, IapDeliveryStatus, IapRefundPreference, IapServerApiConfig, IapServerApiModule, SendAttempt, SendAttemptResult, TestNotificationResult, TestNotificationStatus, } from "./iap/server-api/server-api.types.js";
30
- export type { IapApiErrorCode, IapConfigErrorCode, IapSetupErrorCode, IapStoreErrorCode, IapVerificationErrorCode, } from "./iap/errors.types.js";
31
- export type { DecodedNotification, DecodedNotificationData, DecodedNotificationSummary, DecodedRenewalInfo, DecodedTransaction, IapAppleSubscriptionStatus, IapConsumptionRequestReason, IapEnvironment, IapExpirationIntent, IapOfferDiscountType, IapOfferType, IapOwnershipType, IapProductType, IapRevocationType, IapTransactionReason, } from "./iap/verify/verify.types.js";
@@ -0,0 +1,12 @@
1
+ import type { AxiosInstance } from "axios";
2
+ /**
3
+ * Builds the client's `fetchWithAuth`: a `fetch` that attaches the signed-in
4
+ * user's access token to a request for the app's own origin.
5
+ *
6
+ * @param axios - The user-scoped axios instance. Its `Authorization` default is
7
+ * the live token: it follows `setToken()` and is deleted on `logout()`, so a
8
+ * request never carries a token the user no longer has. In a server-side client
9
+ * from `createClientFromRequest()` it holds the caller's own token.
10
+ * @internal
11
+ */
12
+ export declare function createFetchWithAuth(axios: AxiosInstance): (path: string, init?: RequestInit) => Promise<Response>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Builds the client's `fetchWithAuth`: a `fetch` that attaches the signed-in
3
+ * user's access token to a request for the app's own origin.
4
+ *
5
+ * @param axios - The user-scoped axios instance. Its `Authorization` default is
6
+ * the live token: it follows `setToken()` and is deleted on `logout()`, so a
7
+ * request never carries a token the user no longer has. In a server-side client
8
+ * from `createClientFromRequest()` it holds the caller's own token.
9
+ * @internal
10
+ */
11
+ export function createFetchWithAuth(axios) {
12
+ const currentToken = () => {
13
+ const header = axios.defaults.headers.common["Authorization"];
14
+ if (typeof header !== "string" || !header.startsWith("Bearer ")) {
15
+ return null;
16
+ }
17
+ return header.slice("Bearer ".length) || null;
18
+ };
19
+ return async function fetchWithAuth(path, init = {}) {
20
+ assertOwnOriginPath(path);
21
+ const headers = new Headers(init.headers);
22
+ const token = currentToken();
23
+ if (token && !headers.has("Authorization")) {
24
+ headers.set("Authorization", `Bearer ${token}`);
25
+ }
26
+ // Passed through untouched: resolving it here would need a document, and a
27
+ // root-relative path is already what a runtime that dispatches in-process
28
+ // (Nitro's `fetch`) expects.
29
+ return fetch(path, { ...init, headers });
30
+ };
31
+ }
32
+ function assertOwnOriginPath(path) {
33
+ if (typeof path !== "string" || path === "") {
34
+ throw new Error("fetchWithAuth() requires a path, such as '/api/orders'.");
35
+ }
36
+ // Check what a URL parser would see, not the raw string: it drops every ASCII
37
+ // tab/newline anywhere in the input and trims leading C0/space, so
38
+ // "/<tab>/evil.example" would pass a naive prefix check and then resolve to
39
+ // another host.
40
+ const asParsed = path.replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+/, "");
41
+ // One leading slash is the whole rule: it cannot carry a scheme, and it rules
42
+ // out the two forms that reach another origin — "//host" and, since URL
43
+ // parsing treats a backslash as a slash, "/\host".
44
+ if (!asParsed.startsWith("/") ||
45
+ asParsed.startsWith("//") ||
46
+ asParsed.startsWith("/\\")) {
47
+ throw new Error(`fetchWithAuth() only sends requests to your app's own origin, so the access token never reaches a third party. "${path}" is not a path on it — pass a relative path such as '/api/orders'. Use base44.functions.fetch() to call a Base44 backend function, or plain fetch() for another origin.`);
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,36 +1,9 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.46-pr.276.f98c3b7",
3
+ "version": "0.8.46-pr.277.5cc15f3",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "default": "./dist/index.js"
11
- },
12
- "./iap": {
13
- "types": "./dist/iap/index.d.ts",
14
- "default": "./dist/iap/index.js"
15
- },
16
- "./dist/*.js": {
17
- "types": "./dist/*.d.ts",
18
- "default": "./dist/*.js"
19
- },
20
- "./dist/*.d.ts": "./dist/*.d.ts",
21
- "./dist/*": {
22
- "types": "./dist/*.d.ts",
23
- "default": "./dist/*.js"
24
- },
25
- "./package.json": "./package.json"
26
- },
27
- "typesVersions": {
28
- "*": {
29
- "iap": [
30
- "dist/iap/index.d.ts"
31
- ]
32
- }
33
- },
34
7
  "type": "module",
35
8
  "files": [
36
9
  "dist"
@@ -53,14 +26,12 @@
53
26
  "create-docs:process": "node scripts/mintlify-post-processing/file-processing/file-processing.js"
54
27
  },
55
28
  "dependencies": {
56
- "@apple/app-store-server-library": "^3.1.0",
57
29
  "axios": "^1.18.1",
58
30
  "partysocket": "^0.0.23",
59
31
  "socket.io-client": "^4.8.3",
60
32
  "uuid": "^13.0.2"
61
33
  },
62
34
  "devDependencies": {
63
- "@peculiar/x509": "^2.0.0",
64
35
  "@types/hast": "^3.0.4",
65
36
  "@types/node": "^25.0.1",
66
37
  "@types/unist": "^3.0.3",
@@ -72,7 +43,6 @@
72
43
  "eslint": "^9.39.2",
73
44
  "eslint-plugin-import": "^2.32.0",
74
45
  "nock": "^13.4.0",
75
- "reflect-metadata": "^0.2.2",
76
46
  "typedoc": "^0.28.14",
77
47
  "typedoc-plugin-markdown": "^4.9.0",
78
48
  "typescript": "^5.3.2",
@@ -1,14 +0,0 @@
1
- /**
2
- * The namespace every Base44 in-app purchase account token is derived under.
3
- *
4
- * A fixed, arbitrary version-4 UUID. It must never change: the native shell
5
- * derives the same value independently, and Apple has already signed the
6
- * results into transactions that will keep renewing.
7
- */
8
- export declare const IAP_APP_ACCOUNT_TOKEN_NAMESPACE = "8f2b6a1e-4c5d-4e7a-9b3f-6d1a2c8e5f04";
9
- /**
10
- * Derives the account token for a Base44 user id.
11
- *
12
- * @throws {TypeError} when the user id is empty.
13
- */
14
- export declare function appAccountTokenFor(base44UserId: string): string;
@@ -1,43 +0,0 @@
1
- /**
2
- * Mapping a Base44 user to the UUID Apple signs into their purchases.
3
- *
4
- * StoreKit accepts a UUID at purchase time (`appAccountToken`) and Apple
5
- * returns the same value in every resulting transaction — including renewals
6
- * years later. That signed round trip is the entire attribution mechanism: it
7
- * is the only way to know whose purchase a transaction is, without trusting
8
- * anything the client claims.
9
- *
10
- * The mapping is a deterministic version-5 UUID of the user id under a fixed
11
- * namespace, so it is a pure function. The shell, the web app and the backend
12
- * all derive the same UUID from the same user id with no lookup table to keep
13
- * in sync, and nothing to migrate.
14
- *
15
- * Two consequences worth knowing:
16
- *
17
- * - The namespace is part of the contract. Changing it orphans every purchase
18
- * already attributed under the old one.
19
- * - The mapping is one-way in practice. Recovering a user id means deriving
20
- * the UUID for a candidate user and comparing, not inverting the hash.
21
- *
22
- * @internal
23
- */
24
- import { v5 as uuidv5 } from "uuid";
25
- /**
26
- * The namespace every Base44 in-app purchase account token is derived under.
27
- *
28
- * A fixed, arbitrary version-4 UUID. It must never change: the native shell
29
- * derives the same value independently, and Apple has already signed the
30
- * results into transactions that will keep renewing.
31
- */
32
- export const IAP_APP_ACCOUNT_TOKEN_NAMESPACE = "8f2b6a1e-4c5d-4e7a-9b3f-6d1a2c8e5f04";
33
- /**
34
- * Derives the account token for a Base44 user id.
35
- *
36
- * @throws {TypeError} when the user id is empty.
37
- */
38
- export function appAccountTokenFor(base44UserId) {
39
- if (typeof base44UserId !== "string" || base44UserId.length === 0) {
40
- throw new TypeError("a Base44 user id is required to derive an account token");
41
- }
42
- return uuidv5(base44UserId, IAP_APP_ACCOUNT_TOKEN_NAMESPACE);
43
- }
@@ -1,19 +0,0 @@
1
- import type { IapConfig, IapProductConfig } from "./iap.types.js";
2
- import type { IapServerApiConfig } from "./server-api/server-api.types.js";
3
- /** A validated configuration, with every default filled in. */
4
- export interface ResolvedIapConfig {
5
- readonly bundleId: string;
6
- readonly appAppleId: number;
7
- readonly products: Readonly<Record<string, IapProductConfig>>;
8
- readonly testMode: boolean;
9
- readonly allowLocalTesting: boolean;
10
- readonly serverApi?: IapServerApiConfig;
11
- readonly verifier: "apple" | "builtin";
12
- }
13
- /**
14
- * Validates a configuration and fills in defaults.
15
- *
16
- * @throws {IapConfigError} `IAP_INVALID_CONFIG` for anything malformed, or
17
- * `IAP_ONLINE_CHECKS_UNSUPPORTED` when online certificate checks are asked for.
18
- */
19
- export declare function resolveConfig(config: IapConfig): ResolvedIapConfig;
@@ -1,105 +0,0 @@
1
- /**
2
- * Configuration validation.
3
- *
4
- * Runs once, when the client is created, and refuses to build a client it
5
- * cannot operate correctly. Failing at deploy time is the whole point: the
6
- * alternative is discovering a missing `appAppleId` when Apple sends the first
7
- * refund notification.
8
- *
9
- * @internal
10
- */
11
- import { IapConfigError } from "./errors.js";
12
- const PRODUCT_TYPES = new Set([
13
- "consumable",
14
- "nonConsumable",
15
- "nonRenewingSubscription",
16
- "autoRenewableSubscription",
17
- ]);
18
- function invalid(message) {
19
- throw new IapConfigError("IAP_INVALID_CONFIG", message);
20
- }
21
- /**
22
- * Validates a configuration and fills in defaults.
23
- *
24
- * @throws {IapConfigError} `IAP_INVALID_CONFIG` for anything malformed, or
25
- * `IAP_ONLINE_CHECKS_UNSUPPORTED` when online certificate checks are asked for.
26
- */
27
- export function resolveConfig(config) {
28
- var _a, _b;
29
- if (!config || typeof config !== "object") {
30
- invalid("an in-app purchase configuration object is required");
31
- }
32
- if (typeof config.bundleId !== "string" || config.bundleId.trim().length === 0) {
33
- invalid("'bundleId' is required, e.g. \"com.example.app\"");
34
- }
35
- // A very common mix-up: passing the bundle id where the numeric id belongs.
36
- if (typeof config.appAppleId === "string") {
37
- invalid("'appAppleId' must be a number — the numeric App Store id from App Store " +
38
- "Connect under App Information, not the bundle id");
39
- }
40
- if (typeof config.appAppleId !== "number" ||
41
- !Number.isInteger(config.appAppleId) ||
42
- config.appAppleId <= 0) {
43
- invalid("'appAppleId' must be a positive integer, e.g. 1234567890");
44
- }
45
- if (!config.products || typeof config.products !== "object") {
46
- invalid("'products' is required, keyed by product identifier");
47
- }
48
- for (const [productId, product] of Object.entries(config.products)) {
49
- if (!product || typeof product !== "object") {
50
- invalid(`product ${JSON.stringify(productId)} must be an object`);
51
- }
52
- if (!PRODUCT_TYPES.has(product.type)) {
53
- invalid(`product ${JSON.stringify(productId)} has type ${JSON.stringify(product.type)}; expected one of ${[...PRODUCT_TYPES].join(", ")}`);
54
- }
55
- // Apple never expires a non-renewing subscription, so this number is the
56
- // only thing that decides when access ends. Missing it would silently
57
- // grant the product forever.
58
- if (product.type === "nonRenewingSubscription") {
59
- const days = product.nonRenewingDurationDays;
60
- if (typeof days !== "number" || !Number.isFinite(days) || days <= 0) {
61
- invalid(`product ${JSON.stringify(productId)} is a nonRenewingSubscription, so it ` +
62
- "needs 'nonRenewingDurationDays' — Apple does not expire these, so the " +
63
- "app decides how long they last");
64
- }
65
- }
66
- }
67
- // `null` is treated as absent, not as invalid: a secret that was never set
68
- // arrives that way, and the right answer then is "the API is not configured"
69
- // — which the call itself reports clearly — rather than refusing to start.
70
- if (config.verifier !== undefined &&
71
- config.verifier !== "apple" &&
72
- config.verifier !== "builtin") {
73
- invalid(`'verifier' must be "apple" or "builtin"; got ${JSON.stringify(config.verifier)}`);
74
- }
75
- if (config.serverApi !== undefined && config.serverApi !== null) {
76
- const api = config.serverApi;
77
- if (typeof api !== "object") {
78
- invalid("'serverApi' must be an object, or left out entirely");
79
- }
80
- for (const field of ["keyId", "issuerId", "privateKeyP8"]) {
81
- if (typeof api[field] !== "string" || api[field].trim().length === 0) {
82
- invalid(`'serverApi.${field}' is required when serverApi is supplied`);
83
- }
84
- }
85
- if (!api.privateKeyP8.includes("PRIVATE KEY")) {
86
- invalid("'serverApi.privateKeyP8' does not look like a .p8 file. Pass its whole " +
87
- "contents, including the BEGIN and END lines.");
88
- }
89
- }
90
- if (config.onlineChecks === true) {
91
- throw new IapConfigError("IAP_ONLINE_CHECKS_UNSUPPORTED", "'onlineChecks' asks for certificate revocation lookups, which this version " +
92
- "does not implement. Leave it unset. Certificate validity is evaluated at " +
93
- "each payload's own signedDate, which is what Apple's own library does with " +
94
- "online checks off.");
95
- }
96
- return {
97
- bundleId: config.bundleId,
98
- appAppleId: config.appAppleId,
99
- products: { ...config.products },
100
- testMode: config.testMode === true,
101
- allowLocalTesting: config.allowLocalTesting === true,
102
- serverApi: (_a = config.serverApi) !== null && _a !== void 0 ? _a : undefined,
103
- verifier: (_b = config.verifier) !== null && _b !== void 0 ? _b : "apple",
104
- };
105
- }
@@ -1,89 +0,0 @@
1
- /**
2
- * Error classes for the in-app purchase module.
3
- *
4
- * Each class carries a `code` from `errors.types.ts`. Nothing here imports the
5
- * runtime helpers, so the runtime layer can throw these freely.
6
- *
7
- * @internal
8
- */
9
- import type { IapApiErrorCode, IapConfigErrorCode, IapSetupErrorCode, IapStoreErrorCode, IapVerificationErrorCode } from "./errors.types.js";
10
- /** Base class, so a caller can catch every error this module raises at once. */
11
- export declare class IapError extends Error {
12
- /** Stable machine-readable code. */
13
- readonly code: string;
14
- constructor(code: string, message: string, options?: {
15
- cause?: unknown;
16
- });
17
- }
18
- /**
19
- * A signed Apple token was rejected.
20
- *
21
- * Deny by default: anything that raises this must be treated as "not
22
- * entitled", never as "probably fine".
23
- */
24
- export declare class IapVerificationError extends IapError {
25
- readonly code: IapVerificationErrorCode;
26
- constructor(code: IapVerificationErrorCode, message: string, options?: {
27
- cause?: unknown;
28
- });
29
- }
30
- /** The module cannot start, or was asked for something its configuration does not allow. */
31
- export declare class IapConfigError extends IapError {
32
- readonly code: IapConfigErrorCode;
33
- constructor(code: IapConfigErrorCode, message: string, options?: {
34
- cause?: unknown;
35
- });
36
- }
37
- /**
38
- * The app's Base44 setup is not usable — an entity is missing, or its schema
39
- * has drifted from what the SDK writes.
40
- *
41
- * This is loud on purpose. A silently dropped field means purchase data is
42
- * being lost, which is worse than an outage.
43
- */
44
- export declare class IapSetupError extends IapError {
45
- readonly code: IapSetupErrorCode;
46
- /** The entity the problem was found on. */
47
- readonly entityName?: string;
48
- /** Fields the entity dropped, when the code is `IAP_ENTITY_SCHEMA_DRIFT`. */
49
- readonly missingFields?: string[];
50
- constructor(code: IapSetupErrorCode, message: string, details?: {
51
- entityName?: string;
52
- missingFields?: string[];
53
- cause?: unknown;
54
- });
55
- }
56
- /** A read or write against the app's entities failed. */
57
- export declare class IapStoreError extends IapError {
58
- readonly code: IapStoreErrorCode;
59
- /** The entity being read or written. */
60
- readonly entityName?: string;
61
- constructor(code: IapStoreErrorCode, message: string, details?: {
62
- entityName?: string;
63
- cause?: unknown;
64
- });
65
- }
66
- /** An App Store Server API call failed. */
67
- export declare class IapApiError extends IapError {
68
- readonly code: IapApiErrorCode;
69
- /** The HTTP status Apple returned. */
70
- readonly httpStatus?: number;
71
- /** Apple's own numeric error code from the response body, e.g. `4040010`. */
72
- readonly appleErrorCode?: number;
73
- /** Apple's own error message from the response body. */
74
- readonly appleErrorMessage?: string;
75
- /**
76
- * When rate-limited: the value of Apple's `Retry-After` header.
77
- *
78
- * Apple sends an **absolute UNIX millisecond timestamp** here, not a delay.
79
- * Compare it against `Date.now()`; do not use it as a duration.
80
- */
81
- readonly retryAfter?: number;
82
- constructor(code: IapApiErrorCode, message: string, details?: {
83
- httpStatus?: number;
84
- appleErrorCode?: number;
85
- appleErrorMessage?: string;
86
- retryAfter?: number;
87
- cause?: unknown;
88
- });
89
- }
@@ -1,66 +0,0 @@
1
- /** Base class, so a caller can catch every error this module raises at once. */
2
- export class IapError extends Error {
3
- constructor(code, message, options) {
4
- super(message);
5
- this.name = "IapError";
6
- this.code = code;
7
- // `cause` is set by hand rather than passed to super: the emit target is
8
- // es2018, whose Error constructor takes no options bag.
9
- if (options && "cause" in options) {
10
- this.cause = options.cause;
11
- }
12
- }
13
- }
14
- /**
15
- * A signed Apple token was rejected.
16
- *
17
- * Deny by default: anything that raises this must be treated as "not
18
- * entitled", never as "probably fine".
19
- */
20
- export class IapVerificationError extends IapError {
21
- constructor(code, message, options) {
22
- super(code, message, options);
23
- this.name = "IapVerificationError";
24
- }
25
- }
26
- /** The module cannot start, or was asked for something its configuration does not allow. */
27
- export class IapConfigError extends IapError {
28
- constructor(code, message, options) {
29
- super(code, message, options);
30
- this.name = "IapConfigError";
31
- }
32
- }
33
- /**
34
- * The app's Base44 setup is not usable — an entity is missing, or its schema
35
- * has drifted from what the SDK writes.
36
- *
37
- * This is loud on purpose. A silently dropped field means purchase data is
38
- * being lost, which is worse than an outage.
39
- */
40
- export class IapSetupError extends IapError {
41
- constructor(code, message, details) {
42
- super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
43
- this.name = "IapSetupError";
44
- this.entityName = details === null || details === void 0 ? void 0 : details.entityName;
45
- this.missingFields = details === null || details === void 0 ? void 0 : details.missingFields;
46
- }
47
- }
48
- /** A read or write against the app's entities failed. */
49
- export class IapStoreError extends IapError {
50
- constructor(code, message, details) {
51
- super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
52
- this.name = "IapStoreError";
53
- this.entityName = details === null || details === void 0 ? void 0 : details.entityName;
54
- }
55
- }
56
- /** An App Store Server API call failed. */
57
- export class IapApiError extends IapError {
58
- constructor(code, message, details) {
59
- super(code, message, { cause: details === null || details === void 0 ? void 0 : details.cause });
60
- this.name = "IapApiError";
61
- this.httpStatus = details === null || details === void 0 ? void 0 : details.httpStatus;
62
- this.appleErrorCode = details === null || details === void 0 ? void 0 : details.appleErrorCode;
63
- this.appleErrorMessage = details === null || details === void 0 ? void 0 : details.appleErrorMessage;
64
- this.retryAfter = details === null || details === void 0 ? void 0 : details.retryAfter;
65
- }
66
- }
@@ -1,74 +0,0 @@
1
- /**
2
- * Error codes the in-app purchase module can raise.
3
- *
4
- * Every code is a stable string. Generated code and support tooling branch on
5
- * these, so a code is never renamed — a new situation gets a new code.
6
- */
7
- /**
8
- * Why a signed Apple token was rejected.
9
- *
10
- * The first eight come straight from the verification algorithm Apple
11
- * describes; the last two are this SDK's own.
12
- */
13
- export type IapVerificationErrorCode =
14
- /** The token is not three base64url segments separated by dots. */
15
- "INVALID_JWS_FORMAT"
16
- /** The JWS header named an algorithm other than `ES256`. */
17
- | "UNSUPPORTED_ALG"
18
- /** The `x5c` header did not carry exactly three certificates. */
19
- | "INVALID_CHAIN_LENGTH"
20
- /** A certificate failed to parse, was outside its validity window, or lacked a required marker. */
21
- | "INVALID_CERTIFICATE"
22
- /** A certificate was revoked. Only reachable with online checks, which v1 does not support. */
23
- | "CERTIFICATE_REVOKED"
24
- /** The signature did not verify against the leaf certificate's public key. */
25
- | "INVALID_SIGNATURE"
26
- /** The payload's `bundleId`, or its `appAppleId` in production, did not match the configuration. */
27
- | "INVALID_APP_IDENTIFIER"
28
- /** The payload's `environment` was not one this app accepts. */
29
- | "INVALID_ENVIRONMENT"
30
- /** A transient failure. Retrying may succeed. */
31
- | "RETRYABLE_VERIFICATION_FAILURE"
32
- /**
33
- * The chain anchored at a root this SDK cannot verify against — an RSA root.
34
- *
35
- * Current App Store tokens chain to Apple Root CA - G3, which is ECDSA
36
- * P-384. Apple Root CA - G2 and Apple Inc. Root are RSA and are pinned for
37
- * completeness, but v1 verifies ECDSA signatures only. This is never
38
- * downgraded to a pass.
39
- */
40
- | "UNSUPPORTED_CERT_ALGORITHM";
41
- /** Why the module refused to start, or could not use its configuration. */
42
- export type IapConfigErrorCode =
43
- /** A required configuration field was missing or malformed. */
44
- "IAP_INVALID_CONFIG"
45
- /** `onlineChecks: true` was requested. Certificate revocation lookups are not implemented in v1. */
46
- | "IAP_ONLINE_CHECKS_UNSUPPORTED"
47
- /** The runtime has no WebCrypto. Needs Deno, Node 18 or later, or a secure browser context. */
48
- | "IAP_WEBCRYPTO_UNAVAILABLE"
49
- /** The runtime has no `fetch`. Needs Deno, Node 18 or later, or a browser. */
50
- | "IAP_FETCH_UNAVAILABLE"
51
- /** An App Store Server API call was made without `serverApi` credentials configured. */
52
- | "IAP_SERVER_API_NOT_CONFIGURED";
53
- /** Why the app's own Base44 setup is not usable for in-app purchases. */
54
- export type IapSetupErrorCode =
55
- /** One of the four required entities does not exist in this app. */
56
- "IAP_ENTITY_MISSING"
57
- /** An entity exists but silently dropped a field the SDK wrote. Its schema has drifted. */
58
- | "IAP_ENTITY_SCHEMA_DRIFT"
59
- /** The client was created without service-role credentials, so it cannot write. */
60
- | "IAP_SERVICE_ROLE_REQUIRED";
61
- /** Why a read or write against the app's entities failed. */
62
- export type IapStoreErrorCode =
63
- /** The write did not land. Callers must not report success to Apple or finish a transaction. */
64
- "IAP_WRITE_FAILED"
65
- /** The read did not complete. */
66
- | "IAP_READ_FAILED";
67
- /** Why an App Store Server API call failed. */
68
- export type IapApiErrorCode =
69
- /** Apple answered with an error status. Inspect `appleErrorCode` for which. */
70
- "IAP_API_ERROR"
71
- /** Apple rate-limited the call. `retryAfter` carries the absolute timestamp to retry after. */
72
- | "IAP_API_RATE_LIMITED"
73
- /** The transaction id exists in neither the production nor the sandbox environment. */
74
- | "IAP_API_TRANSACTION_NOT_FOUND";
@@ -1,7 +0,0 @@
1
- /**
2
- * Error codes the in-app purchase module can raise.
3
- *
4
- * Every code is a stable string. Generated code and support tooling branch on
5
- * these, so a code is never renamed — a new situation gets a new code.
6
- */
7
- export {};
@@ -1,28 +0,0 @@
1
- /**
2
- * Delivering events to the app's handlers.
3
- *
4
- * Two rules, both about not letting an app's own code break Apple's contract:
5
- *
6
- * 1. **A handler runs after the write, never before.** An event means the data
7
- * behind it is already stored.
8
- * 2. **A handler can never change the outcome.** If one throws, the throw is
9
- * swallowed and reported; the HTTP response Apple sees is unaffected.
10
- *
11
- * Events are dispatched *synchronously* before the response is returned, not
12
- * after it. A Base44 backend function has no way to run work once it has
13
- * answered — there is no `waitUntil` — so anything deferred until after the
14
- * response is simply lost when the isolate stops.
15
- *
16
- * @internal
17
- */
18
- import type { IapEvent, IapEventHandler } from "./events.types.js";
19
- /** Reports a handler that threw. Defaults to a single console line. */
20
- export type IapHandlerFailureReporter = (event: IapEvent, error: unknown) => void;
21
- /** The event bus for one client. */
22
- export interface IapEmitter {
23
- /** Registers a handler. Returns a function that removes it. */
24
- onEvent(handler: IapEventHandler): () => void;
25
- /** Delivers events to every handler, swallowing their failures. */
26
- emit(events: readonly IapEvent[]): Promise<void>;
27
- }
28
- export declare function createEmitter(reportFailure?: IapHandlerFailureReporter): IapEmitter;