@koolbase/core 10.0.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.
Files changed (104) hide show
  1. package/README.md +19 -0
  2. package/dist/cjs/analytics.d.ts +24 -0
  3. package/dist/cjs/analytics.js +110 -0
  4. package/dist/cjs/auth-errors.d.ts +117 -0
  5. package/dist/cjs/auth-errors.js +250 -0
  6. package/dist/cjs/auth.d.ts +213 -0
  7. package/dist/cjs/auth.js +813 -0
  8. package/dist/cjs/cache-store.d.ts +50 -0
  9. package/dist/cjs/cache-store.js +194 -0
  10. package/dist/cjs/conflict.d.ts +80 -0
  11. package/dist/cjs/conflict.js +84 -0
  12. package/dist/cjs/database-errors.d.ts +101 -0
  13. package/dist/cjs/database-errors.js +200 -0
  14. package/dist/cjs/database.d.ts +298 -0
  15. package/dist/cjs/database.js +852 -0
  16. package/dist/cjs/device-id.d.ts +1 -0
  17. package/dist/cjs/device-id.js +57 -0
  18. package/dist/cjs/device-metadata.d.ts +36 -0
  19. package/dist/cjs/device-metadata.js +94 -0
  20. package/dist/cjs/errors.d.ts +64 -0
  21. package/dist/cjs/errors.js +85 -0
  22. package/dist/cjs/flags.d.ts +15 -0
  23. package/dist/cjs/flags.js +76 -0
  24. package/dist/cjs/function-errors.d.ts +51 -0
  25. package/dist/cjs/function-errors.js +103 -0
  26. package/dist/cjs/functions.d.ts +15 -0
  27. package/dist/cjs/functions.js +83 -0
  28. package/dist/cjs/index.d.ts +22 -0
  29. package/dist/cjs/index.js +56 -0
  30. package/dist/cjs/messaging.d.ts +13 -0
  31. package/dist/cjs/messaging.js +36 -0
  32. package/dist/cjs/offline-state.d.ts +97 -0
  33. package/dist/cjs/offline-state.js +198 -0
  34. package/dist/cjs/package.json +3 -0
  35. package/dist/cjs/pending-write.d.ts +47 -0
  36. package/dist/cjs/pending-write.js +22 -0
  37. package/dist/cjs/platform.d.ts +51 -0
  38. package/dist/cjs/platform.js +41 -0
  39. package/dist/cjs/realtime.d.ts +44 -0
  40. package/dist/cjs/realtime.js +195 -0
  41. package/dist/cjs/record.d.ts +2 -0
  42. package/dist/cjs/record.js +23 -0
  43. package/dist/cjs/shared.d.ts +9 -0
  44. package/dist/cjs/shared.js +43 -0
  45. package/dist/cjs/storage-errors.d.ts +163 -0
  46. package/dist/cjs/storage-errors.js +253 -0
  47. package/dist/cjs/storage.d.ts +198 -0
  48. package/dist/cjs/storage.js +451 -0
  49. package/dist/cjs/sync-engine.d.ts +30 -0
  50. package/dist/cjs/sync-engine.js +286 -0
  51. package/dist/cjs/types.d.ts +487 -0
  52. package/dist/cjs/types.js +40 -0
  53. package/dist/esm/analytics.d.ts +24 -0
  54. package/dist/esm/analytics.js +106 -0
  55. package/dist/esm/auth-errors.d.ts +117 -0
  56. package/dist/esm/auth-errors.js +222 -0
  57. package/dist/esm/auth.d.ts +213 -0
  58. package/dist/esm/auth.js +809 -0
  59. package/dist/esm/cache-store.d.ts +50 -0
  60. package/dist/esm/cache-store.js +179 -0
  61. package/dist/esm/conflict.d.ts +80 -0
  62. package/dist/esm/conflict.js +80 -0
  63. package/dist/esm/database-errors.d.ts +101 -0
  64. package/dist/esm/database-errors.js +189 -0
  65. package/dist/esm/database.d.ts +298 -0
  66. package/dist/esm/database.js +848 -0
  67. package/dist/esm/device-id.d.ts +1 -0
  68. package/dist/esm/device-id.js +54 -0
  69. package/dist/esm/device-metadata.d.ts +36 -0
  70. package/dist/esm/device-metadata.js +90 -0
  71. package/dist/esm/errors.d.ts +64 -0
  72. package/dist/esm/errors.js +79 -0
  73. package/dist/esm/flags.d.ts +15 -0
  74. package/dist/esm/flags.js +72 -0
  75. package/dist/esm/function-errors.d.ts +51 -0
  76. package/dist/esm/function-errors.js +93 -0
  77. package/dist/esm/functions.d.ts +15 -0
  78. package/dist/esm/functions.js +79 -0
  79. package/dist/esm/index.d.ts +22 -0
  80. package/dist/esm/index.js +25 -0
  81. package/dist/esm/messaging.d.ts +13 -0
  82. package/dist/esm/messaging.js +32 -0
  83. package/dist/esm/offline-state.d.ts +97 -0
  84. package/dist/esm/offline-state.js +189 -0
  85. package/dist/esm/package.json +3 -0
  86. package/dist/esm/pending-write.d.ts +47 -0
  87. package/dist/esm/pending-write.js +19 -0
  88. package/dist/esm/platform.d.ts +51 -0
  89. package/dist/esm/platform.js +36 -0
  90. package/dist/esm/realtime.d.ts +44 -0
  91. package/dist/esm/realtime.js +191 -0
  92. package/dist/esm/record.d.ts +2 -0
  93. package/dist/esm/record.js +20 -0
  94. package/dist/esm/shared.d.ts +9 -0
  95. package/dist/esm/shared.js +39 -0
  96. package/dist/esm/storage-errors.d.ts +163 -0
  97. package/dist/esm/storage-errors.js +239 -0
  98. package/dist/esm/storage.d.ts +198 -0
  99. package/dist/esm/storage.js +447 -0
  100. package/dist/esm/sync-engine.d.ts +30 -0
  101. package/dist/esm/sync-engine.js +282 -0
  102. package/dist/esm/types.d.ts +487 -0
  103. package/dist/esm/types.js +37 -0
  104. package/package.json +45 -0
