@lupinum/better-convex-functions 0.1.0 → 0.2.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 (56) hide show
  1. package/dist/agent/AGENTS.md +7 -3
  2. package/dist/agent/pages/docs/build/application-behavior/error-handling.md +40 -1
  3. package/dist/agent/pages/docs/build/authentication/account-deletion.md +73 -0
  4. package/dist/agent/pages/docs/build/authentication/backend-authorization.md +6 -1
  5. package/dist/agent/pages/docs/build/authentication/better-auth-setup.md +3 -1
  6. package/dist/agent/pages/docs/build/authentication/sign-in-and-sign-out.md +3 -0
  7. package/dist/agent/pages/docs/build/authentication/transactional-email.md +45 -10
  8. package/dist/agent/pages/docs/build/files/private-downloads.md +126 -0
  9. package/dist/agent/pages/docs/build/files/storage-urls.md +8 -3
  10. package/dist/agent/pages/docs/build/files/upload-files.md +2 -2
  11. package/dist/agent/pages/docs/build/functions/limits-and-audit.md +142 -4
  12. package/dist/agent/pages/docs/build/functions/testing.md +24 -0
  13. package/dist/agent/pages/docs/build/queries/loading-and-stale-data.md +1 -1
  14. package/dist/agent/pages/docs/build/queries/pagination.md +2 -2
  15. package/dist/agent/pages/docs/build/queries/reactive-arguments.md +46 -0
  16. package/dist/agent/pages/docs/build/server/server-convex.md +16 -1
  17. package/dist/agent/pages/docs/build/write-data/concurrent-operations.md +1 -1
  18. package/dist/agent/pages/docs/build/write-data/forms.md +1 -1
  19. package/dist/agent/pages/docs/build/write-data/multi-step-operations.md +1 -1
  20. package/dist/agent/pages/docs/build/write-data/optimistic-updates.md +1 -1
  21. package/dist/agent/pages/docs/get-started/add-authentication.md +13 -3
  22. package/dist/agent/pages/docs/get-started/complete-and-delete.md +2 -0
  23. package/dist/agent/pages/docs/get-started/first-realtime-page.md +3 -1
  24. package/dist/agent/pages/docs/get-started/installation.md +3 -0
  25. package/dist/agent/pages/docs/get-started/next-steps.md +30 -0
  26. package/dist/agent/pages/docs/get-started/plain-vue.md +143 -41
  27. package/dist/agent/pages/docs/operations/before-launch.md +1 -1
  28. package/dist/agent/pages/docs/operations/log-streams.md +128 -0
  29. package/dist/agent/pages/docs/recipes/dynamic-query-list.md +1 -1
  30. package/dist/agent/pages/docs/recipes/error-messages.md +1 -1
  31. package/dist/agent/pages/docs/recipes/guest-users.md +67 -15
  32. package/dist/agent/pages/docs/recipes/multiple-file-uploads.md +1 -1
  33. package/dist/agent/pages/docs/recipes/optimistic-todo-list.md +1 -1
  34. package/dist/agent/pages/docs/recipes/realtime-feed.md +1 -1
  35. package/dist/agent/pages/docs/recipes/sign-in-link.md +129 -0
  36. package/dist/agent/pages/docs/reference/api-surface.md +11 -0
  37. package/dist/agent/pages/docs/reference/error-types.md +12 -2
  38. package/dist/agent/pages/docs/reference/operation-error-codes.md +15 -1
  39. package/dist/agent/pages/docs/reference/package-exports.md +3 -2
  40. package/dist/agent/pages/docs/reference/server-api.md +5 -1
  41. package/dist/index.d.mts +2 -2
  42. package/dist/index.d.ts +2 -2
  43. package/dist/index.mjs +2 -2
  44. package/dist/internal.d.mts +3 -3
  45. package/dist/internal.d.ts +3 -3
  46. package/dist/internal.mjs +2 -2
  47. package/dist/shared/{better-convex-functions.Bdo4Aaov.d.mts → better-convex-functions.58GAkR9U.d.mts} +1 -1
  48. package/dist/shared/{better-convex-functions.BkEAj2tq.d.mts → better-convex-functions.B3cGyLjQ.d.mts} +204 -103
  49. package/dist/shared/{better-convex-functions.DVNOVULJ.mjs → better-convex-functions.BY1yTglN.mjs} +332 -131
  50. package/dist/shared/{better-convex-functions.bhHIvhtY.d.ts → better-convex-functions.BpPWw1jZ.d.ts} +1 -1
  51. package/dist/shared/{better-convex-functions.BgrHMmbW.mjs → better-convex-functions.Cnkl3RDb.mjs} +1 -1
  52. package/dist/shared/{better-convex-functions.CMT57Zsz.d.ts → better-convex-functions.Wr9dSqS9.d.ts} +204 -103
  53. package/dist/test.d.mts +1 -1
  54. package/dist/test.d.ts +1 -1
  55. package/dist/test.mjs +1 -1
  56. package/package.json +1 -1
