@midsummer-ai/sdk 0.1.0-staging.3539 → 0.1.0-staging.3545

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.
@@ -73,6 +73,13 @@ declare function enumAsObject(ts: string, line: number, column: number): string
73
73
  declare function blockNames(statements: ReadonlyArray<Any>, out: Set<string>): void;
74
74
  /** Every call of `name` where no scope around it binds `name`: the global's, which a module may not call. */
75
75
  declare function unboundCalls(tree: Any, name: string): Any[];
76
+ type EngineName = "split-cell" | "ghost-fn";
77
+ /**
78
+ * The engine Databases run on today, which `midsummer db dev`, `midsummer dev` and `midsummer db deploy` build for, so
79
+ * a function they admit runs there. When ghost-fn ships this is "ghost-fn", the one line to change. A build that
80
+ * names no engine checks against ghost-fn's, the contract's engine.
81
+ */
82
+ declare const DEPLOYED_ENGINE: EngineName;
76
83
  /**
77
84
  * The file a package's `exports` gives `sub` ("." or "./<path>"), with `*` patterns; null when it
78
85
  * gives none. Of the patterns that match, the longest part before `*` wins, then the longest key, as Node orders them.
@@ -83,13 +90,15 @@ declare function exported(exports: unknown, sub: string, conditions?: ReadonlySe
83
90
  * folder. Without `packages` an import of a package or of a file outside the folder is refused.
84
91
  *
85
92
  * A build's own `files` build again to the same files: what a deploy uploads, and what the Database
86
- * checks, is the build. Throws `Refused`.
93
+ * checks, is the build. `engine` is the engine whose rules of what a function may name it checks
94
+ * (`DEPLOYED_ENGINE` for what runs today; ghost-fn's when not given). Throws `Refused`.
87
95
  */
88
96
  declare function buildDatabase(sources: Readonly<Record<string, string>>, strip: (ts: string) => string, options?: {
89
97
  readonly packages?: Packages;
90
98
  readonly ahead?: boolean;
99
+ readonly engine?: EngineName;
91
100
  }): Built;
92
101
  /** A shape as a TypeScript type. */
93
102
  declare function typeOf(shape: Shape | null | undefined): string;
94
103
  //#endregion
