deepspace 0.2.8 → 0.3.3
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/dist/cli.js +473 -5
- package/dist/cli.js.map +1 -1
- package/dist/worker.d.ts +453 -1
- package/dist/worker.js +444 -0
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/worker.d.ts
CHANGED
|
@@ -1650,6 +1650,268 @@ type DOBindings<T extends readonly DOManifestEntry[]> = {
|
|
|
1650
1650
|
};
|
|
1651
1651
|
/** Default manifest for apps that don't declare one */
|
|
1652
1652
|
declare const DEFAULT_DO_MANIFEST: DOManifest;
|
|
1653
|
+
/**
|
|
1654
|
+
* Shape-validate a DO manifest received over the wire (e.g. from the CLI's
|
|
1655
|
+
* deploy form-field). Without this, malformed input gets passed straight to
|
|
1656
|
+
* `deployToWfP`'s `.filter(...).map(...)` chain and crashes the route mid-deploy.
|
|
1657
|
+
*
|
|
1658
|
+
* Mirrors the contract of `validateBindingManifest` for non-DO bindings.
|
|
1659
|
+
*/
|
|
1660
|
+
declare function validateDoManifest(manifest: unknown): {
|
|
1661
|
+
valid: true;
|
|
1662
|
+
manifest: DOManifest;
|
|
1663
|
+
} | {
|
|
1664
|
+
valid: false;
|
|
1665
|
+
reason: string;
|
|
1666
|
+
};
|
|
1667
|
+
|
|
1668
|
+
/**
|
|
1669
|
+
* Binding Manifest — non-DO bindings declared by an app's wrangler.toml that
|
|
1670
|
+
* the deploy-worker should pass through to Cloudflare's WfP upload API.
|
|
1671
|
+
*
|
|
1672
|
+
* Apps don't export a `__BINDING_MANIFEST__`; the CLI extracts these from the
|
|
1673
|
+
* normalized vite/wrangler output config at deploy time. This file just owns
|
|
1674
|
+
* the types + validation so both sides (CLI client and deploy-worker server)
|
|
1675
|
+
* agree on the shape.
|
|
1676
|
+
*/
|
|
1677
|
+
/**
|
|
1678
|
+
* A single non-DO binding the app declares. Mirrors CF's WfP binding API.
|
|
1679
|
+
*
|
|
1680
|
+
* Provisionable resources (d1, kv_namespace, vectorize, r2_bucket, queue) accept
|
|
1681
|
+
* the literal string `"auto"` in their ID field to request platform-side
|
|
1682
|
+
* provisioning at deploy time. When `"auto"` is used, the deploy-worker creates
|
|
1683
|
+
* the resource on the platform CF account, persists the resulting CF ID in the
|
|
1684
|
+
* app registry, and substitutes the real ID before forwarding to WfP. The
|
|
1685
|
+
* sentinel sticks around in this type because:
|
|
1686
|
+
* 1. `wrangler` parsing requires a non-empty string in the id field
|
|
1687
|
+
* 2. The CLI passes the unresolved manifest through to the deploy-worker
|
|
1688
|
+
* 3. The deploy-worker is the only side with CF API credentials
|
|
1689
|
+
*
|
|
1690
|
+
* Companion fields (`database_name`, `title`, `dimensions`, `metric`) are only
|
|
1691
|
+
* used when `"auto"` is set — they tell the provisioner how to create the
|
|
1692
|
+
* resource. After provisioning these fields are still present on the wire but
|
|
1693
|
+
* ignored by WfP.
|
|
1694
|
+
*/
|
|
1695
|
+
type CustomBinding = {
|
|
1696
|
+
type: 'vectorize';
|
|
1697
|
+
name: string;
|
|
1698
|
+
/** Either a pre-existing index name or the literal `"auto"`. */
|
|
1699
|
+
index_name: string;
|
|
1700
|
+
/** Required when `index_name === "auto"`. */
|
|
1701
|
+
dimensions?: number;
|
|
1702
|
+
/** Required when `index_name === "auto"`. */
|
|
1703
|
+
metric?: 'cosine' | 'euclidean' | 'dot-product';
|
|
1704
|
+
} | {
|
|
1705
|
+
type: 'ai';
|
|
1706
|
+
name: string;
|
|
1707
|
+
} | {
|
|
1708
|
+
type: 'r2_bucket';
|
|
1709
|
+
name: string;
|
|
1710
|
+
/** Either a pre-existing bucket name or the literal `"auto"`. */
|
|
1711
|
+
bucket_name: string;
|
|
1712
|
+
} | {
|
|
1713
|
+
type: 'kv_namespace';
|
|
1714
|
+
name: string;
|
|
1715
|
+
/** Either a pre-existing KV namespace ID or the literal `"auto"`. */
|
|
1716
|
+
namespace_id: string;
|
|
1717
|
+
/** Required when `namespace_id === "auto"`. Human-readable namespace title. */
|
|
1718
|
+
title?: string;
|
|
1719
|
+
} | {
|
|
1720
|
+
type: 'd1';
|
|
1721
|
+
name: string;
|
|
1722
|
+
/** Either a pre-existing D1 database UUID or the literal `"auto"`. */
|
|
1723
|
+
id: string;
|
|
1724
|
+
/** Required when `id === "auto"`. Human-readable database name. */
|
|
1725
|
+
database_name?: string;
|
|
1726
|
+
} | {
|
|
1727
|
+
type: 'queue';
|
|
1728
|
+
name: string;
|
|
1729
|
+
/** Either a pre-existing queue name or the literal `"auto"`. */
|
|
1730
|
+
queue_name: string;
|
|
1731
|
+
} | {
|
|
1732
|
+
type: 'browser_rendering';
|
|
1733
|
+
name: string;
|
|
1734
|
+
} | {
|
|
1735
|
+
type: 'analytics_engine';
|
|
1736
|
+
name: string;
|
|
1737
|
+
dataset?: string;
|
|
1738
|
+
} | {
|
|
1739
|
+
type: 'hyperdrive';
|
|
1740
|
+
name: string;
|
|
1741
|
+
id: string;
|
|
1742
|
+
};
|
|
1743
|
+
type CustomBindingManifest = CustomBinding[];
|
|
1744
|
+
/** Sentinel string in an ID field that requests platform-side provisioning. */
|
|
1745
|
+
declare const AUTO_PROVISION_SENTINEL = "auto";
|
|
1746
|
+
/** Binding types whose ID field accepts the `"auto"` sentinel for provisioning. */
|
|
1747
|
+
declare const AUTO_PROVISIONABLE_TYPES: Set<string>;
|
|
1748
|
+
/**
|
|
1749
|
+
* True if a binding has the `"auto"` sentinel in its primary ID field. Used by
|
|
1750
|
+
* the deploy-worker to decide which entries need provisioning and by the
|
|
1751
|
+
* validator to enforce companion-field requirements.
|
|
1752
|
+
*/
|
|
1753
|
+
declare function isAutoProvision(b: CustomBinding): boolean;
|
|
1754
|
+
/** Binding `type` values an app is allowed to declare. */
|
|
1755
|
+
declare const ALLOWED_BINDING_TYPES: Set<string>;
|
|
1756
|
+
/**
|
|
1757
|
+
* Binding NAMES the SDK reserves on every app — apps may not redeclare them.
|
|
1758
|
+
*
|
|
1759
|
+
* Includes:
|
|
1760
|
+
* - Static-asset + service bindings the platform sets up automatically.
|
|
1761
|
+
* - SDK-managed env (auth, identity, owner JWT, HMAC secret).
|
|
1762
|
+
* - The auto-attached cost-tracking AE dataset (`USAGE_EVENTS`).
|
|
1763
|
+
*
|
|
1764
|
+
* DO binding names (RECORD_ROOMS, YJS_ROOMS, etc.) are NOT in this set
|
|
1765
|
+
* because they live in a separate manifest (`__DO_MANIFEST__`).
|
|
1766
|
+
*/
|
|
1767
|
+
declare const RESERVED_BINDING_NAMES: Set<string>;
|
|
1768
|
+
/**
|
|
1769
|
+
* Per-binding validation error. `binding` is undefined for top-level
|
|
1770
|
+
* shape failures (e.g. manifest is not an array).
|
|
1771
|
+
*/
|
|
1772
|
+
interface ValidationError {
|
|
1773
|
+
binding?: CustomBinding;
|
|
1774
|
+
reason: string;
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Validate a binding manifest. Returns errors; an empty array means valid.
|
|
1778
|
+
*
|
|
1779
|
+
* Used both client-side (CLI) for friendly fail-fast and server-side
|
|
1780
|
+
* (deploy-worker) as a security boundary — apps can't sneak in reserved
|
|
1781
|
+
* binding names by editing the wire format.
|
|
1782
|
+
*/
|
|
1783
|
+
declare function validateBindingManifest(manifest: unknown): {
|
|
1784
|
+
valid: true;
|
|
1785
|
+
bindings: CustomBindingManifest;
|
|
1786
|
+
} | {
|
|
1787
|
+
valid: false;
|
|
1788
|
+
errors: ValidationError[];
|
|
1789
|
+
};
|
|
1790
|
+
/**
|
|
1791
|
+
* Convert vite/wrangler's normalized config (from `.wrangler/deploy/config.json`)
|
|
1792
|
+
* into a CustomBindingManifest.
|
|
1793
|
+
*
|
|
1794
|
+
* Vite normalizes wrangler.toml into object/array structures with shapes like
|
|
1795
|
+
* `{ ai: { binding: 'AI' } }`, `{ vectorize: [{ binding, index_name }] }`,
|
|
1796
|
+
* etc. We extract each known shape with explicit field plucks (no broad
|
|
1797
|
+
* `as` casts) and return a flat array.
|
|
1798
|
+
*/
|
|
1799
|
+
declare function bindingManifestFromOutputConfig(outputConfig: Record<string, unknown>): CustomBindingManifest;
|
|
1800
|
+
|
|
1801
|
+
/**
|
|
1802
|
+
* Pure helpers for computing Cloudflare Durable Object migrations from a
|
|
1803
|
+
* declared manifest + the bindings already registered on a deployed script.
|
|
1804
|
+
*
|
|
1805
|
+
* Lives in the SDK (not deploy-worker) so the logic is testable with vitest
|
|
1806
|
+
* and reusable from other CF deploy paths if we ever add them.
|
|
1807
|
+
*/
|
|
1808
|
+
|
|
1809
|
+
/** Subset of CF's `bindings` API response we read from. */
|
|
1810
|
+
interface ExistingDOBinding {
|
|
1811
|
+
/** Binding name in `env`, e.g. 'RECORD_ROOMS' */
|
|
1812
|
+
name: string;
|
|
1813
|
+
/** Always `'durable_object_namespace'` for DO bindings. */
|
|
1814
|
+
type: string;
|
|
1815
|
+
/** SDK class name, e.g. 'AppRecordRoom' */
|
|
1816
|
+
class_name?: string;
|
|
1817
|
+
}
|
|
1818
|
+
/** What goes in the CF script-upload `migrations` block. */
|
|
1819
|
+
interface DoMigrationDirective {
|
|
1820
|
+
tag: string;
|
|
1821
|
+
new_sqlite_classes?: string[];
|
|
1822
|
+
deleted_classes?: string[];
|
|
1823
|
+
}
|
|
1824
|
+
interface DoMigrationPlan {
|
|
1825
|
+
/** New SQLite classes to register (present in manifest, absent in existing). */
|
|
1826
|
+
newSqliteClasses: string[];
|
|
1827
|
+
/** Classes to delete (present in existing, absent in manifest). */
|
|
1828
|
+
deletedClasses: string[];
|
|
1829
|
+
/** True when there's actual delta — only then should the migrations block be sent. */
|
|
1830
|
+
needsMigration: boolean;
|
|
1831
|
+
/** The full directive to splat into the CF script-upload metadata. Null if no migration is needed. */
|
|
1832
|
+
directive: DoMigrationDirective | null;
|
|
1833
|
+
}
|
|
1834
|
+
interface ComputeDoMigrationOptions {
|
|
1835
|
+
/**
|
|
1836
|
+
* Override for the timestamp baked into the migration tag. Tests pass a
|
|
1837
|
+
* fixed value to assert determinism; production omits this and gets
|
|
1838
|
+
* `Date.now()`, which guarantees lifetime tag uniqueness even across
|
|
1839
|
+
* cycles like `[A]→[A,B]→[A]→[A,B]`.
|
|
1840
|
+
*/
|
|
1841
|
+
now?: number;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Compute the migration plan for a deploy.
|
|
1845
|
+
*
|
|
1846
|
+
* manifest: what the app declares now
|
|
1847
|
+
* existing: what CF currently has registered for this script
|
|
1848
|
+
*
|
|
1849
|
+
* Behavior:
|
|
1850
|
+
* - new_sqlite_classes ← in manifest, not in existing, sqlite=true
|
|
1851
|
+
* - deleted_classes ← in existing, not in manifest
|
|
1852
|
+
* - needsMigration ← either of the above is non-empty
|
|
1853
|
+
* - tag ← content-addressed by (add, remove) so:
|
|
1854
|
+
* - identical re-deploy → unchanged tag → no-op (and
|
|
1855
|
+
* `needsMigration` is false anyway)
|
|
1856
|
+
* - any class change → unique tag → CF processes
|
|
1857
|
+
*
|
|
1858
|
+
* Bug history: an earlier version computed `tag = v${count}`. Removing a class
|
|
1859
|
+
* dropped the count, the migration block was skipped (no NEW classes), and CF
|
|
1860
|
+
* retained the orphaned class registration with its SQLite storage. The
|
|
1861
|
+
* `deleted_classes` path closes that gap; the content-addressed tag prevents
|
|
1862
|
+
* tag collisions when class sets are added and removed in different orders.
|
|
1863
|
+
*/
|
|
1864
|
+
declare function computeDoMigration(manifest: readonly DOManifestEntry[], existing: readonly ExistingDOBinding[], options?: ComputeDoMigrationOptions): DoMigrationPlan;
|
|
1865
|
+
|
|
1866
|
+
/**
|
|
1867
|
+
* App-name validation + sanitization helpers.
|
|
1868
|
+
*
|
|
1869
|
+
* Strategy: validate strictly so we have a precise definition of "valid",
|
|
1870
|
+
* but DON'T reject non-conforming names — sanitize them, warn the user, and
|
|
1871
|
+
* proceed. Hard rejection would break apps whose `wrangler.toml name` was
|
|
1872
|
+
* something like `My_App` (previously deployed as `my-app` via silent
|
|
1873
|
+
* server-side sanitization). The new behavior preserves "still deploys,"
|
|
1874
|
+
* but the CLI now surfaces a warning so the user can fix the name when
|
|
1875
|
+
* convenient instead of being silently surprised by their hostname.
|
|
1876
|
+
*
|
|
1877
|
+
* Rules track Cloudflare's WfP script-name constraints (RFC 1035 host label,
|
|
1878
|
+
* no consecutive dashes) plus our 2-char minimum so subdomains read sensibly.
|
|
1879
|
+
*/
|
|
1880
|
+
declare const APP_NAME_RULES: {
|
|
1881
|
+
/** ^[a-z0-9](-?[a-z0-9])+$ — RFC 1035 host label, no consecutive dashes. */
|
|
1882
|
+
readonly pattern: RegExp;
|
|
1883
|
+
readonly minLength: 2;
|
|
1884
|
+
readonly maxLength: 63;
|
|
1885
|
+
};
|
|
1886
|
+
type AppNameValidation = {
|
|
1887
|
+
valid: true;
|
|
1888
|
+
name: string;
|
|
1889
|
+
} | {
|
|
1890
|
+
valid: false;
|
|
1891
|
+
reason: string;
|
|
1892
|
+
};
|
|
1893
|
+
/**
|
|
1894
|
+
* Strict validation: returns valid only if the name already conforms.
|
|
1895
|
+
* Useful as a precondition test or for CI lints.
|
|
1896
|
+
*/
|
|
1897
|
+
declare function validateAppName(raw: unknown): AppNameValidation;
|
|
1898
|
+
type AppNameResolution = {
|
|
1899
|
+
ok: true;
|
|
1900
|
+
name: string;
|
|
1901
|
+
warning?: string;
|
|
1902
|
+
} | {
|
|
1903
|
+
ok: false;
|
|
1904
|
+
reason: string;
|
|
1905
|
+
};
|
|
1906
|
+
/**
|
|
1907
|
+
* Resolve an app name for deploy: prefer the input as-is if valid, otherwise
|
|
1908
|
+
* sanitize and warn. Hard-fail only if even sanitization can't produce a
|
|
1909
|
+
* valid name (empty, all-non-alphanumeric, too short, too long).
|
|
1910
|
+
*
|
|
1911
|
+
* The intent is "what previously worked still works, with a friendly warning
|
|
1912
|
+
* about non-conforming names."
|
|
1913
|
+
*/
|
|
1914
|
+
declare function resolveAppName(raw: unknown): AppNameResolution;
|
|
1653
1915
|
|
|
1654
1916
|
/**
|
|
1655
1917
|
* AI Chat Schemas
|
|
@@ -2398,7 +2660,22 @@ declare function makeDefaultSummarizer(env: DeepSpaceAIEnv, options?: {
|
|
|
2398
2660
|
* The tools API returns records as `{ recordId, data, createdAt, updatedAt }`
|
|
2399
2661
|
* envelopes; helpers below flatten them into ChatRow / ChatMessageRow.
|
|
2400
2662
|
*/
|
|
2663
|
+
/**
|
|
2664
|
+
* Canonical chat row.
|
|
2665
|
+
*
|
|
2666
|
+
* `recordId` is the primary identifier — same envelope shape as every
|
|
2667
|
+
* other DeepSpace data type (records.* tools, useQuery results, etc.).
|
|
2668
|
+
*
|
|
2669
|
+
* `id` is kept as a deprecated alias so existing callers don't break,
|
|
2670
|
+
* but every new caller should prefer `recordId`. Without this rename
|
|
2671
|
+
* an integrator who reads `chat.recordId` (the obvious thing given the
|
|
2672
|
+
* rest of the SDK) silently gets `undefined`, then ships code that
|
|
2673
|
+
* sends `{"chatId": undefined}` to `/api/ai/chat` and gets back a 400
|
|
2674
|
+
* with a misleading error.
|
|
2675
|
+
*/
|
|
2401
2676
|
type ChatRow = {
|
|
2677
|
+
recordId: string;
|
|
2678
|
+
/** @deprecated Use `recordId`. Retained for backward compatibility. */
|
|
2402
2679
|
id: string;
|
|
2403
2680
|
userId: string;
|
|
2404
2681
|
title: string;
|
|
@@ -2409,6 +2686,8 @@ type ChatRow = {
|
|
|
2409
2686
|
updatedAt: string;
|
|
2410
2687
|
};
|
|
2411
2688
|
type ChatMessageRow = {
|
|
2689
|
+
recordId: string;
|
|
2690
|
+
/** @deprecated Use `recordId`. Retained for backward compatibility. */
|
|
2412
2691
|
id: string;
|
|
2413
2692
|
chatId: string;
|
|
2414
2693
|
userId: string;
|
|
@@ -2434,6 +2713,179 @@ declare function appendMessage(stub: DurableObjectStub, msg: {
|
|
|
2434
2713
|
parts?: unknown[];
|
|
2435
2714
|
}): Promise<void>;
|
|
2436
2715
|
|
|
2716
|
+
/**
|
|
2717
|
+
* Per-binding usage metering — record Vectorize / Workers AI / etc. costs
|
|
2718
|
+
* to the auto-attached `USAGE_EVENTS` Analytics Engine dataset.
|
|
2719
|
+
*
|
|
2720
|
+
* Why: the platform's tail-worker captures per-invocation compute (CPU + wall
|
|
2721
|
+
* time + script name) but it can't see which model an AI call hit, how many
|
|
2722
|
+
* tokens it embedded, or how many vectors a Vectorize query scanned. Without
|
|
2723
|
+
* those signals there's no way to surface per-tenant binding cost on the
|
|
2724
|
+
* billing dashboard.
|
|
2725
|
+
*
|
|
2726
|
+
* The deploy-worker auto-attaches a `USAGE_EVENTS` AE binding to every app
|
|
2727
|
+
* (dataset: `deepspace_binding_usage`). Apps don't need to declare it. They
|
|
2728
|
+
* just call `meterAi(...)` / `meterVectorize(...)` / `meterUsage(...)` after
|
|
2729
|
+
* each call and the dashboard rolls it up by `ownerUserId`.
|
|
2730
|
+
*
|
|
2731
|
+
* Schema written:
|
|
2732
|
+
* indexes: [ownerUserId]
|
|
2733
|
+
* blobs: [appName, kind, model_or_index, op]
|
|
2734
|
+
* doubles: [units, count]
|
|
2735
|
+
*
|
|
2736
|
+
* Use:
|
|
2737
|
+
* await meterAi(env, '@cf/qwen/qwen3-embedding-0.6b', { inputChars: 5000 })
|
|
2738
|
+
* await meterVectorize(env, 'unison-candidates', 'query', { vectors: 1000 })
|
|
2739
|
+
* await meterUsage(env, 'custom-thing', { units: 1 })
|
|
2740
|
+
*/
|
|
2741
|
+
interface MeteringEnv {
|
|
2742
|
+
USAGE_EVENTS?: AnalyticsEngineDataset;
|
|
2743
|
+
OWNER_USER_ID?: string;
|
|
2744
|
+
APP_NAME?: string;
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* Generic event recorder. Returns `false` if the binding isn't present
|
|
2748
|
+
* (dev / not yet deployed) or if AnalyticsEngine throws — metering must
|
|
2749
|
+
* never break the calling code path.
|
|
2750
|
+
*/
|
|
2751
|
+
declare function meterUsage(env: MeteringEnv, kind: string, fields?: {
|
|
2752
|
+
id?: string;
|
|
2753
|
+
op?: string;
|
|
2754
|
+
units?: number;
|
|
2755
|
+
count?: number;
|
|
2756
|
+
}): boolean;
|
|
2757
|
+
/**
|
|
2758
|
+
* Record a Workers AI call.
|
|
2759
|
+
*
|
|
2760
|
+
* Cloudflare prices input and output tokens at different rates for LLMs
|
|
2761
|
+
* (output is typically more expensive); embedding models bill input only.
|
|
2762
|
+
* Emits up to two events per call so the dashboard rollup can group by
|
|
2763
|
+
* `op` and apply the right per-token rate:
|
|
2764
|
+
*
|
|
2765
|
+
* op='input' units=inputChars
|
|
2766
|
+
* op='output' units=outputChars
|
|
2767
|
+
*
|
|
2768
|
+
* For a pure embedding call (outputChars=0), only the input event fires.
|
|
2769
|
+
* Pass `inputChars` and `outputChars` raw — the rough chars-to-token
|
|
2770
|
+
* conversion happens at price time using `COST_RATES.ai.embedPerChar`.
|
|
2771
|
+
*/
|
|
2772
|
+
declare function meterAi(env: MeteringEnv, model: string, fields?: {
|
|
2773
|
+
inputChars?: number;
|
|
2774
|
+
outputChars?: number;
|
|
2775
|
+
calls?: number;
|
|
2776
|
+
}): boolean;
|
|
2777
|
+
/**
|
|
2778
|
+
* Record a Vectorize operation.
|
|
2779
|
+
*
|
|
2780
|
+
* Cloudflare's published model (https://developers.cloudflare.com/vectorize/platform/pricing/):
|
|
2781
|
+
*
|
|
2782
|
+
* "If you have 10,000 vectors with 384-dimensions in an index, and make
|
|
2783
|
+
* 100 queries against that index, your total queried vector dimensions
|
|
2784
|
+
* would sum to 3.878 million ((10000 + 100) * 384)."
|
|
2785
|
+
*
|
|
2786
|
+
* So query billing is *additive* — `(stored + queries) * dims` summed
|
|
2787
|
+
* across the call, not per-query-multiplied-by-stored. Translating to a
|
|
2788
|
+
* per-call meter:
|
|
2789
|
+
*
|
|
2790
|
+
* op='query': units = (vectors + storedCount) * dims
|
|
2791
|
+
* Without `storedCount` we significantly undercount: a single
|
|
2792
|
+
* query against a 100K-vector index produces ~100K queried
|
|
2793
|
+
* dims, not just `dims`.
|
|
2794
|
+
* op='upsert': CF doesn't bill upserts directly; the chargeable delta is
|
|
2795
|
+
* the change to stored-vector-month. `units = vectors * dims`
|
|
2796
|
+
* approximates the per-call storage delta.
|
|
2797
|
+
* op='delete' / 'getByIds': recorded for observability; no direct cost.
|
|
2798
|
+
*
|
|
2799
|
+
* Edge case: querying an empty index gives `(1 + 0) * dims = dims`, which
|
|
2800
|
+
* matches CF's formula (the `+ queries` term is always added, even at 0
|
|
2801
|
+
* stored). If CF later changes that and an empty-index query bills 0,
|
|
2802
|
+
* adjust here — `metering` is the single place to update the math.
|
|
2803
|
+
*/
|
|
2804
|
+
declare function meterVectorize(env: MeteringEnv, indexName: string, op: 'query' | 'upsert' | 'delete' | 'getByIds', fields?: {
|
|
2805
|
+
vectors?: number;
|
|
2806
|
+
dims?: number;
|
|
2807
|
+
storedCount?: number;
|
|
2808
|
+
}): boolean;
|
|
2809
|
+
/**
|
|
2810
|
+
* Per-`units` USD multipliers, matched to the (`kind`, `op`) the meter
|
|
2811
|
+
* helpers above record. Dashboard rollup can multiply
|
|
2812
|
+
*
|
|
2813
|
+
* SUM(_sample_interval * doubles[1]) -- units
|
|
2814
|
+
*
|
|
2815
|
+
* by these to surface $-figures without re-querying CF's billing API.
|
|
2816
|
+
*/
|
|
2817
|
+
declare const COST_RATES: {
|
|
2818
|
+
readonly ai: {
|
|
2819
|
+
/** USD per character (input or output). */
|
|
2820
|
+
readonly perChar: number;
|
|
2821
|
+
};
|
|
2822
|
+
readonly vectorize: {
|
|
2823
|
+
/** USD per queried dimension (per query, per stored vector compared). */
|
|
2824
|
+
readonly queriedPerDim: number;
|
|
2825
|
+
/** USD per stored dimension per month. */
|
|
2826
|
+
readonly storedPerDimPerMonth: number;
|
|
2827
|
+
};
|
|
2828
|
+
};
|
|
2829
|
+
|
|
2830
|
+
/**
|
|
2831
|
+
* Lightweight D1 schema bootstrapping for apps that use auto-provisioned
|
|
2832
|
+
* `[[d1_databases]]` bindings.
|
|
2833
|
+
*
|
|
2834
|
+
* The auto-provisioner gives apps an empty D1; the app needs to create its
|
|
2835
|
+
* own tables before using them. This helper runs ordered SQL fragments and
|
|
2836
|
+
* tracks which have applied via a `_dpc_migrations` meta-table so re-running
|
|
2837
|
+
* is a no-op:
|
|
2838
|
+
*
|
|
2839
|
+
* ```ts
|
|
2840
|
+
* import { runMigrations } from 'deepspace/worker'
|
|
2841
|
+
*
|
|
2842
|
+
* await runMigrations(env.CARDS_DB, [
|
|
2843
|
+
* `CREATE TABLE cards (id INTEGER PRIMARY KEY, json TEXT NOT NULL);`,
|
|
2844
|
+
* `CREATE INDEX idx_cards_updated ON cards(updated_at);`,
|
|
2845
|
+
* ])
|
|
2846
|
+
* ```
|
|
2847
|
+
*
|
|
2848
|
+
* Each entry in the array is one migration. The runner records the index of
|
|
2849
|
+
* each successfully-applied migration in `_dpc_migrations`; subsequent calls
|
|
2850
|
+
* skip rows already recorded. Adding a new migration means appending to the
|
|
2851
|
+
* array; never reorder or delete entries.
|
|
2852
|
+
*
|
|
2853
|
+
* Why a meta-table instead of `PRAGMA user_version`: D1's SQLite authorizer
|
|
2854
|
+
* rejects PRAGMA writes with `SQLITE_AUTH`, even though the same statements
|
|
2855
|
+
* work in raw SQLite. A real table works on any D1 database and stays a
|
|
2856
|
+
* trivial bootstrap (one CREATE TABLE IF NOT EXISTS).
|
|
2857
|
+
*
|
|
2858
|
+
* Concurrency: D1 serializes statements per database, but two simultaneous
|
|
2859
|
+
* `runMigrations` callers could race the same migration index. The duplicate
|
|
2860
|
+
* INSERT collides on the primary key and the second caller sees the failure
|
|
2861
|
+
* — but the migration itself uses `IF NOT EXISTS` so the schema is correct
|
|
2862
|
+
* either way. Apps invoke this at startup which is single-threaded per
|
|
2863
|
+
* worker isolate; the cross-isolate race is rare and self-healing.
|
|
2864
|
+
*
|
|
2865
|
+
* This is the simplest possible migration story (option 1 in
|
|
2866
|
+
* docs/proposals/binding-auto-provisioning.md). Apps that outgrow it can
|
|
2867
|
+
* adopt CF's `wrangler d1 migrations apply` directly without breaking the
|
|
2868
|
+
* helper.
|
|
2869
|
+
*/
|
|
2870
|
+
interface RunMigrationsResult {
|
|
2871
|
+
/** Version before this run started. Equals the count of migrations already applied. */
|
|
2872
|
+
fromVersion: number;
|
|
2873
|
+
/** Version after migrations applied. Equals fromVersion if nothing ran. */
|
|
2874
|
+
toVersion: number;
|
|
2875
|
+
/** Number of migrations applied this call. */
|
|
2876
|
+
applied: number;
|
|
2877
|
+
}
|
|
2878
|
+
/**
|
|
2879
|
+
* Apply ordered SQL migrations to a D1 database. Idempotent: the next call
|
|
2880
|
+
* with the same array is a no-op until the array grows.
|
|
2881
|
+
*
|
|
2882
|
+
* Throws on any individual migration failure. The migrations meta-row is
|
|
2883
|
+
* only inserted after a migration succeeds, so a partial failure leaves a
|
|
2884
|
+
* recoverable state — fix the SQL, redeploy, and the failed migration runs
|
|
2885
|
+
* on next startup.
|
|
2886
|
+
*/
|
|
2887
|
+
declare function runMigrations(db: D1Database, migrations: readonly string[]): Promise<RunMigrationsResult>;
|
|
2888
|
+
|
|
2437
2889
|
/**
|
|
2438
2890
|
* Auth types for the DeepSpace SDK.
|
|
2439
2891
|
*
|
|
@@ -3387,4 +3839,4 @@ type DeepSpaceAuth = ReturnType<typeof createDeepSpaceAuth>;
|
|
|
3387
3839
|
/** Collections that bypass schema checks (permissive access) */
|
|
3388
3840
|
declare const SYSTEM_COLLECTIONS: Set<string>;
|
|
3389
3841
|
|
|
3390
|
-
export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GlobalDOType, type HandlerContext, type InternalSignature, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type Summarizer, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, capToolResultSize, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isOwner, loadMessages, makeDefaultSummarizer, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, readVarUint, readVarUint8Array, resolveColumn, rowToData, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
|
|
3842
|
+
export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GlobalDOType, type HandlerContext, type InternalSignature, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type Summarizer, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, capToolResultSize, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAutoProvision, isOwner, loadMessages, makeDefaultSummarizer, meterAi, meterUsage, meterVectorize, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, readVarUint, readVarUint8Array, resolveAppName, resolveColumn, rowToData, runMigrations, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
|