@@ -94,13 +94,25 @@ const errorCodes = [
94
94
  "MODEL_FAILED",
95
95
  "MODEL_TIMEOUT"
96
96
  ];
97
- function fail(code, message) {
98
- throw new ConvexError({ code, message });
97
+ const codesWithoutHelp = ["NOT_FOUND", "FAILED"];
98
+ function helpOf(code, help) {
99
+ if (!help || codesWithoutHelp.includes(code)) return {};
100
+ const text = (value) => typeof value === "string" && value ? value : void 0;
101
+ const why = text(help.why);
102
+ const fix = text(help.fix);
103
+ return { ...why && { why }, ...fix && { fix } };
104
+ }
105
+ function fail(code, message, help) {
106
+ throw new ConvexError({ code, message, ...helpOf(code, help) });
99
107
  }
100
108
  function failureOf(error) {
101
109
  const data = error?.data;
102
110
  if (!data || typeof data !== "object" || !isErrorCode(data.code)) return null;
103
- return { code: data.code, message: typeof data.message === "string" ? data.message : data.code };
111
+ return {
112
+ code: data.code,
113
+ message: typeof data.message === "string" ? data.message : data.code,
114
+ ...helpOf(data.code, data)
115
+ };
104
116
  }
105
117
  const isErrorCode = (code) => errorCodes.includes(code);
106
118
 
@@ -597,6 +609,86 @@ function rateLimited(wait) {
597
609
  return fail("RATE_LIMITED", `Too many requests. Try again in ${wait} seconds.`);
598
610
  }
599
611
 
612
+ const newSeen = (trace) => ({
613
+ ...trace !== void 0 && { trace },
614
+ fields: {}
615
+ });
616
+ function traceOf(seen) {
617
+ seen.trace ??= Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join(
618
+ ""
619
+ );
620
+ return seen.trace;
621
+ }
622
+ const logOf = (seen) => ({
623
+ set: (fields) => {
624
+ for (const [key, value] of Object.entries(fields)) {
625
+ try {
626
+ const json = JSON.stringify(value);
627
+ if (json !== void 0) seen.fields[key] = JSON.parse(json);
628
+ } catch {
629
+ }
630
+ }
631
+ }
632
+ });
633
+ function sawActor(seen, actor) {
634
+ seen.actor = actor.kind === "visitor" ? { kind: "visitor" } : actorRecord(actor);
635
+ if (actor.kind === "agent" && actor.approvalId !== void 0) seen.approval = actor.approvalId;
636
+ }
637
+ function sawActing(seen, who) {
638
+ if (who.kind === "system") {
639
+ seen.actor = actorRecord(who);
640
+ return;
641
+ }
642
+ seen.actor = { kind: who.kind };
643
+ if (who.kind === "agent" && who.approvalId !== void 0) seen.approval = who.approvalId;
644
+ }
645
+ function codeOf(error) {
646
+ const data = error?.data;
647
+ const code = data && typeof data === "object" ? data.code : void 0;
648
+ return typeof code === "string" ? code : void 0;
649
+ }
650
+ function callEvent(kind, action, seen, failure) {
651
+ const settled = seen.outcome;
652
+ const code = failure ? codeOf(failure.error) : typeof settled === "object" ? settled.code : void 0;
653
+ const outcome = failure || typeof settled === "object" ? "error" : settled ?? "ok";
654
+ const rows = seen.written || seen.innerWritten ? (/* @__PURE__ */ new Set([...seen.written ?? [], ...seen.innerWritten ?? []])).size : void 0;
655
+ return {
656
+ type: "better-convex.call",
657
+ ...(seen.action ?? action) !== void 0 && { action: seen.action ?? action },
658
+ kind,
659
+ ...seen.actor && { actor: seen.actor },
660
+ ...seen.agent !== void 0 && { agent: seen.agent },
661
+ ...seen.tenant !== void 0 && { tenant: seen.tenant },
662
+ outcome,
663
+ ...code !== void 0 && { code },
664
+ // A failed call keeps none of its writes, so only a call that did its work counts them.
665
+ ...outcome === "ok" && kind !== "query" && rows !== void 0 && { written: rows },
666
+ ...seen.approval !== void 0 && { approval: seen.approval },
667
+ ...seen.trace !== void 0 && { trace: seen.trace },
668
+ ...fieldsOf(seen)
669
+ };
670
+ }
671
+ const fieldsOf = (seen) => Object.keys(seen.fields).length > 0 ? { fields: seen.fields } : {};
672
+ const handedFields = (seen) => Object.keys(seen.fields).length > 0 ? { fields: JSON.stringify(seen.fields) } : {};
673
+ function tookFields(seen, fields) {
674
+ Object.assign(seen.fields, JSON.parse(fields));
675
+ }
676
+ function logFailure(kind, action, seen, error) {
677
+ console.log(JSON.stringify(callEvent(kind, action, seen, { error })));
678
+ }
679
+ async function observed(on, kind, action, seen, run) {
680
+ if (!on) return run();
681
+ let result;
682
+ try {
683
+ result = await run();
684
+ } catch (error) {
685
+ logFailure(kind, action, seen, error);
686
+ throw error;
687
+ }
688
+ if (kind !== "query") console.log(JSON.stringify(callEvent(kind, action, seen)));
689
+ return result;
690
+ }
691
+
600
692
  const jsonOf = (validator) => validator.json;
601
693
  function idsIn(json, value) {
602
694
  if (value === void 0 || value === null) return [];
@@ -1305,9 +1397,15 @@ function guardQuery(query, check) {
1305
1397
  );
1306
1398
  }
1307
1399
 
1400
+ function forPeople(_key, value) {
1401
+ if (typeof value === "bigint") return value.toString();
1402
+ if (value instanceof ArrayBuffer) return `<${value.byteLength} bytes>`;
1403
+ return value;
1404
+ }
1308
1405
  async function planOf(op, ctx, input) {
1309
1406
  const named = () => idsIn(jsonOf(v.object(op.args)), input).filter(({ table, id }) => !table.startsWith("_") && ctx.db.normalizeId(table, id) !== null).map(({ id }) => id);
1310
- if (!op.plan) return { summary: `${op.action} ${JSON.stringify(input)}`, rows: named() };
1407
+ if (!op.plan)
1408
+ return { summary: `${op.action} ${JSON.stringify(input, forPeople)}`, rows: named() };
1311
1409
  const plan = await op.plan(planReader(ctx), frozen(input));
1312
1410
  if (!plan || typeof plan !== "object" || typeof plan.summary !== "string" || !["rows", "files"].every((key) => {
1313
1411
  const ids = plan[key];
@@ -1353,6 +1451,7 @@ function internalsOf(fns) {
1353
1451
  }
1354
1452
  function defineFunctions(config) {
1355
1453
  const { auth, policy } = config;
1454
+ const observe = config.observe === true;
1356
1455
  const rules = config.rules;
1357
1456
  const tenants = tenancy(rules);
1358
1457
  for (const [table, createdBy] of tenants.createdBy) {
@@ -1526,7 +1625,8 @@ function defineFunctions(config) {
1526
1625
  await visit(shape, input, false);
1527
1626
  return [...found.values()];
1528
1627
  }
1529
- async function authorize(ctx, op, actor, input) {
1628
+ async function authorize(ctx, op, actor, input, seen = newSeen()) {
1629
+ sawActor(seen, actor);
1530
1630
  const rows = /* @__PURE__ */ new Map();
1531
1631
  const roles = /* @__PURE__ */ new Map();
1532
1632
  const load = async (id) => {
@@ -1558,6 +1658,7 @@ function defineFunctions(config) {
1558
1658
  }
1559
1659
  }
1560
1660
  const tenant = op.crossTenant ? void 0 : deepest?.[0];
1661
+ if (tenant) seen.tenant = tenant.id;
1561
1662
  const role = open ? null : tenant ? roles.get(tenant.id) ?? null : op.crossTenant && named.length > 0 ? roles.get(named[0].id) ?? null : await roleOf(null);
1562
1663
  const asker = actor.kind === "agent" ? { kind: "agent", scopes: actor.scopes } : { kind: actor.kind };
1563
1664
  const writes = op.kind === "mutation" || op.kind === "action" || op.writes === true;
@@ -1601,6 +1702,7 @@ function defineFunctions(config) {
1601
1702
  };
1602
1703
  }
1603
1704
  const written = /* @__PURE__ */ new Set();
1705
+ if (actor.kind !== "system") seen.written = written;
1604
1706
  const db = checkedDb(ctx.db, rules, {
1605
1707
  // Custom rules see the actor as handlers do, without the approval's credentials (class 10).
1606
1708
  actor: shown(actor),
@@ -1625,7 +1727,8 @@ function defineFunctions(config) {
1625
1727
  // Operations this call runs in its own transaction add their ids to the audit row of the
1626
1728
  // outermost audited call. Under an unaudited call they write their own row.
1627
1729
  collect: audits || op.nested ? (ids) => ids.forEach((id) => written.add(id)) : void 0,
1628
- spent: paid
1730
+ spent: paid,
1731
+ seen
1629
1732
  }
1630
1733
  );
1631
1734
  const record = async () => {
@@ -1660,7 +1763,8 @@ function defineFunctions(config) {
1660
1763
  ...nested,
1661
1764
  ...files && "storage" in ctx && { storage: deleting(ctx.storage, files) },
1662
1765
  db,
1663
- actor: shown(actor)
1766
+ actor: shown(actor),
1767
+ log: logOf(seen)
1664
1768
  }
1665
1769
  };
1666
1770
  }
@@ -1672,11 +1776,14 @@ function defineFunctions(config) {
1672
1776
  const isComponent = (ref) => getFunctionAddress(ref).reference?.startsWith(
1673
1777
  "_reference/childComponent/"
1674
1778
  ) ?? false;
1675
- const wrapArgs = (ref, args, as = acting, mutation2 = false) => isComponent(ref) ? args : {
1779
+ const inner = observe && c.db !== void 0;
1780
+ const wrapArgs = (ref, args, as = acting, mutation2 = false, run = false) => isComponent(ref) ? args : {
1676
1781
  actingAs: as,
1677
1782
  input: args ?? {},
1678
1783
  ...mutation2 && collect && { nested: true },
1679
- ...chain && chain.spent.length > 0 && { spent: [...chain.spent] }
1784
+ ...chain?.spent && chain.spent.length > 0 && { spent: [...chain.spent] },
1785
+ ...run && inner && { inner: true },
1786
+ ...observe && chain?.seen && { trace: traceOf(chain.seen) }
1680
1787
  };
1681
1788
  const scheduledAs = async () => {
1682
1789
  if (acting.kind !== "agent") return acting;
@@ -1697,7 +1804,7 @@ function defineFunctions(config) {
1697
1804
  [name]: async (ref, args) => {
1698
1805
  let out;
1699
1806
  try {
1700
- out = await c[name](ref, wrapArgs(ref, args, acting, name === "runMutation"));
1807
+ out = await c[name](ref, wrapArgs(ref, args, acting, name === "runMutation", true));
1701
1808
  } catch (error) {
1702
1809
  throw notAnOperation(ref, error);
1703
1810
  } finally {
@@ -1708,8 +1815,13 @@ function defineFunctions(config) {
1708
1815
  reachedRaw();
1709
1816
  throw notAnOperation(ref, null);
1710
1817
  }
1711
- const { result, written } = out;
1712
- if (written) collect?.(written);
1818
+ const { result, written, fields } = out;
1819
+ if (written) {
1820
+ collect?.(written);
1821
+ if (chain?.seen)
1822
+ for (const id of written) (chain.seen.innerWritten ??= /* @__PURE__ */ new Set()).add(id);
1823
+ }
1824
+ if (fields && chain?.seen) tookFields(chain.seen, fields);
1713
1825
  return result;
1714
1826
  }
1715
1827
  } : {};
@@ -1786,13 +1898,17 @@ function defineFunctions(config) {
1786
1898
  args: spec.args,
1787
1899
  returns: spec.returns,
1788
1900
  handler: async (ctx, input) => {
1789
- const { ctx: checked, settle } = await authorize(
1790
- ctx,
1791
- op,
1792
- await caller(ctx, spec.action),
1793
- input
1794
- );
1795
- return settle(await spec.handler(checked, input));
1901
+ const seen = newSeen();
1902
+ return observed(observe, "query", spec.action, seen, async () => {
1903
+ const { ctx: checked, settle } = await authorize(
1904
+ ctx,
1905
+ op,
1906
+ await caller(ctx, spec.action),
1907
+ input,
1908
+ seen
1909
+ );
1910
+ return settle(await spec.handler(checked, input));
1911
+ });
1796
1912
  }
1797
1913
  });
1798
1914
  return operation(
@@ -1808,12 +1924,15 @@ function defineFunctions(config) {
1808
1924
  args: spec.args,
1809
1925
  returns: spec.returns,
1810
1926
  handler: async (ctx, input) => {
1811
- const who = await caller(ctx, spec.action);
1812
- const { ctx: checked, settle, record } = await authorize(ctx, op, who, input);
1813
- const plan = frozen(await planOf(op, checked, input));
1814
- const result = settle(await spec.handler(checked, input, plan));
1815
- await record();
1816
- return result;
1927
+ const seen = newSeen();
1928
+ return observed(observe, "mutation", spec.action, seen, async () => {
1929
+ const who = await caller(ctx, spec.action);
1930
+ const { ctx: checked, settle, record } = await authorize(ctx, op, who, input, seen);
1931
+ const plan = frozen(await planOf(op, checked, input));
1932
+ const result = settle(await spec.handler(checked, input, plan));
1933
+ await record();
1934
+ return result;
1935
+ });
1817
1936
  }
1818
1937
  });
1819
1938
  return operation(
@@ -1827,11 +1946,15 @@ function defineFunctions(config) {
1827
1946
  /** Set by `ctx.runMutation` of an operation: the caller writes the audit row and takes this call's ids. */
1828
1947
  nested: v.optional(v.boolean()),
1829
1948
  /** Set by `ctx.run*` and `ctx.scheduler`: the buckets an outer operation already took a token from. */
1830
- spent: v.optional(v.array(v.string()))
1949
+ spent: v.optional(v.array(v.string())),
1950
+ /** Set by `ctx.run*` of a query or mutation with `observe`: the caller's event covers this call. */
1951
+ inner: v.optional(v.boolean()),
1952
+ /** Set by `ctx.run*` and `ctx.scheduler` with `observe`: the trace of the call that handed this work on. */
1953
+ trace: v.optional(v.string())
1831
1954
  });
1832
- async function authorizeInternal(ctx, spec, who, input, writes = false, chain = {}) {
1955
+ async function authorizeInternal(ctx, spec, who, input, writes = false, chain = {}, seen = newSeen()) {
1833
1956
  const actor = await actingAs(ctx, who);
1834
- const authorized = await authorize(ctx, { ...spec, writes, ...chain }, actor, input);
1957
+ const authorized = await authorize(ctx, { ...spec, writes, ...chain }, actor, input, seen);
1835
1958
  if (authorized.decision === "approve" && !(actor.kind === "agent" && actor.approvalId !== void 0)) {
1836
1959
  fail("FORBIDDEN", `${spec.action} needs a person's approval. Use the tool that asks for it.`);
1837
1960
  }
@@ -1844,14 +1967,35 @@ function defineFunctions(config) {
1844
1967
  internalQueryGeneric({
1845
1968
  args: internalArgs(spec.args),
1846
1969
  ...spec.returns && {
1847
- returns: v.object({ operation: v.literal(operationMark), result: spec.returns })
1970
+ returns: v.object({
1971
+ operation: v.literal(operationMark),
1972
+ result: spec.returns,
1973
+ fields: v.optional(v.string())
1974
+ })
1848
1975
  },
1849
- handler: async (ctx, { actingAs: who, input }) => {
1850
- const { ctx: checked, settle } = await authorizeInternal(ctx, spec, who, input);
1851
- return {
1852
- operation: operationMark,
1853
- result: settle(await spec.handler(checked, input))
1854
- };
1976
+ handler: async (ctx, {
1977
+ actingAs: who,
1978
+ input,
1979
+ inner,
1980
+ trace
1981
+ }) => {
1982
+ const seen = newSeen(trace);
1983
+ return observed(observe && !inner, "query", spec.action, seen, async () => {
1984
+ const { ctx: checked, settle } = await authorizeInternal(
1985
+ ctx,
1986
+ spec,
1987
+ who,
1988
+ input,
1989
+ false,
1990
+ {},
1991
+ seen
1992
+ );
1993
+ return {
1994
+ operation: operationMark,
1995
+ result: settle(await spec.handler(checked, input)),
1996
+ ...inner && handedFields(seen)
1997
+ };
1998
+ });
1855
1999
  }
1856
2000
  })
1857
2001
  );
@@ -1865,25 +2009,33 @@ function defineFunctions(config) {
1865
2009
  returns: v.object({
1866
2010
  operation: v.literal(operationMark),
1867
2011
  result: spec.returns,
1868
- written: v.optional(v.array(v.string()))
2012
+ written: v.optional(v.array(v.string())),
2013
+ fields: v.optional(v.string())
1869
2014
  })
1870
2015
  },
1871
2016
  handler: async (ctx, {
1872
2017
  actingAs: who,
1873
2018
  input,
1874
2019
  nested,
1875
- spent
2020
+ spent,
2021
+ inner,
2022
+ trace
1876
2023
  }) => {
1877
- const {
1878
- ctx: checked,
1879
- settle,
1880
- record,
1881
- written
1882
- } = await authorizeInternal(ctx, spec, who, input, true, { nested, spent });
1883
- const result = settle(await spec.handler(checked, input));
1884
- if (nested) return { operation: operationMark, result, written: [...written] };
1885
- await record();
1886
- return { operation: operationMark, result };
2024
+ const seen = newSeen(trace);
2025
+ return observed(observe && !inner, "mutation", spec.action, seen, async () => {
2026
+ const {
2027
+ ctx: checked,
2028
+ settle,
2029
+ record,
2030
+ written
2031
+ } = await authorizeInternal(ctx, spec, who, input, true, { nested, spent }, seen);
2032
+ const result = settle(await spec.handler(checked, input));
2033
+ const handBack = inner ? { written: [...written, ...seen.innerWritten ?? []], ...handedFields(seen) } : {};
2034
+ if (nested)
2035
+ return { operation: operationMark, result, written: [...written], ...handBack };
2036
+ await record();
2037
+ return { operation: operationMark, result, ...handBack };
2038
+ });
1887
2039
  }
1888
2040
  })
1889
2041
  );
@@ -1898,38 +2050,44 @@ function defineFunctions(config) {
1898
2050
  handler: async (ctx, {
1899
2051
  actingAs: who,
1900
2052
  input,
1901
- spent
2053
+ spent,
2054
+ trace
1902
2055
  }) => {
1903
- let reached = null;
1904
- const nested = nestedCalls(
1905
- ctx,
1906
- who,
1907
- () => {
1908
- },
1909
- () => reached ??= new Error(
1910
- "This action reached a function that is not an internal operation."
1911
- ),
1912
- // The call that scheduled or ran this action paid these buckets: its saves do not pay again.
1913
- { spent: spent ?? [] }
1914
- );
1915
- const approved = who.kind === "agent" && who.approvalId !== void 0;
1916
- const result = await spec.handler(
1917
- {
1918
- ...ctx,
1919
- ...nested,
1920
- ...approved && { storage: deleting(ctx.storage, /* @__PURE__ */ new Set()) },
1921
- actor: shown(who)
1922
- },
1923
- input
1924
- );
1925
- if (reached) {
1926
- console.error(
1927
- "Raw function reached from an internal action; its writes are committed. Make it an internal operation.",
1928
- reached
2056
+ const seen = newSeen(trace);
2057
+ sawActing(seen, who);
2058
+ return observed(observe, "action", void 0, seen, async () => {
2059
+ let reached = null;
2060
+ const nested = nestedCalls(
2061
+ ctx,
2062
+ who,
2063
+ () => {
2064
+ },
2065
+ () => reached ??= new Error(
2066
+ "This action reached a function that is not an internal operation."
2067
+ ),
2068
+ // The call that scheduled or ran this action paid these buckets: its saves do not pay again.
2069
+ { spent: spent ?? [], seen }
1929
2070
  );
1930
- throw reached;
1931
- }
1932
- return { operation: operationMark, result };
2071
+ const approved = who.kind === "agent" && who.approvalId !== void 0;
2072
+ const result = await spec.handler(
2073
+ {
2074
+ ...ctx,
2075
+ ...nested,
2076
+ ...approved && { storage: deleting(ctx.storage, /* @__PURE__ */ new Set()) },
2077
+ actor: shown(who),
2078
+ log: logOf(seen)
2079
+ },
2080
+ input
2081
+ );
2082
+ if (reached) {
2083
+ console.error(
2084
+ "Raw function reached from an internal action; its writes are committed. Make it an internal operation.",
2085
+ reached
2086
+ );
2087
+ throw reached;
2088
+ }
2089
+ return { operation: operationMark, result };
2090
+ });
1933
2091
  }
1934
2092
  })
1935
2093
  );
@@ -1940,20 +2098,33 @@ function defineFunctions(config) {
1940
2098
  returns: v.object({
1941
2099
  checked: v.literal(actionCheckMark),
1942
2100
  actor: v.any(),
1943
- paid: v.array(v.string())
2101
+ paid: v.array(v.string()),
2102
+ tenant: v.optional(v.string())
1944
2103
  }),
1945
2104
  handler: async (ctx, { action: action2, shape, input }) => {
1946
2105
  assertAction({ action: action2 });
1947
- const who = await caller(ctx, action2);
1948
- const { decision, paid } = await authorize(
1949
- ctx,
1950
- { kind: "action", action: action2, shape: JSON.parse(shape) },
1951
- who,
1952
- input
1953
- );
1954
- if (decision !== "allow")
1955
- fail("FORBIDDEN", `${action2} needs a person's approval, and an action cannot wait.`);
1956
- return { checked: actionCheckMark, actor: shown(who), paid: [...paid] };
2106
+ const seen = newSeen();
2107
+ try {
2108
+ const who = await caller(ctx, action2);
2109
+ const { decision, paid } = await authorize(
2110
+ ctx,
2111
+ { kind: "action", action: action2, shape: JSON.parse(shape) },
2112
+ who,
2113
+ input,
2114
+ seen
2115
+ );
2116
+ if (decision !== "allow")
2117
+ fail("FORBIDDEN", `${action2} needs a person's approval, and an action cannot wait.`);
2118
+ return {
2119
+ checked: actionCheckMark,
2120
+ actor: shown(who),
2121
+ paid: [...paid],
2122
+ ...seen.tenant !== void 0 && { tenant: seen.tenant }
2123
+ };
2124
+ } catch (error) {
2125
+ if (observe) logFailure("action", action2, seen, error);
2126
+ throw error;
2127
+ }
1957
2128
  }
1958
2129
  })
1959
2130
  );
@@ -1997,35 +2168,43 @@ function defineFunctions(config) {
1997
2168
  throw new Error(
1998
2169
  `${checkName} is not the check of defineFunctions. Pass internal.<module>.authorizeAction to fns.action.`
1999
2170
  );
2000
- const { actor, paid } = checked;
2001
- let reached = null;
2002
- const nested = nestedCalls(
2003
- ctx,
2004
- handOver(actor),
2005
- () => {
2006
- },
2007
- () => reached ??= new Error(
2008
- "This action reached a function that is not an internal operation."
2009
- ),
2010
- // Its mutations take no second token from the bucket the check took one from.
2011
- { spent: paid }
2012
- );
2013
- const result = await spec.handler({ ...ctx, ...nested, actor }, input);
2014
- if (reached) {
2015
- console.error(
2016
- "Raw function reached from a public action; its writes are committed. Make it an internal operation.",
2017
- reached
2171
+ const { actor, paid, tenant } = checked;
2172
+ const seen = newSeen();
2173
+ sawActor(seen, actor);
2174
+ if (tenant !== void 0) seen.tenant = tenant;
2175
+ return observed(observe, "action", spec.action, seen, async () => {
2176
+ let reached = null;
2177
+ const nested = nestedCalls(
2178
+ ctx,
2179
+ handOver(actor),
2180
+ () => {
2181
+ },
2182
+ () => reached ??= new Error(
2183
+ "This action reached a function that is not an internal operation."
2184
+ ),
2185
+ // Its mutations take no second token from the bucket the check took one from.
2186
+ { spent: paid, seen }
2018
2187
  );
2019
- throw reached;
2020
- }
2021
- return result;
2188
+ const result = await spec.handler(
2189
+ { ...ctx, ...nested, actor, log: logOf(seen) },
2190
+ input
2191
+ );
2192
+ if (reached) {
2193
+ console.error(
2194
+ "Raw function reached from a public action; its writes are committed. Make it an internal operation.",
2195
+ reached
2196
+ );
2197
+ throw reached;
2198
+ }
2199
+ return result;
2200
+ });
2022
2201
  }
2023
2202
  });
2024
2203
  return guarded(registered);
2025
2204
  };
2026
2205
  }
2027
2206
  function job(spec) {
2028
- for (const reserved of ["actingAs", "input"]) {
2207
+ for (const reserved of ["actingAs", "input", "inner", "trace"]) {
2029
2208
  if (reserved in spec.args)
2030
2209
  throw new Error(`Job ${spec.name}: the argument name ${reserved} is reserved. Rename it.`);
2031
2210
  }
@@ -2040,7 +2219,9 @@ function defineFunctions(config) {
2040
2219
  ])
2041
2220
  ),
2042
2221
  actingAs: v.optional(actingAsValidator),
2043
- input: v.optional(v.object(spec.args))
2222
+ input: v.optional(v.object(spec.args)),
2223
+ inner: v.optional(v.boolean()),
2224
+ trace: v.optional(v.string())
2044
2225
  };
2045
2226
  return guarded(
2046
2227
  internalMutationGeneric({
@@ -2048,6 +2229,8 @@ function defineFunctions(config) {
2048
2229
  handler: async (ctx, {
2049
2230
  actingAs: who,
2050
2231
  input: wrapped,
2232
+ inner,
2233
+ trace,
2051
2234
  ...plain
2052
2235
  }) => {
2053
2236
  if (who !== void 0 && who.kind !== "system")
@@ -2061,25 +2244,33 @@ function defineFunctions(config) {
2061
2244
  }
2062
2245
  const input = wrapped ?? plain;
2063
2246
  const actor = { kind: "system", job: spec.name };
2064
- let tainted = null;
2065
- const nested = nestedCalls(
2066
- ctx,
2067
- actor,
2068
- () => {
2069
- },
2070
- () => tainted ??= new Error(
2071
- "This job reached a function that is not an internal operation; nothing it did is kept."
2072
- )
2073
- );
2074
- const result = await spec.handler({ ...ctx, ...nested, actor }, input);
2075
- if (tainted) throw tainted;
2076
- await lib(ctx).insert("activity", {
2077
- actor: { key: `system:${spec.name}`, kind: "system", door: "job", job: spec.name },
2078
- action: `job.${spec.name}`,
2079
- status: "done",
2080
- result: storable(result)
2247
+ const seen = newSeen(trace);
2248
+ sawActor(seen, actor);
2249
+ return observed(observe && !inner, "mutation", `job.${spec.name}`, seen, async () => {
2250
+ let tainted = null;
2251
+ const nested = nestedCalls(
2252
+ ctx,
2253
+ actor,
2254
+ () => {
2255
+ },
2256
+ () => tainted ??= new Error(
2257
+ "This job reached a function that is not an internal operation; nothing it did is kept."
2258
+ ),
2259
+ { seen }
2260
+ );
2261
+ const result = await spec.handler(
2262
+ { ...ctx, ...nested, actor, log: logOf(seen) },
2263
+ input
2264
+ );
2265
+ if (tainted) throw tainted;
2266
+ await lib(ctx).insert("activity", {
2267
+ actor: { key: `system:${spec.name}`, kind: "system", door: "job", job: spec.name },
2268
+ action: `job.${spec.name}`,
2269
+ status: "done",
2270
+ result: storable(result)
2271
+ });
2272
+ return who ? { operation: operationMark, result: null, ...inner && handedFields(seen) } : null;
2081
2273
  });
2082
- return who ? { operation: operationMark, result: null } : null;
2083
2274
  }
2084
2275
  }),
2085
2276
  "job"
@@ -2097,7 +2288,17 @@ function defineFunctions(config) {
2097
2288
  action,
2098
2289
  authorizeAction
2099
2290
  };
2100
- kits.set(fns, { auth, person, agent, authorize, lib, tenants, roleOf: config.roleOf });
2291
+ kits.set(fns, {
2292
+ auth,
2293
+ person,
2294
+ agent,
2295
+ authorize,
2296
+ lib,
2297
+ tenants,
2298
+ roleOf: config.roleOf,
2299
+ /** Runs one call of the agents package and writes its event, as the calls here do. */
2300
+ observed: (kind, action2, seen, run, inner = false) => observed(observe && !inner, kind, action2, seen, run)
2301
+ });
2101
2302
  if (config.erasure === void 0) return fns;
2102
2303
  const { eraseStep } = defineErasure(config.schema, config.erasure);
2103
2304
  erasureMaps.set(fns, config.erasure);
@@ -2125,4 +2326,4 @@ async function auditTrail(ctx, options) {
2125
2326
  const operationMark = "better-convex/operation";
2126
2327
  const actionCheckMark = "better-convex/action-check";
2127
2328
 
2128
- export { isIdOf as A, jsonOf as B, markHousekeeping as C, markTools as D, planOf as E, rateLimited as F, readOnly as G, storable as H, takeToken as I, toJsonSchema as J, toolNamePattern as K, unsendable as L, callOf as M, unguardedFunctions as N, OPERATION as O, erasureOf as P, scanModules as Q, ERASURE_STEP as R, HOUSEKEEPING as S, TOOLS as T, allOf as a, anyOf as b, auditTrail as c, custom as d, defineFunctions as e, docValidator as f, eraseUser as g, fail as h, owner as i, trusted as j, actorRecord as k, libraryTables as l, agentCallerValidator as m, callKey as n, oneLine as o, publicRead as p, checkInput as q, failureOf as r, fingerprint as s, tenant as t, unchecked as u, frozen as v, guarded as w, idsIn as x, inertMarkdown as y, internalsOf as z };
2329
+ export { internalsOf as A, isIdOf as B, jsonOf as C, markHousekeeping as D, markTools as E, newSeen as F, planOf as G, rateLimited as H, readOnly as I, sawActor as J, storable as K, takeToken as L, toJsonSchema as M, tookFields as N, OPERATION as O, toolNamePattern as P, unsendable as Q, callOf as R, unguardedFunctions as S, erasureOf as T, scanModules as U, ERASURE_STEP as V, HOUSEKEEPING as W, TOOLS as X, allOf as a, anyOf as b, auditTrail as c, custom as d, defineFunctions as e, docValidator as f, eraseUser as g, fail as h, owner as i, trusted as j, actorRecord as k, libraryTables as l, agentCallerValidator as m, callKey as n, oneLine as o, publicRead as p, checkInput as q, failureOf as r, fingerprint as s, tenant as t, unchecked as u, frozen as v, guarded as w, handedFields as x, idsIn as y, inertMarkdown as z };
@@ -1,4 +1,4 @@
1
- import './better-convex-functions.CMT57Zsz.js';
1
+ import './better-convex-functions.Wr9dSqS9.js';
2
2
  import './better-convex-functions.KGPg5Suv.js';
3
3
  import { GenericId, Value } from 'convex/values';
4
4