@niscorp/vex 0.3.0 → 0.3.1

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 (40) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DESIGN.md +26 -11
  3. package/DOCS.md +39 -9
  4. package/dist/adapters/express/index.cjs +6 -24
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +2 -2
  7. package/dist/adapters/express/index.d.ts +2 -2
  8. package/dist/adapters/express/index.js +2 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +6 -24
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +2 -2
  13. package/dist/adapters/hono/index.d.ts +2 -2
  14. package/dist/adapters/hono/index.js +2 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/adapters/pglite/index.cjs.map +1 -1
  17. package/dist/adapters/pglite/index.js.map +1 -1
  18. package/dist/agent/index.cjs +5 -11
  19. package/dist/agent/index.cjs.map +1 -1
  20. package/dist/agent/index.d.cts +1 -1
  21. package/dist/agent/index.d.ts +1 -1
  22. package/dist/agent/index.js +3 -6
  23. package/dist/agent/index.js.map +1 -1
  24. package/dist/{chunk-IQM4SQE2.js → chunk-3HORTMZ7.js} +6 -21
  25. package/dist/chunk-3HORTMZ7.js.map +1 -0
  26. package/dist/{chunk-H4BHW76Q.js → chunk-J7JYKCUA.js} +5 -8
  27. package/dist/chunk-J7JYKCUA.js.map +1 -0
  28. package/dist/{handler-CMrjTXNx.d.cts → handler-B4NAi4k_.d.cts} +1 -1
  29. package/dist/{handler-BGCL6_Si.d.ts → handler-BRVhWuNk.d.ts} +1 -1
  30. package/dist/index.cjs +23 -79
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +14 -62
  33. package/dist/index.d.ts +14 -62
  34. package/dist/index.js +21 -59
  35. package/dist/index.js.map +1 -1
  36. package/dist/{types-Bi-Lg86b.d.cts → types-DUJp5B3o.d.cts} +9 -124
  37. package/dist/{types-Bi-Lg86b.d.ts → types-DUJp5B3o.d.ts} +9 -124
  38. package/package.json +7 -7
  39. package/dist/chunk-H4BHW76Q.js.map +0 -1
  40. package/dist/chunk-IQM4SQE2.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -14,11 +14,6 @@ var ContextSchema = zod.z.object({
14
14
  'Caller runtime values. Keys referenced from the DSL via { $context: "key" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` ("asc"|"desc") are reserved keys that drive ORDER BY directly and are never bound as parameters.'
15
15
  );
16
16
  var QueryRequestSchema = zod.z.object({
17
- // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in
18
- // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are
19
- // mutable named slots: the name is yours, its content follows your request.
20
- // Alone → replay-or-error. With intent/shape → hit when the stored request
21
- // matches, regenerate-and-replace when it differs (409 when protected).
22
17
  fingerprint: zod.z.string().min(1).optional(),
23
18
  intent: zod.z.string().optional(),
24
19
  shape: zod.z.unknown().optional(),
@@ -94,12 +89,9 @@ var FilterSchema = zod.z.lazy(
94
89
  zod.z.object({
95
90
  optional: zod.z.object({
96
91
  key: zod.z.union([zod.z.string().min(1), zod.z.array(zod.z.string().min(1)).min(1)]).describe("The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both \u2014 gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply."),
97
- // BARE, never `.describe()`d. That call CLONES the schema, and zod
98
- // detects a recursive reference by instance identity — a clone is a
99
- // different instance, so `to-json-schema` stops seeing the cycle and
100
- // expands the filter union into itself until the stack goes. Every
101
- // other recursive slot here (`not`, `and`, `or`) uses it bare for the
102
- // same reason; the description belongs on the wrapper below.
92
+ // Bare, never `.describe()`d: that call clones the schema, and zod's
93
+ // to-json-schema detects recursion by instance identity, so a clone
94
+ // expands the filter union into itself until the stack overflows.
103
95
  then: FilterSchema
104
96
  }).strict()
105
97
  }).strict().describe(
@@ -1507,13 +1499,9 @@ var computeSchemaFingerprint = (schema) => {
1507
1499
  primaryKey: f.primaryKey,
1508
1500
  ...f.vectorDimensions !== void 0 ? { vectorDimensions: f.vectorDimensions } : {}
1509
1501
  })),
1510
- // Column order within a relation is the key's own order, so it is
1511
- // preserved; relations are sorted by target and columns. This shape
1512
- // changed when keys became composite, so every entry cached before
1513
- // revalidates once on the next boot — the drift eviction, by design.
1502
+ // Column order within a relation is the key's own order, so it is not sorted.
1514
1503
  relations: [...e.relations].sort((a, b) => `${a.entity}.${a.localFields.join(",")}`.localeCompare(`${b.entity}.${b.localFields.join(",")}`)).map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),
1515
- // Index field order is significant (composite indexes) and stable
1516
- // from introspection, so it is preserved; indexes are sorted by name.
1504
+ // Index field order is significant (composite indexes) and stable from introspection.
1517
1505
  indexes: [...e.indexes].sort(byName).map((i) => ({
1518
1506
  name: i.name,
1519
1507
  fields: i.fields,
@@ -2538,8 +2526,7 @@ var compileFilter = (filter, ctx) => {
2538
2526
  const inner = {
2539
2527
  ...ctx,
2540
2528
  resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,
2541
- // The inner map LAYERS OVER the outer one, so an inner path resolves to
2542
- // the inner alias and an outer path — the correlation — still resolves.
2529
+ // Inner over outer: an outer path, the correlation, still resolves.
2543
2530
  aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap])
2544
2531
  };
2545
2532
  const parts = ["SELECT 1"];
@@ -2726,7 +2713,14 @@ var compileAggregate = (expr, ctx) => {
2726
2713
  // src/adapters/postgres/compile.ts
2727
2714
  var compileQuery = (resolved) => {
2728
2715
  const paramSlots = [];
2729
- const paramCounter = { value: 0 };
2716
+ const sql = compileLevel(resolved, paramSlots, { value: 0 });
2717
+ const contextContract = {};
2718
+ for (const slot of paramSlots) {
2719
+ contextContract[slot.key] = { type: slot.type, kind: slot.kind };
2720
+ }
2721
+ return { sql, paramSlots, contextContract };
2722
+ };
2723
+ var compileLevel = (resolved, paramSlots, paramCounter) => {
2730
2724
  const ctx = {
2731
2725
  resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
2732
2726
  aliasMap: resolved.aliasMap,
@@ -2750,15 +2744,7 @@ var compileQuery = (resolved) => {
2750
2744
  const expr = compileAggregate(a.expression, ctx);
2751
2745
  return `${expr} AS ${quoteIdent(a.name)}`;
2752
2746
  });
2753
- const semanticColumns = [];
2754
- if (resolved.semantic !== void 0) {
2755
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
2756
- const semanticParamIndex = findSemanticParamIndex(paramSlots);
2757
- if (semanticParamIndex !== void 0) {
2758
- semanticColumns.push(`1 - (${col} <=> $${semanticParamIndex}) AS "$score"`);
2759
- }
2760
- }
2761
- const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns, ...semanticColumns];
2747
+ const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns];
2762
2748
  if (selectParts.length > 0) {
2763
2749
  sqlParts.push(`SELECT ${selectParts.join(" ")} ${allColumns.join(", ")}`);
2764
2750
  } else {
@@ -2767,9 +2753,7 @@ var compileQuery = (resolved) => {
2767
2753
  const firstSource = resolved.sources[0];
2768
2754
  if (firstSource !== void 0) {
2769
2755
  if (firstSource.subquery !== void 0) {
2770
- const subSql = compileQuery(firstSource.subquery);
2771
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2772
- sqlParts.push(`FROM (${subSql.sql}) AS ${firstSource.alias}`);
2756
+ sqlParts.push(`FROM (${compileLevel(firstSource.subquery, paramSlots, paramCounter)}) AS ${firstSource.alias}`);
2773
2757
  } else if (firstSource.table !== void 0) {
2774
2758
  sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
2775
2759
  }
@@ -2784,9 +2768,7 @@ var compileQuery = (resolved) => {
2784
2768
  ];
2785
2769
  const on = conditions.join(" AND ");
2786
2770
  if (joinSource.subquery !== void 0) {
2787
- const subSql = compileQuery(joinSource.subquery);
2788
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2789
- sqlParts.push(`${keyword} (${subSql.sql}) AS ${join.toAlias} ON ${on}`);
2771
+ sqlParts.push(`${keyword} (${compileLevel(joinSource.subquery, paramSlots, paramCounter)}) AS ${join.toAlias} ON ${on}`);
2790
2772
  } else {
2791
2773
  sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
2792
2774
  }
@@ -2796,9 +2778,7 @@ var compileQuery = (resolved) => {
2796
2778
  for (const source of resolved.sources) {
2797
2779
  if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
2798
2780
  if (source.subquery !== void 0) {
2799
- const subSql = compileQuery(source.subquery);
2800
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2801
- sqlParts.push(`CROSS JOIN (${subSql.sql}) AS ${source.alias}`);
2781
+ sqlParts.push(`CROSS JOIN (${compileLevel(source.subquery, paramSlots, paramCounter)}) AS ${source.alias}`);
2802
2782
  } else if (source.table !== void 0) {
2803
2783
  sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
2804
2784
  }
@@ -2820,11 +2800,9 @@ var compileQuery = (resolved) => {
2820
2800
  });
2821
2801
  sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
2822
2802
  } else if (resolved.semantic !== void 0) {
2823
- const semanticIdx = findSemanticParamIndex(paramSlots);
2824
- if (semanticIdx !== void 0) {
2825
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
2826
- sqlParts.push(`ORDER BY ${col} <=> $${semanticIdx} ASC`);
2827
- }
2803
+ const { field, contextPath } = resolved.semantic;
2804
+ const position = paramSlots.findIndex((slot) => slot.kind === "semantic" && slot.key === contextPath) + 1;
2805
+ if (position > 0) sqlParts.push(`ORDER BY ${field.alias}.${field.column} <=> $${position} ASC`);
2828
2806
  }
2829
2807
  if (resolved.limit !== void 0) {
2830
2808
  if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
@@ -2832,30 +2810,7 @@ var compileQuery = (resolved) => {
2832
2810
  }
2833
2811
  sqlParts.push(`LIMIT ${resolved.limit}`);
2834
2812
  }
2835
- const contextContract = {};
2836
- for (const slot of paramSlots) {
2837
- contextContract[slot.key] = { type: slot.type, kind: slot.kind };
2838
- }
2839
- return {
2840
- sql: sqlParts.join(" "),
2841
- paramSlots,
2842
- contextContract
2843
- };
2844
- };
2845
- var findSemanticParamIndex = (slots) => {
2846
- for (let i = 0; i < slots.length; i++) {
2847
- const slot = slots[i];
2848
- if (slot !== void 0 && slot.kind === "semantic") {
2849
- return i + 1;
2850
- }
2851
- }
2852
- return void 0;
2853
- };
2854
- var mergeSubqueryParams = (subCompiled, parentSlots, parentCounter) => {
2855
- for (const slot of subCompiled.paramSlots) {
2856
- parentCounter.value += 1;
2857
- parentSlots.push(slot);
2858
- }
2813
+ return sqlParts.join(" ");
2859
2814
  };
2860
2815
 
2861
2816
  // src/adapters/postgres/statement-timeout.ts
@@ -2905,7 +2860,7 @@ var createPostgresAdapter = (config) => {
2905
2860
  const capabilities = {
2906
2861
  vectorSearch: true,
2907
2862
  fuzzyMatch: false,
2908
- // Requires pg_trgm extension, not guaranteed
2863
+ // needs the pg_trgm extension, which may not be installed
2909
2864
  jsonFields: true,
2910
2865
  fullTextSearch: true,
2911
2866
  returningClause: true,
@@ -3013,9 +2968,7 @@ var UpsertSchema = zod.z.object({
3013
2968
  op: zod.z.literal("upsert"),
3014
2969
  table: zod.z.string(),
3015
2970
  columns: Columns,
3016
- // set on BOTH branches (update SET, and part of the insert)
3017
2971
  insert: Columns.optional(),
3018
- // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)
3019
2972
  key: zod.z.string()
3020
2973
  }).strict().describe('Sugar: insert-or-update by `key` (e.g. "id"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');
3021
2974
  var MutationSchema = zod.z.discriminatedUnion("op", [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);
@@ -3095,13 +3048,7 @@ var rowToEntry = (row) => {
3095
3048
  kind: "ok",
3096
3049
  dsl: row["dsl"],
3097
3050
  ...row["prism_ir"] != null ? { prismIr: row["prism_ir"] } : {},
3098
- // A DECLARED REACH IS PART OF THE ENTRY, so it has to survive the round
3099
- // trip. Dropping it here would not fail loudly — the read would simply be
3100
- // served at the caller's own, wider reach, which is the exact thing the
3101
- // field exists to prevent.
3102
3051
  ...row["reach"] != null ? { reach: row["reach"] } : {},
3103
- // So must the refresh mode: dropped, a reactive read would quietly answer
3104
- // once and never again.
3105
3052
  ...isRefresh(row["refresh"]) ? { refresh: row["refresh"] } : {},
3106
3053
  ...meta
3107
3054
  };
@@ -4010,7 +3957,6 @@ var listFingerprints = async (engine, policy) => {
4010
3957
  ...entry.intent !== void 0 ? { intent: entry.intent } : {},
4011
3958
  createdAt: entry.createdAt,
4012
3959
  ...entry.lastUsedAt !== void 0 ? { lastUsedAt: entry.lastUsedAt } : {},
4013
- // The derived contract — what to pass, straight from the stored def.
4014
3960
  ...entry.kind === "ok" ? {
4015
3961
  context: collectQueryContext(entry.dsl, schema),
4016
3962
  ...entry.shape !== void 0 ? { shape: entry.shape } : {}
@@ -4086,8 +4032,6 @@ var handleQuery = async (config, body, scope, live) => {
4086
4032
  const result = await runQuery(config, body, scope, probe, live);
4087
4033
  const record = {
4088
4034
  kind: probe.kind,
4089
- // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a
4090
- // fault); everything else is an error.
4091
4035
  status: result.status === 200 ? "ok" : result.status === 403 ? "refused" : "error",
4092
4036
  startUnixNano,
4093
4037
  endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,