@@ -0,0 +1 @@
1
+ export declare function getOrCreateDeviceId(): Promise<string>;
@@ -0,0 +1,54 @@
1
+ import { getPlatform } from './platform.js';
2
+ // Single source of the anonymous device identifier for the whole SDK.
3
+ // Generated once, persisted, and shared by messaging (registration keying),
4
+ // feature flags (rollout bucketing: stableHash(deviceId + ":" + key) % 100),
5
+ // code push (targeting), and analytics. Previously each subsystem was handed a
6
+ // hardcoded 'rn-device' literal, so every RN device collided on one messaging
7
+ // registration row and bucketed identically for every rollout — a 10% flag was
8
+ // on for everyone or no one, never 10%.
9
+ //
10
+ // The id is anonymous, not a secret: what matters is uniform DISTRIBUTION so
11
+ // hash(id) % 100 is even, not unpredictability. We use crypto.getRandomValues
12
+ // when the runtime provides it (best distribution, no modulo bias) and fall
13
+ // back to Math.random otherwise — mirroring the runtime-guarded crypto use
14
+ // already in code-push.ts, and adding no dependency (per the SDK's stated
15
+ // preference against a crypto-grade UUID dependency for non-security ids).
16
+ const DEVICE_ID_KEY = 'koolbase:device_id';
17
+ let _cached = null;
18
+ export async function getOrCreateDeviceId() {
19
+ if (_cached)
20
+ return _cached;
21
+ try {
22
+ const existing = await getPlatform().storage.getItem(DEVICE_ID_KEY);
23
+ if (existing) {
24
+ _cached = existing;
25
+ return existing;
26
+ }
27
+ const newId = generateUUID();
28
+ await getPlatform().storage.setItem(DEVICE_ID_KEY, newId);
29
+ _cached = newId;
30
+ return newId;
31
+ }
32
+ catch {
33
+ // Storage unavailable — return an ephemeral (unpersisted) id so the SDK
34
+ // stays functional rather than throwing. Not stable across launches.
35
+ return generateUUID();
36
+ }
37
+ }
38
+ // UUID v4. Uses crypto.getRandomValues where available for uniform,
39
+ // modulo-bias-free bytes; Math.random fallback keeps it dependency-free.
40
+ function generateUUID() {
41
+ const bytes = new Uint8Array(16);
42
+ const c = typeof crypto !== 'undefined' ? crypto : undefined;
43
+ if (c && typeof c.getRandomValues === 'function') {
44
+ c.getRandomValues(bytes);
45
+ }
46
+ else {
47
+ for (let i = 0; i < 16; i++)
48
+ bytes[i] = (Math.random() * 256) | 0;
49
+ }
50
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
51
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant
52
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
53
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
54
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Koolbase React Native SDK version. Sent in the `x-koolbase-sdk-version`
3
+ * header on every authenticated request so the server can route
4
+ * version-conditional logic (deprecation warnings, schema migrations,
5
+ * feature flags). Must match the `version` field in package.json.
6
+ */
7
+ export declare const koolbaseSdkVersion = "10.0.0";
8
+ /**
9
+ * Builds device-identifying headers attached to every Koolbase auth
10
+ * request. Mirrors the Flutter SDK's `DeviceMetadata` for parity. Apps
11
+ * with privacy concerns can swap in a custom storage adapter to avoid
12
+ * persisting the device label.
13
+ *
14
+ * Headers emitted:
15
+ * - User-Agent: koolbase-react-native/<sdk> (<platform> <version>)
16
+ * - x-koolbase-sdk: react-native
17
+ * - x-koolbase-sdk-version: <koolbaseSdkVersion>
18
+ * - x-koolbase-platform: ios | android | web | etc.
19
+ * - x-koolbase-platform-version: numeric SDK level or OS version string
20
+ * - x-koolbase-app-version: from KoolbaseConfig.appVersion or 'unknown'
21
+ * - x-koolbase-device-label: persistent UUID per install
22
+ */
23
+ export declare class DeviceMetadata {
24
+ private cached;
25
+ private ephemeralLabel;
26
+ private readonly appVersion;
27
+ constructor(appVersion?: string);
28
+ /**
29
+ * Build (or return cached) device headers. The first call may perform
30
+ * an async keychain read to look up the persisted device label;
31
+ * subsequent calls return the in-memory cache synchronously via the
32
+ * returned Promise.
33
+ */
34
+ build(): Promise<Record<string, string>>;
35
+ private getOrCreateDeviceLabel;
36
+ }
@@ -0,0 +1,90 @@
1
+ import { getPlatform } from './platform.js';
2
+ /**
3
+ * Koolbase React Native SDK version. Sent in the `x-koolbase-sdk-version`
4
+ * header on every authenticated request so the server can route
5
+ * version-conditional logic (deprecation warnings, schema migrations,
6
+ * feature flags). Must match the `version` field in package.json.
7
+ */
8
+ export const koolbaseSdkVersion = '10.0.0';
9
+ /**
10
+ * Generate a UUIDv4-shaped string for use as a stable per-install
11
+ * device label. Not cryptographically secure — this is a label, not a
12
+ * security primitive. Avoids pulling in a crypto-grade UUID dependency.
13
+ */
14
+ function generateDeviceLabel() {
15
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
16
+ const r = (Math.random() * 16) | 0;
17
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
18
+ return v.toString(16);
19
+ });
20
+ }
21
+ /**
22
+ * Builds device-identifying headers attached to every Koolbase auth
23
+ * request. Mirrors the Flutter SDK's `DeviceMetadata` for parity. Apps
24
+ * with privacy concerns can swap in a custom storage adapter to avoid
25
+ * persisting the device label.
26
+ *
27
+ * Headers emitted:
28
+ * - User-Agent: koolbase-react-native/<sdk> (<platform> <version>)
29
+ * - x-koolbase-sdk: react-native
30
+ * - x-koolbase-sdk-version: <koolbaseSdkVersion>
31
+ * - x-koolbase-platform: ios | android | web | etc.
32
+ * - x-koolbase-platform-version: numeric SDK level or OS version string
33
+ * - x-koolbase-app-version: from KoolbaseConfig.appVersion or 'unknown'
34
+ * - x-koolbase-device-label: persistent UUID per install
35
+ */
36
+ export class DeviceMetadata {
37
+ constructor(appVersion) {
38
+ this.cached = null;
39
+ this.ephemeralLabel = null;
40
+ this.appVersion = appVersion ?? 'unknown';
41
+ }
42
+ /**
43
+ * Build (or return cached) device headers. The first call may perform
44
+ * an async keychain read to look up the persisted device label;
45
+ * subsequent calls return the in-memory cache synchronously via the
46
+ * returned Promise.
47
+ */
48
+ async build() {
49
+ if (this.cached)
50
+ return this.cached;
51
+ const platform = getPlatform().info.os;
52
+ const platformVersion = getPlatform().info.version;
53
+ const deviceLabel = await this.getOrCreateDeviceLabel();
54
+ // No User-Agent: a browser forbids setting it, and the same header set
55
+ // now goes out from both hosts. The platform and version below carry
56
+ // what it used to say.
57
+ this.cached = {
58
+ 'x-koolbase-sdk': getPlatform().info.os === 'web' ? 'js' : 'react-native',
59
+ 'x-koolbase-sdk-version': koolbaseSdkVersion,
60
+ 'x-koolbase-platform': platform,
61
+ 'x-koolbase-platform-version': platformVersion,
62
+ 'x-koolbase-app-version': this.appVersion,
63
+ 'x-koolbase-device-label': deviceLabel,
64
+ };
65
+ return this.cached;
66
+ }
67
+ async getOrCreateDeviceLabel() {
68
+ // A stable per-install label, kept in the platform's storage. On a host
69
+ // with nothing persistent (the in-memory adapter) it lives for the
70
+ // session, which is still useful for in-session debugging.
71
+ const key = 'koolbase_device_label_v1';
72
+ const storage = getPlatform().storage;
73
+ try {
74
+ const existing = await storage.getItem(key);
75
+ if (existing)
76
+ return existing;
77
+ }
78
+ catch {
79
+ // fall through to create
80
+ }
81
+ const newLabel = generateDeviceLabel();
82
+ try {
83
+ await storage.setItem(key, newLabel);
84
+ }
85
+ catch {
86
+ // storage refused; the label still serves this session
87
+ }
88
+ return newLabel;
89
+ }
90
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The root of every error the SDK raises.
3
+ *
4
+ * Each subsystem has its own family beneath this — data, storage, auth — so an
5
+ * application can catch narrowly where it wants to and broadly where it does
6
+ * not:
7
+ *
8
+ * ```ts
9
+ * try {
10
+ * await Koolbase.storage.upload(...);
11
+ * } catch (e) {
12
+ * if (e instanceof KoolbaseUnauthenticatedError) return goToLogin();
13
+ * if (e instanceof KoolbaseStorageError) return showError(e.message);
14
+ * throw e;
15
+ * }
16
+ * ```
17
+ *
18
+ * The families used to be unrelated roots, which meant a failure belonging to no
19
+ * single subsystem — a rejected credential, discovered by whichever call
20
+ * happened to make it — had to be redefined in each one.
21
+ */
22
+ export declare class KoolbaseError extends Error {
23
+ code?: string;
24
+ constructor(message: string, code?: string);
25
+ }
26
+ /**
27
+ * The server would not accept the caller's credentials.
28
+ *
29
+ * Raised by any surface — a query, an upload, a Function invoke — because a
30
+ * session stops working for the whole SDK at once, not one subsystem at a time.
31
+ *
32
+ * Named for what the server actually reports. A 401 covers an expired session, a
33
+ * revoked key, a malformed header, and no credentials at all, and the server
34
+ * does not distinguish them: calling this "session expired" would claim a
35
+ * precision that does not exist, and an app that signed a user out on a revoked
36
+ * API key would be acting on it.
37
+ *
38
+ * When the SDK holds a session it clears it before throwing, so by the time an
39
+ * application catches this the user is already signed out.
40
+ */
41
+ export declare class KoolbaseUnauthenticatedError extends KoolbaseError {
42
+ constructor(message: string);
43
+ }
44
+ /**
45
+ * An offline update or delete could not be queued, because the SDK has no
46
+ * record of what the change was composed against.
47
+ *
48
+ * Replaying a mutation without knowing the state it was based on means applying
49
+ * it blindly: whatever changed on the server in the meantime is overwritten,
50
+ * silently, with nobody able to tell it happened.
51
+ *
52
+ * A baseline is available when the record is in the local cache — read through
53
+ * a query, a single fetch, or seen over the socket — or when it was created
54
+ * offline and its insert is still queued. It is unavailable when the record has
55
+ * never been seen on this device, so read it first, or make the change while
56
+ * online where the server arbitrates directly.
57
+ *
58
+ * Deliberate rather than lenient. Queueing these anyway would mean most offline
59
+ * updates are conflict-safe and some quietly are not, which is a worse guarantee
60
+ * than a clear refusal.
61
+ */
62
+ export declare class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
63
+ constructor(message: string);
64
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The root of every error the SDK raises.
3
+ *
4
+ * Each subsystem has its own family beneath this — data, storage, auth — so an
5
+ * application can catch narrowly where it wants to and broadly where it does
6
+ * not:
7
+ *
8
+ * ```ts
9
+ * try {
10
+ * await Koolbase.storage.upload(...);
11
+ * } catch (e) {
12
+ * if (e instanceof KoolbaseUnauthenticatedError) return goToLogin();
13
+ * if (e instanceof KoolbaseStorageError) return showError(e.message);
14
+ * throw e;
15
+ * }
16
+ * ```
17
+ *
18
+ * The families used to be unrelated roots, which meant a failure belonging to no
19
+ * single subsystem — a rejected credential, discovered by whichever call
20
+ * happened to make it — had to be redefined in each one.
21
+ */
22
+ export class KoolbaseError extends Error {
23
+ constructor(message, code) {
24
+ super(message);
25
+ this.code = code;
26
+ this.name = 'KoolbaseError';
27
+ // Required for `instanceof` to work across the prototype chain when
28
+ // targeting ES5-era output, which TypeScript's class extension otherwise
29
+ // breaks. Every subclass repeats it for the same reason.
30
+ Object.setPrototypeOf(this, new.target.prototype);
31
+ }
32
+ }
33
+ /**
34
+ * The server would not accept the caller's credentials.
35
+ *
36
+ * Raised by any surface — a query, an upload, a Function invoke — because a
37
+ * session stops working for the whole SDK at once, not one subsystem at a time.
38
+ *
39
+ * Named for what the server actually reports. A 401 covers an expired session, a
40
+ * revoked key, a malformed header, and no credentials at all, and the server
41
+ * does not distinguish them: calling this "session expired" would claim a
42
+ * precision that does not exist, and an app that signed a user out on a revoked
43
+ * API key would be acting on it.
44
+ *
45
+ * When the SDK holds a session it clears it before throwing, so by the time an
46
+ * application catches this the user is already signed out.
47
+ */
48
+ export class KoolbaseUnauthenticatedError extends KoolbaseError {
49
+ constructor(message) {
50
+ super(message, 'unauthenticated');
51
+ this.name = 'KoolbaseUnauthenticatedError';
52
+ Object.setPrototypeOf(this, new.target.prototype);
53
+ }
54
+ }
55
+ /**
56
+ * An offline update or delete could not be queued, because the SDK has no
57
+ * record of what the change was composed against.
58
+ *
59
+ * Replaying a mutation without knowing the state it was based on means applying
60
+ * it blindly: whatever changed on the server in the meantime is overwritten,
61
+ * silently, with nobody able to tell it happened.
62
+ *
63
+ * A baseline is available when the record is in the local cache — read through
64
+ * a query, a single fetch, or seen over the socket — or when it was created
65
+ * offline and its insert is still queued. It is unavailable when the record has
66
+ * never been seen on this device, so read it first, or make the change while
67
+ * online where the server arbitrates directly.
68
+ *
69
+ * Deliberate rather than lenient. Queueing these anyway would mean most offline
70
+ * updates are conflict-safe and some quietly are not, which is a worse guarantee
71
+ * than a clear refusal.
72
+ */
73
+ export class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
74
+ constructor(message) {
75
+ super(message, 'offline_baseline_unavailable');
76
+ this.name = 'KoolbaseOfflineBaselineUnavailableError';
77
+ Object.setPrototypeOf(this, new.target.prototype);
78
+ }
79
+ }
@@ -0,0 +1,15 @@
1
+ import { KoolbaseConfig, VersionCheckResult } from './types.js';
2
+ export declare class KoolbaseFlags {
3
+ private config;
4
+ private payload;
5
+ private deviceId;
6
+ constructor(config: KoolbaseConfig, deviceId: string);
7
+ fetch(appVersion: string, platform: string): Promise<void>;
8
+ isEnabled(key: string): boolean;
9
+ getString(key: string, fallback?: string): string;
10
+ getNumber(key: string, fallback?: number): number;
11
+ getBool(key: string, fallback?: boolean): boolean;
12
+ checkVersion(currentVersion: string): VersionCheckResult;
13
+ private parseVersion;
14
+ private stableHash;
15
+ }
@@ -0,0 +1,72 @@
1
+ export class KoolbaseFlags {
2
+ constructor(config, deviceId) {
3
+ this.payload = null;
4
+ this.config = config;
5
+ this.deviceId = deviceId;
6
+ }
7
+ async fetch(appVersion, platform) {
8
+ try {
9
+ const res = await fetch(`${this.config.baseUrl}/v1/bootstrap?public_key=${this.config.publicKey}&device_id=${this.deviceId}&app_version=${appVersion}&platform=${platform}`);
10
+ if (res.ok) {
11
+ this.payload = await res.json();
12
+ }
13
+ }
14
+ catch (_) { }
15
+ }
16
+ isEnabled(key) {
17
+ const flag = this.payload?.flags[key];
18
+ if (!flag || !flag.enabled || flag.kill_switch)
19
+ return false;
20
+ const bucket = this.stableHash(`${this.deviceId}:${key}`) % 100;
21
+ return bucket < flag.rollout_percentage;
22
+ }
23
+ getString(key, fallback = '') {
24
+ const val = this.payload?.config[key];
25
+ return val !== undefined ? String(val) : fallback;
26
+ }
27
+ getNumber(key, fallback = 0) {
28
+ const val = this.payload?.config[key];
29
+ return typeof val === 'number' ? val : Number(val) || fallback;
30
+ }
31
+ getBool(key, fallback = false) {
32
+ const val = this.payload?.config[key];
33
+ if (typeof val === 'boolean')
34
+ return val;
35
+ return val === 'true' ? true : fallback;
36
+ }
37
+ checkVersion(currentVersion) {
38
+ const policy = this.payload?.version;
39
+ if (!policy?.min_version) {
40
+ return { status: 'up_to_date', message: '', latestVersion: '' };
41
+ }
42
+ const current = this.parseVersion(currentVersion);
43
+ const min = this.parseVersion(policy.min_version);
44
+ const latest = this.parseVersion(policy.latest_version);
45
+ if (current < min) {
46
+ return {
47
+ status: 'force_update',
48
+ message: policy.update_message,
49
+ latestVersion: policy.latest_version,
50
+ };
51
+ }
52
+ if (policy.latest_version && current < latest) {
53
+ return {
54
+ status: policy.force_update ? 'force_update' : 'soft_update',
55
+ message: policy.update_message,
56
+ latestVersion: policy.latest_version,
57
+ };
58
+ }
59
+ return { status: 'up_to_date', message: '', latestVersion: policy.latest_version };
60
+ }
61
+ parseVersion(v) {
62
+ const parts = v.split('.').map(Number);
63
+ return (parts[0] ?? 0) * 10000 + (parts[1] ?? 0) * 100 + (parts[2] ?? 0);
64
+ }
65
+ stableHash(s) {
66
+ let hash = 0;
67
+ for (let i = 0; i < s.length; i++) {
68
+ hash = (Math.imul(31, hash) + s.charCodeAt(i)) | 0;
69
+ }
70
+ return Math.abs(hash);
71
+ }
72
+ }
@@ -0,0 +1,51 @@
1
+ import { KoolbaseError } from './errors.js';
2
+ /**
3
+ * A Function call did not succeed.
4
+ *
5
+ * Every failure used to be a bare `Error`, so an application could only match on
6
+ * message text — and a missing Function, a caller without permission, a Function
7
+ * that threw, and an exhausted plan limit all looked alike, though they call for
8
+ * entirely different responses.
9
+ */
10
+ export declare class FunctionInvokeError extends KoolbaseError {
11
+ statusCode?: number;
12
+ constructor(message: string, statusCode?: number, code?: string);
13
+ }
14
+ /** No Function by that name is deployed to this project. */
15
+ export declare class FunctionNotFoundError extends FunctionInvokeError {
16
+ constructor(message: string);
17
+ }
18
+ /**
19
+ * The caller may not invoke this Function.
20
+ *
21
+ * Distinct from an authentication failure: the credentials were accepted and
22
+ * this caller is not permitted. Retrying will not help, and signing the user out
23
+ * would be wrong.
24
+ */
25
+ export declare class FunctionPermissionError extends FunctionInvokeError {
26
+ constructor(message: string);
27
+ }
28
+ /** The Function rejected its arguments. */
29
+ export declare class FunctionValidationError extends FunctionInvokeError {
30
+ constructor(message: string);
31
+ }
32
+ /**
33
+ * The project's Function invocations are used up.
34
+ *
35
+ * Nothing about the call is wrong — retrying will not help until the plan
36
+ * allows it. The one failure here fixed by changing a plan rather than code.
37
+ */
38
+ export declare class FunctionQuotaExceededError extends FunctionInvokeError {
39
+ constructor(message: string);
40
+ }
41
+ /**
42
+ * The Function ran and threw.
43
+ *
44
+ * The message is the Function's own, not the platform's — it comes from the code
45
+ * that was deployed.
46
+ */
47
+ export declare class FunctionExecutionError extends FunctionInvokeError {
48
+ constructor(message: string, statusCode?: number);
49
+ }
50
+ /** Builds the right error for a failed invocation. */
51
+ export declare function functionInvokeError(status: number, message: string): KoolbaseError;
@@ -0,0 +1,93 @@
1
+ import { KoolbaseError, KoolbaseUnauthenticatedError } from './errors.js';
2
+ /**
3
+ * A Function call did not succeed.
4
+ *
5
+ * Every failure used to be a bare `Error`, so an application could only match on
6
+ * message text — and a missing Function, a caller without permission, a Function
7
+ * that threw, and an exhausted plan limit all looked alike, though they call for
8
+ * entirely different responses.
9
+ */
10
+ export class FunctionInvokeError extends KoolbaseError {
11
+ constructor(message, statusCode, code) {
12
+ super(message, code);
13
+ this.statusCode = statusCode;
14
+ this.name = 'FunctionInvokeError';
15
+ Object.setPrototypeOf(this, new.target.prototype);
16
+ }
17
+ }
18
+ /** No Function by that name is deployed to this project. */
19
+ export class FunctionNotFoundError extends FunctionInvokeError {
20
+ constructor(message) {
21
+ super(message, 404, 'not_found');
22
+ this.name = 'FunctionNotFoundError';
23
+ Object.setPrototypeOf(this, new.target.prototype);
24
+ }
25
+ }
26
+ /**
27
+ * The caller may not invoke this Function.
28
+ *
29
+ * Distinct from an authentication failure: the credentials were accepted and
30
+ * this caller is not permitted. Retrying will not help, and signing the user out
31
+ * would be wrong.
32
+ */
33
+ export class FunctionPermissionError extends FunctionInvokeError {
34
+ constructor(message) {
35
+ super(message, 403, 'permission_denied');
36
+ this.name = 'FunctionPermissionError';
37
+ Object.setPrototypeOf(this, new.target.prototype);
38
+ }
39
+ }
40
+ /** The Function rejected its arguments. */
41
+ export class FunctionValidationError extends FunctionInvokeError {
42
+ constructor(message) {
43
+ super(message, 400, 'validation_error');
44
+ this.name = 'FunctionValidationError';
45
+ Object.setPrototypeOf(this, new.target.prototype);
46
+ }
47
+ }
48
+ /**
49
+ * The project's Function invocations are used up.
50
+ *
51
+ * Nothing about the call is wrong — retrying will not help until the plan
52
+ * allows it. The one failure here fixed by changing a plan rather than code.
53
+ */
54
+ export class FunctionQuotaExceededError extends FunctionInvokeError {
55
+ constructor(message) {
56
+ super(message, 402, 'limit_reached');
57
+ this.name = 'FunctionQuotaExceededError';
58
+ Object.setPrototypeOf(this, new.target.prototype);
59
+ }
60
+ }
61
+ /**
62
+ * The Function ran and threw.
63
+ *
64
+ * The message is the Function's own, not the platform's — it comes from the code
65
+ * that was deployed.
66
+ */
67
+ export class FunctionExecutionError extends FunctionInvokeError {
68
+ constructor(message, statusCode) {
69
+ super(message, statusCode, 'execution_failed');
70
+ this.name = 'FunctionExecutionError';
71
+ Object.setPrototypeOf(this, new.target.prototype);
72
+ }
73
+ }
74
+ /** Builds the right error for a failed invocation. */
75
+ export function functionInvokeError(status, message) {
76
+ switch (status) {
77
+ case 401:
78
+ // Not a Function failure. A rejected credential stops the whole SDK
79
+ // working, so it raises the shared type.
80
+ return new KoolbaseUnauthenticatedError(message);
81
+ case 403:
82
+ return new FunctionPermissionError(message);
83
+ case 404:
84
+ return new FunctionNotFoundError(message);
85
+ case 400:
86
+ return new FunctionValidationError(message);
87
+ case 402:
88
+ return new FunctionQuotaExceededError(message);
89
+ }
90
+ if (status >= 500)
91
+ return new FunctionExecutionError(message, status);
92
+ return new FunctionInvokeError(message, status);
93
+ }
@@ -0,0 +1,15 @@
1
+ import { KoolbaseConfig, FunctionInvokeResult, DeployOptions, DeployResult } from './types.js';
2
+ export declare class KoolbaseFunctions {
3
+ private config;
4
+ private getUserAccessToken?;
5
+ /**
6
+ * Called when the server rejects the caller's credentials.
7
+ *
8
+ * A session stops working for the whole SDK at once, so an app whose failing
9
+ * call happens to be a Function invoke must not keep believing it is signed in.
10
+ */
11
+ private onSessionExpired?;
12
+ constructor(config: KoolbaseConfig, getUserAccessToken?: () => Promise<string | null>, onSessionExpired?: () => Promise<void>);
13
+ deploy(options: DeployOptions): Promise<DeployResult>;
14
+ invoke(name: string, body?: Record<string, unknown>): Promise<FunctionInvokeResult>;
15
+ }
@@ -0,0 +1,79 @@
1
+ import { functionInvokeError } from './function-errors.js';
2
+ import { KoolbaseUnauthenticatedError } from './errors.js';
3
+ import { FunctionRuntime, } from './types.js';
4
+ export class KoolbaseFunctions {
5
+ constructor(config, getUserAccessToken, onSessionExpired) {
6
+ this.config = config;
7
+ this.onSessionExpired = onSessionExpired;
8
+ this.getUserAccessToken = getUserAccessToken;
9
+ }
10
+ // ─── Deploy ────────────────────────────────────────────────────────────────
11
+ async deploy(options) {
12
+ const runtime = options.runtime ?? FunctionRuntime.Deno;
13
+ const res = await fetch(`${this.config.baseUrl}/v1/sdk/functions/deploy`, {
14
+ method: 'POST',
15
+ headers: {
16
+ 'Content-Type': 'application/json',
17
+ 'x-api-key': this.config.publicKey,
18
+ },
19
+ body: JSON.stringify({
20
+ name: options.name,
21
+ code: options.code,
22
+ runtime,
23
+ timeout_ms: options.timeoutMs ?? 10000,
24
+ }),
25
+ });
26
+ const data = await res.json().catch(() => null);
27
+ if (!res.ok) {
28
+ const message = data?.error ??
29
+ 'Function deploy failed';
30
+ const err = functionInvokeError(res.status, message);
31
+ if (err instanceof KoolbaseUnauthenticatedError) {
32
+ await this.onSessionExpired?.();
33
+ }
34
+ throw err;
35
+ }
36
+ const d = data;
37
+ return {
38
+ id: d.id,
39
+ name: d.name,
40
+ runtime: d.runtime,
41
+ version: d.version,
42
+ isActive: d.is_active,
43
+ timeoutMs: d.timeout_ms,
44
+ lastDeployedAt: d.last_deployed_at,
45
+ };
46
+ }
47
+ // ─── Invoke ────────────────────────────────────────────────────────────────
48
+ async invoke(name, body) {
49
+ const headers = {
50
+ 'Content-Type': 'application/json',
51
+ 'x-api-key': this.config.publicKey,
52
+ };
53
+ const userToken = await this.getUserAccessToken?.();
54
+ if (userToken) {
55
+ headers['Authorization'] = `Bearer ${userToken}`;
56
+ }
57
+ const res = await fetch(`${this.config.baseUrl}/v1/sdk/functions/${name}`, {
58
+ method: 'POST',
59
+ headers,
60
+ body: JSON.stringify({ body: body ?? {} }),
61
+ });
62
+ const data = await res.json().catch(() => null);
63
+ const success = res.status >= 200 && res.status < 300;
64
+ if (!success) {
65
+ const message = data?.error ??
66
+ 'Function invocation failed';
67
+ const err = functionInvokeError(res.status, message);
68
+ if (err instanceof KoolbaseUnauthenticatedError) {
69
+ await this.onSessionExpired?.();
70
+ }
71
+ throw err;
72
+ }
73
+ return {
74
+ statusCode: res.status,
75
+ data: data,
76
+ success,
77
+ };
78
+ }
79
+ }