restricted-cel.test.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. RestrictedCelError,
  4. compileModelOptionMap,
  5. compileRestrictedCel,
  6. tokenizeRestrictedCel,
  7. } from "../src/index.js";
  8. describe("restricted CEL", () => {
  9. it("tokenizes supported literals and operators with stable offsets", () => {
  10. expect(tokenizeRestrictedCel("value >= 10 ? {'ok': true} : null").slice(0, 4)).toMatchObject([
  11. { kind: "identifier", offset: 0, value: "value" },
  12. { kind: "operator", offset: 6, value: ">=" },
  13. { kind: "number", offset: 9, value: "10" },
  14. { kind: "punctuation", offset: 12, value: "?" },
  15. ]);
  16. });
  17. it("evaluates nested objects, arrays, arithmetic and ternaries", () => {
  18. const program = compileRestrictedCel(
  19. "reasoningLevel == 'low' ? {'thinking': {'budget_tokens': 1024, 'enabled': true}, 'tags': [reasoningLevel, 2 + 3 * 4]} : {'thinking': null}",
  20. "reasoningLevel",
  21. );
  22. expect(program.evaluate("low")).toEqual({
  23. tags: ["low", 14],
  24. thinking: { budget_tokens: 1024, enabled: true },
  25. });
  26. expect(program.evaluate("off")).toEqual({ thinking: null });
  27. });
  28. it("implements CEL precedence, short circuiting and string concatenation", () => {
  29. expect(compileRestrictedCel("false && (1 / 0 > 0)", "reasoningLevel").evaluate(0)).toBe(false);
  30. expect(compileRestrictedCel("true || (1 / 0 > 0)", "reasoningLevel").evaluate(0)).toBe(true);
  31. expect(
  32. compileRestrictedCel("!(1 + 2 * 3 == 7) ? 'bad' : 'o' + 'k'", "reasoningLevel").evaluate(0),
  33. ).toBe("ok");
  34. });
  35. it("caches immutable programs without sharing execution state", () => {
  36. const first = compileRestrictedCel("{'selected': reasoningLevel}", "reasoningLevel");
  37. const second = compileRestrictedCel("{'selected': reasoningLevel}", "reasoningLevel");
  38. expect(second).toBe(first);
  39. expect(first.evaluate("first")).toEqual({ selected: "first" });
  40. expect(second.evaluate("second")).toEqual({ selected: "second" });
  41. expect(Object.isFrozen(first)).toBe(true);
  42. });
  43. it("does not reuse a program compiled for another option variable", () => {
  44. const source = "{'selected': reasoningLevel}";
  45. expect(compileModelOptionMap(source, "reasoningLevel").evaluate("high")).toEqual({
  46. selected: "high",
  47. });
  48. expect(() => compileModelOptionMap(source, "maxOutputTokens")).toThrow(
  49. 'unknown identifier "reasoningLevel"',
  50. );
  51. });
  52. it.each([
  53. ["unknown", "unknown identifier"],
  54. ["reasoningLevel.field", "member access"],
  55. ["fn(value)", "function calls"],
  56. ["reasoningLevel.map(x, x)", "member access"],
  57. ["[x for x in value]", "unknown identifier"],
  58. ["reasoningLevel trailing", "unexpected token"],
  59. ])("rejects unsupported expression %s", (source, reason) => {
  60. expect(() => compileRestrictedCel(source, "reasoningLevel")).toThrowError(RestrictedCelError);
  61. expect(() => compileRestrictedCel(source, "reasoningLevel")).toThrow(reason);
  62. });
  63. it.each(["9007199254740992", "1 / 0", "0 / 0", "1e309"])(
  64. "rejects non JSON-safe number %s",
  65. (source) => {
  66. expect(() => compileRestrictedCel(source, "reasoningLevel").evaluate(0)).toThrow(
  67. RestrictedCelError,
  68. );
  69. },
  70. );
  71. it("rejects non JSON-safe runtime input and duplicate object keys", () => {
  72. expect(() =>
  73. compileRestrictedCel("reasoningLevel", "reasoningLevel").evaluate(Number.NaN),
  74. ).toThrow("JSON-safe");
  75. expect(() =>
  76. compileRestrictedCel("reasoningLevel", "reasoningLevel").evaluate(true as never),
  77. ).toThrow("string or number");
  78. expect(() => compileRestrictedCel("{'a': 1, 'a': 2}", "reasoningLevel")).toThrow(
  79. "duplicate object key",
  80. );
  81. });
  82. it("requires model option maps to return a JSON object patch", () => {
  83. expect(
  84. compileModelOptionMap("{'max_tokens': maxOutputTokens}", "maxOutputTokens").evaluate(1024),
  85. ).toEqual({
  86. max_tokens: 1024,
  87. });
  88. expect(() => compileModelOptionMap("maxOutputTokens", "maxOutputTokens")).toThrow(
  89. "must return a JSON object",
  90. );
  91. expect(() => compileModelOptionMap("[maxOutputTokens]", "maxOutputTokens")).toThrow(
  92. "must return a JSON object",
  93. );
  94. expect(() =>
  95. compileModelOptionMap("maxOutputTokens == 1 ? {'ok': true} : null", "maxOutputTokens"),
  96. ).toThrow("must return a JSON object");
  97. expect(() =>
  98. compileModelOptionMap(
  99. "maxOutputTokens == 1 ? {'selected': maxOutputTokens} : {'fallback': true}",
  100. "maxOutputTokens",
  101. ),
  102. ).not.toThrow();
  103. expect(() => compileModelOptionMap("{'max_tokens': value}", "maxOutputTokens")).toThrow(
  104. 'unknown identifier "value"',
  105. );
  106. });
  107. it("reports a stable source offset", () => {
  108. try {
  109. compileRestrictedCel("reasoningLevel ? {'ok': true} :", "reasoningLevel");
  110. throw new Error("expected compile failure");
  111. } catch (error) {
  112. expect(error).toBeInstanceOf(RestrictedCelError);
  113. expect((error as RestrictedCelError).offset).toBe(31);
  114. expect((error as Error).message).toContain("offset 31");
  115. }
  116. });
  117. });