95
- export { MODULE_BYTES as a, blockNames as c, exported as d, isSource as f, BuiltFunction as i, buildDatabase as l, unboundCalls as m, BUILD_FILES as n, Packages as o, typeOf as p, Built as r, Refused as s, BUILD_BYTES as t, enumAsObject as u };
104
+ export { DEPLOYED_ENGINE as a, Packages as c, buildDatabase as d, enumAsObject as f, unboundCalls as g, typeOf as h, BuiltFunction as i, Refused as l, isSource as m, BUILD_FILES as n, EngineName as o, exported as p, Built as r, MODULE_BYTES as s, BUILD_BYTES as t, blockNames as u };
@@ -1,2 +1,2 @@
1
- import { a as MODULE_BYTES, c as blockNames, d as exported, f as isSource, i as BuiltFunction, l as buildDatabase, m as unboundCalls, n as BUILD_FILES, o as Packages, p as typeOf, r as Built, s as Refused, t as BUILD_BYTES, u as enumAsObject } from "../build-BhmOZmGQ.mjs";
2
- export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
1
+ import { a as DEPLOYED_ENGINE, c as Packages, d as buildDatabase, f as enumAsObject, g as unboundCalls, h as typeOf, i as BuiltFunction, l as Refused, m as isSource, n as BUILD_FILES, o as EngineName, p as exported, r as Built, s as MODULE_BYTES, t as BUILD_BYTES, u as blockNames } from "../build-D-cwtwV_.mjs";
2
+ export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, DEPLOYED_ENGINE, EngineName, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
@@ -321,8 +321,23 @@ function scopeNames(statements, vars) {
321
321
  * module declares again. A parameter, variable, function or class of the same name in a nested
322
322
  * scope hides the import there, as it does when the code runs.
323
323
  */
324
- function importsUsed(tree) {
325
- const used = /* @__PURE__ */ new Set();
324
+ const importsUsed = (tree) => new Set(references(tree, true).keys());
325
+ /**
326
+ * The globals a module names: each reference to a name that neither its top level (its imports and
327
+ * declarations) nor a scope inside it declares, with the first node naming it.
328
+ */
329
+ function globalsNamed(tree) {
330
+ const own = scopeNames(tree.body, true);
331
+ for (const node of tree.body) if (node.type === "ImportDeclaration") for (const s of node.specifiers) own.add(s.local.name);
332
+ return new Map([...references(tree, false)].filter(([name]) => !own.has(name)));
333
+ }
334
+ /**
335
+ * Each name a module references that no scope inside it declares, with the first node naming it; `arguments` is
336
+ * declared by every function but an arrow. Without `typeOf`, a name only read by `typeof` is left out, as `typeof`
337
+ * of a name declared nowhere is "undefined".
338
+ */
339
+ function references(tree, typeOf) {
340
+ const used = /* @__PURE__ */ new Map();
326
341
  const hidden = (scopes, name) => scopes.some((scope) => scope.has(name));
327
342
  const pattern = (node, scopes) => {
328
343
  if (!node || node.type === "Identifier") return;
@@ -349,9 +364,19 @@ function importsUsed(tree) {
349
364
  function visit(node, scopes) {
350
365
  if (!node || typeof node.type !== "string") return;
351
366
  switch (node.type) {
352
- case "ImportDeclaration": return;
367
+ case "ImportDeclaration":
368
+ case "ExportAllDeclaration": return;
369
+ case "ExportNamedDeclaration":
370
+ if (!node.source) children(node, scopes);
371
+ return;
372
+ case "ExportSpecifier":
373
+ visit(node.local, scopes);
374
+ return;
375
+ case "UnaryExpression":
376
+ if (typeOf || node.operator !== "typeof" || node.argument.type !== "Identifier") visit(node.argument, scopes);
377
+ return;
353
378
  case "Identifier":
354
- if (!hidden(scopes, node.name)) used.add(node.name);
379
+ if (!hidden(scopes, node.name) && !used.has(node.name)) used.set(node.name, node);
355
380
  return;
356
381
  case "MemberExpression":
357
382
  visit(node.object, scopes);
@@ -376,7 +401,7 @@ function importsUsed(tree) {
376
401
  case "FunctionDeclaration":
377
402
  case "FunctionExpression":
378
403
  case "ArrowFunctionExpression": {
379
- const params = /* @__PURE__ */ new Set();
404
+ const params = new Set(node.type === "ArrowFunctionExpression" ? [] : ["arguments"]);
380
405
  if (node.type === "FunctionExpression" && node.id) params.add(node.id.name);
381
406
  for (const p of node.params) bindingNames(p, params);
382
407
  const head = [...scopes, params];
@@ -557,6 +582,223 @@ function unboundCalls(tree, name) {
557
582
  visit(tree, false);
558
583
  return found;
559
584
  }
585
+ const NOW = "Use ctx.now for the call's time in milliseconds (in an action, ctx.now()).";
586
+ const RANDOM = "In an action, use ctx.random(n) for n random bytes; a query or a mutation has none, so its result is the same when it runs again.";
587
+ const NETWORK = "Reach the network from an action with ctx.fetch.";
588
+ const LATER = "Schedule work with ctx.scheduler.runAfter(ms, fn, args) from a mutation or an action.";
589
+ /**
590
+ * The split cell's: the engine staging and production run today (compute deployment a0f2bc85, 2026-11-03). Its seal
591
+ * binds each of these names to undefined at the top of every function's module, queries, mutations and actions alike
592
+ * (`SHADOWED` in its `tools/seal-core.mjs`, the fabric's list), and its `Math` has no `random`. So `Date.now()` fails
593
+ * there as "Cannot read properties of undefined (reading 'now')". Every other global of its V8 runtime is there.
594
+ */
595
+ const SPLIT_CELL_SHADOWED = {
596
+ ...Object.fromEntries([
597
+ "Date",
598
+ "Temporal",
599
+ "performance"
600
+ ].map((name) => [name, NOW])),
601
+ ...Object.fromEntries([
602
+ "crypto",
603
+ "Crypto",
604
+ "SubtleCrypto",
605
+ "CryptoKey"
606
+ ].map((name) => [name, RANDOM])),
607
+ ...Object.fromEntries([
608
+ "fetch",
609
+ "Request",
610
+ "Response",
611
+ "Headers",
612
+ "WebSocket",
613
+ "WebSocketPair",
614
+ "EventSource",
615
+ "XMLHttpRequest",
616
+ "connect",
617
+ "caches",
618
+ "Cache",
619
+ "CacheStorage",
620
+ "HTMLRewriter"
621
+ ].map((name) => [name, NETWORK])),
622
+ ...Object.fromEntries([
623
+ "setTimeout",
624
+ "setInterval",
625
+ "setImmediate",
626
+ "clearTimeout",
627
+ "clearInterval",
628
+ "clearImmediate",
629
+ "queueMicrotask",
630
+ "requestAnimationFrame",
631
+ "requestIdleCallback",
632
+ "scheduler"
633
+ ].map((name) => [name, LATER])),
634
+ ...Object.fromEntries([
635
+ "globalThis",
636
+ "self",
637
+ "global",
638
+ "window",
639
+ "frames",
640
+ "parent",
641
+ "top",
642
+ "opener",
643
+ "navigator",
644
+ "location",
645
+ "origin"
646
+ ].map((name) => [name, "Name what you need directly, or import it."])),
647
+ ...Object.fromEntries([
648
+ "process",
649
+ "Buffer",
650
+ "require",
651
+ "module",
652
+ "exports",
653
+ "Deno",
654
+ "Bun"
655
+ ].map((name) => [name, "Functions get no environment values or Node globals here: pass what they need as arguments, and import packages."])),
656
+ Intl: "Format numbers and dates in the code that shows them, outside the database.",
657
+ structuredClone: "Copy a value with JSON.parse(JSON.stringify(value)), or spread it.",
658
+ ...Object.fromEntries([
659
+ "Atomics",
660
+ "SharedArrayBuffer",
661
+ "WeakRef",
662
+ "FinalizationRegistry",
663
+ "MessageChannel",
664
+ "MessagePort",
665
+ "BroadcastChannel",
666
+ "Worker",
667
+ "importScripts",
668
+ "WebAssembly",
669
+ "Function",
670
+ "Proxy"
671
+ ].map((name) => [name, "A function can't use it here."]))
672
+ };
673
+ const SPLIT_CELL = {
674
+ refuses: (name) => Object.hasOwn(SPLIT_CELL_SHADOWED, name) ? `\`${name}\` isn't available in database functions. ${SPLIT_CELL_SHADOWED[name]}` : void 0,
675
+ members: { "Math.random": `Math.random isn't available in database functions. ${RANDOM}` }
676
+ };
677
+ /**
678
+ * ghost-fn's: the rebuild engine, not deployed yet. Its compiler takes these globals (`resolve` in its `compile.rs`)
679
+ * and refuses any other at deploy, in the words below; `GHOST_FN_UNBOUND` compile and are undefined when read.
680
+ */
681
+ const GHOST_FN_GLOBALS = /* @__PURE__ */ new Set([
682
+ "Math",
683
+ "JSON",
684
+ "Object",
685
+ "Array",
686
+ "Number",
687
+ "String",
688
+ "Boolean",
689
+ "Date",
690
+ "console",
691
+ "Promise",
692
+ "Error",
693
+ "TypeError",
694
+ "RangeError",
695
+ "SyntaxError",
696
+ "ReferenceError",
697
+ "EvalError",
698
+ "URIError",
699
+ "RegExp",
700
+ "Symbol",
701
+ "Proxy",
702
+ "Reflect",
703
+ "ArrayBuffer",
704
+ "Uint8Array",
705
+ "Uint8ClampedArray",
706
+ "Int8Array",
707
+ "Uint16Array",
708
+ "Int16Array",
709
+ "Uint32Array",
710
+ "Int32Array",
711
+ "Float32Array",
712
+ "Float64Array",
713
+ "DataView",
714
+ "TextEncoder",
715
+ "TextDecoder",
716
+ "Function",
717
+ "BigInt",
718
+ "process",
719
+ "WeakMap",
720
+ "WeakSet",
721
+ "ConvexError",
722
+ "Map",
723
+ "Set",
724
+ "Infinity",
725
+ "NaN",
726
+ "undefined",
727
+ "globalThis",
728
+ "global",
729
+ "fetch",
730
+ "Response",
731
+ "Request",
732
+ "Headers",
733
+ "Blob",
734
+ "URL",
735
+ "URLSearchParams",
736
+ "encodeURIComponent",
737
+ "decodeURIComponent",
738
+ "encodeURI",
739
+ "decodeURI",
740
+ "btoa",
741
+ "atob",
742
+ "crypto",
743
+ "parseInt",
744
+ "parseFloat",
745
+ "isNaN",
746
+ "isFinite",
747
+ "escape",
748
+ "unescape",
749
+ "setTimeout",
750
+ "setInterval",
751
+ "clearTimeout",
752
+ "clearInterval",
753
+ "AbortController",
754
+ "AbortSignal",
755
+ "structuredClone"
756
+ ]);
757
+ const GHOST_FN_UNBOUND = /* @__PURE__ */ new Set([
758
+ "window",
759
+ "document",
760
+ "navigator",
761
+ "location",
762
+ "self",
763
+ "localStorage",
764
+ "sessionStorage",
765
+ "XMLHttpRequest",
766
+ "Deno",
767
+ "Bun",
768
+ "EdgeRuntime",
769
+ "WorkerGlobalScope",
770
+ "importScripts",
771
+ "File",
772
+ "FormData",
773
+ "Buffer",
774
+ "Temporal",
775
+ "addEventListener",
776
+ "removeEventListener"
777
+ ]);
778
+ /** What to use instead of a global ghost-fn refuses, said after its words. */
779
+ const GHOST_FN_INSTEAD = {
780
+ performance: "Time a call with Date.now(), or read ctx.now for the call's time.",
781
+ queueMicrotask: "Await Promise.resolve() instead.",
782
+ setImmediate: "In an action, use setTimeout; a query or a mutation never waits.",
783
+ Intl: "Format numbers and dates in the code that shows them, outside the database.",
784
+ WebSocket: NETWORK,
785
+ EventSource: NETWORK,
786
+ ReadableStream: "Read a response's body with text(), json() or arrayBuffer().",
787
+ WeakRef: "Keep the value in a Map, or read it again."
788
+ };
789
+ const ENGINES = {
790
+ "split-cell": SPLIT_CELL,
791
+ "ghost-fn": {
792
+ refuses: (name) => GHOST_FN_GLOBALS.has(name) || GHOST_FN_UNBOUND.has(name) ? void 0 : `\`${name}\` is not defined here (a global a function may not use, or a name never declared)${GHOST_FN_INSTEAD[name] ? `. ${GHOST_FN_INSTEAD[name]}` : ""}`,
793
+ members: {}
794
+ }
795
+ };
796
+ /**
797
+ * The engine Databases run on today, which `midsummer db dev`, `midsummer dev` and `midsummer db deploy` build for, so
798
+ * a function they admit runs there. When ghost-fn ships this is "ghost-fn", the one line to change. A build that
799
+ * names no engine checks against ghost-fn's, the contract's engine.
800
+ */
801
+ const DEPLOYED_ENGINE = "split-cell";
560
802
  /** Whether a module's parse has an import or export of its own. */
561
803
  const hasModuleSyntax = (tree) => tree.body.some((node) => /^(Import|ExportNamed|ExportAll|ExportDefault)Declaration$/u.test(node.type));
562
804
  /** Whether a package's .js file is CommonJS: no import or export of its own, in a package that doesn't say `"type": "module"`. */
@@ -980,7 +1222,7 @@ function commonJsModule(label, text, body, resolve) {
980
1222
  };
981
1223
  }
982
1224
  /** Parses one built module and checks every rule of admission. Throws `Refused` naming the author's file and line. */
983
- function inspect(file, path, text, built) {
1225
+ function inspect(file, path, text, built, engine) {
984
1226
  const refuse = (why, node) => {
985
1227
  throw new Refused(`${file}${node?.loc ? `:${node.loc.start.line}` : ""}: ${why}`);
986
1228
  };
@@ -996,6 +1238,18 @@ function inspect(file, path, text, built) {
996
1238
  }
997
1239
  const unbound = unboundCalls(tree, "require")[0];
998
1240
  if (unbound) refuse("require() in an ES module (the Database has none: import it)", unbound);
1241
+ if (!path.startsWith("node_modules/") && path !== SCHEMA_FILE && path !== AUTH_FILE) {
1242
+ const globals = globalsNamed(tree);
1243
+ for (const [name, node] of globals) {
1244
+ const why = name === "require" || FORBIDDEN.has(name) ? void 0 : engine.refuses(name);
1245
+ if (why) refuse(why, node);
1246
+ }
1247
+ for (const node of nodes(tree)) {
1248
+ if (node.type !== "MemberExpression" || node.computed || node.object.type !== "Identifier" || node.property.type !== "Identifier") continue;
1249
+ const why = engine.members[`${node.object.name}.${node.property.name}`];
1250
+ if (why && globals.has(node.object.name)) refuse(why, node);
1251
+ }
1252
+ }
999
1253
  for (const node of nodes(tree)) {
1000
1254
  if (node.type === "ImportExpression") refuse("a dynamic import() (a function loads nothing at runtime)", node);
1001
1255
  if (node.type === "MetaProperty" && node.meta.name === "import") refuse("import.meta", node);
@@ -1346,7 +1600,8 @@ function authConfigFrom(file, tree) {
1346
1600
  * folder. Without `packages` an import of a package or of a file outside the folder is refused.
1347
1601
  *
1348
1602
  * A build's own `files` build again to the same files: what a deploy uploads, and what the Database
1349
- * checks, is the build. Throws `Refused`.
1603
+ * checks, is the build. `engine` is the engine whose rules of what a function may name it checks
1604
+ * (`DEPLOYED_ENGINE` for what runs today; ghost-fn's when not given). Throws `Refused`.
1350
1605
  */
1351
1606
  function buildDatabase(sources, strip, options = {}) {
1352
1607
  const { files, from, inputs } = linkAll(stripSources(sources, strip), options.packages, strip);
@@ -1356,7 +1611,7 @@ function buildDatabase(sources, strip, options = {}) {
1356
1611
  let cronTree = null;
1357
1612
  for (const file of Object.keys(files)) {
1358
1613
  const author = from[file];
1359
- const tree = inspect(author, file, files[file], files);
1614
+ const tree = inspect(author, file, files[file], files, ENGINES[options.engine ?? "ghost-fn"]);
1360
1615
  if (file.startsWith("node_modules/") && !file.startsWith(`${PROJECT}/`)) continue;
1361
1616
  const unsafe = authTests(tree)[0];
1362
1617
  if (unsafe) throw new Refused(`${author}${unsafe.loc ? `:${unsafe.loc.start.line}` : ""}: \`${files[file].slice(unsafe.start, unsafe.end)}\` checks nobody: \`ctx.auth\` is there for every caller, signed in or not. Check the caller instead: \`const user = await ctx.auth.getUserIdentity()\`, then \`if (!user)\`.`);
@@ -1695,15 +1950,17 @@ export type DatabaseWriter = Tables<"write">;
1695
1950
 
1696
1951
  type SearchIndexes<T extends TableNames> = DataModel[T]["searchIndexes"];
1697
1952
  type VectorIndexes<T extends TableNames> = DataModel[T]["vectorIndexes"];
1953
+ /** An index's \`searchField\` or \`filterFields\`, read without indexing a type the checker can't see holds the key. */
1954
+ type IndexPart<D, K extends string> = D extends { readonly [P in K]: infer V } ? V : never;
1698
1955
  /** A filter field's value: a top-level field's type, or any value for a path into an object. */
1699
1956
  type FieldValue<T extends TableNames, F> = F extends keyof Doc<T> ? Doc<T>[F] : unknown;
1700
1957
  export interface SearchFilter<T extends TableNames, I extends keyof SearchIndexes<T>> {
1701
1958
  /** The words to find in the index's search field; the last also matches the words it begins. */
1702
- search(field: SearchIndexes<T>[I]["searchField"], text: string): SearchFilterEq<T, I>;
1959
+ search(field: IndexPart<SearchIndexes<T>[I], "searchField">, text: string): SearchFilterEq<T, I>;
1703
1960
  }
1704
1961
  export interface SearchFilterEq<T extends TableNames, I extends keyof SearchIndexes<T>> {
1705
1962
  /** Only rows whose filter field holds \`value\` (\`undefined\`: rows without it); every one holds; up to 8. */
1706
- eq<F extends SearchIndexes<T>[I]["filterFields"]>(field: F, value: FieldValue<T, F>): SearchFilterEq<T, I>;
1963
+ eq<F extends IndexPart<SearchIndexes<T>[I], "filterFields">>(field: F, value: FieldValue<T, F>): SearchFilterEq<T, I>;
1707
1964
  }
1708
1965
  /** A value, a document's field, or what Convex's filter builder makes of them. */
1709
1966
  export interface FilterExpression<T> { readonly __filter?: T }
@@ -1744,7 +2001,7 @@ export interface QueryStart<T extends TableNames> {
1744
2001
  export interface VectorFilterExpression { readonly __vectorFilter?: true }
1745
2002
  export interface VectorFilterBuilder<T extends TableNames, I extends keyof VectorIndexes<T>> {
1746
2003
  /** Rows whose filter field holds \`value\` (\`undefined\`: rows without it). */
1747
- eq<F extends VectorIndexes<T>[I]["filterFields"]>(field: F, value: FieldValue<T, F>): VectorFilterExpression;
2004
+ eq<F extends IndexPart<VectorIndexes<T>[I], "filterFields">>(field: F, value: FieldValue<T, F>): VectorFilterExpression;
1748
2005
  /** Rows matching any of them, up to 64 in all; none: no row. */
1749
2006
  or(...any: VectorFilterExpression[]): VectorFilterExpression;
1750
2007
  }
@@ -1896,4 +2153,4 @@ export declare function defineTable<F extends Fields>(fields: F): TableDefinitio
1896
2153
  export declare function defineSchema<T extends Record<string, TableDefinition<any>>>(tables: T): { tables: T };
1897
2154
  `;
1898
2155
  //#endregion
1899
- export { BUILD_BYTES, BUILD_FILES, MODULE_BYTES, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
2156
+ export { BUILD_BYTES, BUILD_FILES, DEPLOYED_ENGINE, MODULE_BYTES, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
@@ -1,7 +1,7 @@
1
1
  import { p as Storage } from "../index-CXiY5knc.mjs";
2
2
  import { t as AuthConfig } from "../auth-B7rCtXFQ.mjs";
3
3
  import { a as FileMetadata, c as FunctionReference, d as HttpRouter, n as CronJob, s as FunctionKind, v as RegisteredFunction, y as Row } from "../server-B5HK2Ou9.mjs";
4
- import { r as Built } from "../build-BhmOZmGQ.mjs";
4
+ import { r as Built } from "../build-D-cwtwV_.mjs";
5
5
  import { t as DatabaseError } from "../errors-x2vXKi0u.mjs";
6
6
  import { A as VectorControl, M as VectorEngine } from "../index-B9zs0wIp.mjs";
7
7
  //#region src/database/stand-in.d.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.3539",
3
+ "version": "0.1.0-staging.3545",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",