@composable-os/cli 0.0.0-stage → 0.1.0-beta.8
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/LICENSE +109 -0
- package/README.md +24 -2
- package/dist/blocks-DEELKGDC.js +233 -0
- package/dist/chunk-2ABSVMGB.js +13 -0
- package/dist/chunk-2S7375SC.js +802 -0
- package/dist/chunk-5KSXSK7Y.js +47 -0
- package/dist/chunk-6UWRT4VM.js +220 -0
- package/dist/chunk-E5JLTLRM.js +50 -0
- package/dist/chunk-G3ORKXVP.js +1178 -0
- package/dist/chunk-HDIOVFAZ.js +544 -0
- package/dist/chunk-KGHA67HG.js +765 -0
- package/dist/chunk-KOKYDJ7Z.js +1423 -0
- package/dist/chunk-KTXGEXTY.js +358 -0
- package/dist/chunk-LTQDLCP7.js +16486 -0
- package/dist/chunk-MAXLUQKB.js +1287 -0
- package/dist/chunk-STJZJIRA.js +11378 -0
- package/dist/chunk-X6I2LWB3.js +24319 -0
- package/dist/chunk-XDDBLYKW.js +29154 -0
- package/dist/chunk-ZRWF6QZS.js +2357 -0
- package/dist/cli-BRSACHSG.js +31393 -0
- package/dist/cli-DTMGNDXN.js +121 -0
- package/dist/cli.js +25 -0
- package/dist/client-repo-ZVZ6KW5S.js +55 -0
- package/dist/create.js +25 -0
- package/dist/fields-64BQJA62.js +48 -0
- package/dist/invoke-NHHOLLF6.js +26 -0
- package/dist/person-WMWRF2HV.js +58 -0
- package/dist/platform/migrations/0001_init.sql +59 -0
- package/dist/platform/migrations/0002_users_settings.sql +34 -0
- package/dist/platform/migrations/0003_people_organisations.sql +225 -0
- package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
- package/dist/platform/migrations/0005_views_audit.sql +79 -0
- package/dist/platform/migrations/0006_search.sql +223 -0
- package/dist/platform/migrations/0007_crm_views.sql +141 -0
- package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
- package/dist/platform/migrations/0010_approval_queue.sql +90 -0
- package/dist/platform/migrations/0011_connected_apps.sql +36 -0
- package/dist/platform/migrations/0020_extensions.sql +373 -0
- package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
- package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
- package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
- package/dist/platform/migrations/0061_audit_retention.sql +95 -0
- package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
- package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
- package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
- package/dist/platform/migrations/0065_storage_stats.sql +13 -0
- package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
- package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
- package/dist/platform/migrations/0100_stage_history.sql +54 -0
- package/dist/platform/migrations/0110_integrations.sql +103 -0
- package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
- package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
- package/dist/platform/migrations/0130_automations.sql +113 -0
- package/dist/platform/migrations/0131_notifications.sql +29 -0
- package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
- package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
- package/dist/platform/migrations/0160_releases.sql +41 -0
- package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
- package/dist/platform/migrations/0170_automation_connections.sql +32 -0
- package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
- package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
- package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
- package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
- package/dist/platform/migrations/0210_daily_digest.sql +33 -0
- package/dist/platform/migrations/0220_entitlements.sql +13 -0
- package/dist/platform/migrations/0221_support_grants.sql +33 -0
- package/dist/platform/migrations/0250_judge.sql +11 -0
- package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
- package/dist/platform/migrations/0252_judge_usage.sql +14 -0
- package/dist/platform/migrations/0255_summary_checks.sql +9 -0
- package/dist/platform/migrations/0256_outbound_check.sql +9 -0
- package/dist/platform/migrations/0260_ai_usage.sql +20 -0
- package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
- package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
- package/dist/platform/migrations/0320_duplicates.sql +41 -0
- package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
- package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
- package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
- package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
- package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
- package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
- package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
- package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
- package/dist/platform/migrations/0362_voice_usage.sql +17 -0
- package/dist/platform/migrations/0365_routines.sql +38 -0
- package/dist/platform/migrations/0370_approval_execution.sql +20 -0
- package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
- package/dist/platform/migrations/0380_rec_views.sql +94 -0
- package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
- package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
- package/dist/platform/migrations/0402_erase_requests.sql +34 -0
- package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
- package/dist/platform/migrations/0411_device_sessions.sql +33 -0
- package/dist/platform/migrations/0420_transition_history.sql +100 -0
- package/dist/platform/migrations/0421_orders.sql +134 -0
- package/dist/platform/migrations/0422_order_payments.sql +109 -0
- package/dist/platform/migrations/0440_capacity.sql +100 -0
- package/dist/platform/migrations/0441_capacity_views.sql +40 -0
- package/dist/platform/migrations/0450_order_grants.sql +21 -0
- package/dist/platform/migrations/0451_pack_roles.sql +18 -0
- package/dist/platform/migrations/0460_content.sql +59 -0
- package/dist/platform/migrations/0461_media.sql +52 -0
- package/dist/platform/migrations/0470_publish_versions.sql +36 -0
- package/dist/platform/migrations/0471_permission_grants.sql +18 -0
- package/dist/platform/migrations/0490_staff_invites.sql +40 -0
- package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
- package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
- package/dist/platform/migrations/0500_published_media_field.sql +25 -0
- package/dist/platform/migrations/0501_import_keys.sql +23 -0
- package/dist/platform/migrations/0520_publish_requests.sql +20 -0
- package/dist/platform/sdk/automation-check.ts +534 -0
- package/dist/platform/sdk/automation.ts +743 -0
- package/dist/platform/sdk/behaviour.ts +215 -0
- package/dist/platform/sdk/capacity.ts +112 -0
- package/dist/platform/sdk/contract.ts +766 -0
- package/dist/platform/sdk/document.ts +788 -0
- package/dist/platform/sdk/field-types.ts +106 -0
- package/dist/platform/sdk/formula/ast.ts +72 -0
- package/dist/platform/sdk/formula/compile.ts +454 -0
- package/dist/platform/sdk/formula/index.ts +4 -0
- package/dist/platform/sdk/formula/parser.ts +417 -0
- package/dist/platform/sdk/index.ts +33 -0
- package/dist/platform/sdk/manifest.ts +1484 -0
- package/dist/platform/sdk/media.ts +46 -0
- package/dist/platform/sdk/permissions.ts +60 -0
- package/dist/platform/sdk/renamed.ts +63 -0
- package/dist/platform/sdk/rich-text-fixture.ts +68 -0
- package/dist/platform/sdk/rich-text.ts +173 -0
- package/dist/platform/sdk/runtime.ts +410 -0
- package/dist/platform/sdk/sellable.ts +396 -0
- package/dist/platform/sdk/slug.ts +25 -0
- package/dist/platform/sdk/states.ts +162 -0
- package/dist/platform/sdk/testing.ts +836 -0
- package/dist/products-2H5DR232.js +11 -0
- package/dist/run-4JNFLYXV.js +847 -0
- package/dist/src-G6OF5SKW.js +31 -0
- package/dist/src-J27WXNLY.js +270 -0
- package/dist/token-MOJUA2U6.js +70 -0
- package/dist/token-util-TENRN4V7.js +6 -0
- package/package.json +33 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The extension field types (ADR 0023) and the facts about them both the SDK and the host need:
|
|
2
|
+
// the formula type a field reads as, and which type changes are lossless. Storage, validation,
|
|
3
|
+
// filter operators, CSV mapping and widgets live in the host's field-type registry
|
|
4
|
+
// (`@composable-os/core`, fields/field-types.ts), keyed by these names.
|
|
5
|
+
import type { FormulaType } from "./formula/ast.ts";
|
|
6
|
+
|
|
7
|
+
export const FIELD_TYPES = [
|
|
8
|
+
"text",
|
|
9
|
+
"longText",
|
|
10
|
+
"number",
|
|
11
|
+
"currency",
|
|
12
|
+
"percent",
|
|
13
|
+
"date",
|
|
14
|
+
"datetime",
|
|
15
|
+
"boolean",
|
|
16
|
+
"select",
|
|
17
|
+
"multiSelect",
|
|
18
|
+
"relation",
|
|
19
|
+
"user",
|
|
20
|
+
"email",
|
|
21
|
+
"phone",
|
|
22
|
+
"url",
|
|
23
|
+
"formula",
|
|
24
|
+
// A JSON document checked against a schema the field declares (stage 41, ADR 0445).
|
|
25
|
+
"document",
|
|
26
|
+
// An IANA time zone name (`Asia/Bangkok`), checked against the runtime's list of zones. Left
|
|
27
|
+
// empty on a new record, the host fills in the deployment's zone (ADR 0460).
|
|
28
|
+
"timezone",
|
|
29
|
+
// Structured prose: a document with the platform's one rich text schema (stage 28, ADR 0440).
|
|
30
|
+
"richText",
|
|
31
|
+
// A record's address in its object (`summer-launch`): lowercase words joined by hyphens,
|
|
32
|
+
// unique among the object's live records, made from the title when left empty (ADR 0442).
|
|
33
|
+
"slug",
|
|
34
|
+
// A picture from the media library, with alt text and a focal point (stage 28, ADR 0444).
|
|
35
|
+
"image",
|
|
36
|
+
] as const;
|
|
37
|
+
export type FieldTypeName = (typeof FIELD_TYPES)[number];
|
|
38
|
+
|
|
39
|
+
/** What a formula sees when it reads a field of this type (null: not readable from formulas). */
|
|
40
|
+
export function formulaTypeOf(
|
|
41
|
+
type: FieldTypeName,
|
|
42
|
+
many = false,
|
|
43
|
+
): Exclude<FormulaType, "null"> | null {
|
|
44
|
+
switch (type) {
|
|
45
|
+
case "text":
|
|
46
|
+
case "longText":
|
|
47
|
+
case "select":
|
|
48
|
+
case "user":
|
|
49
|
+
case "email":
|
|
50
|
+
case "phone":
|
|
51
|
+
case "url":
|
|
52
|
+
case "timezone":
|
|
53
|
+
case "slug":
|
|
54
|
+
return "text";
|
|
55
|
+
case "relation":
|
|
56
|
+
return many ? null : "text";
|
|
57
|
+
case "number":
|
|
58
|
+
case "currency":
|
|
59
|
+
case "percent":
|
|
60
|
+
return "number";
|
|
61
|
+
case "boolean":
|
|
62
|
+
return "boolean";
|
|
63
|
+
case "date":
|
|
64
|
+
return "date";
|
|
65
|
+
case "datetime":
|
|
66
|
+
return "datetime";
|
|
67
|
+
case "multiSelect":
|
|
68
|
+
case "formula":
|
|
69
|
+
case "document":
|
|
70
|
+
case "richText":
|
|
71
|
+
case "image":
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Type changes the reconciler accepts: the stored values stay valid and keep their meaning.
|
|
78
|
+
* Anything else is refused with a suggestion to add a new field and migrate.
|
|
79
|
+
*/
|
|
80
|
+
export const LOSSLESS_TYPE_CHANGES: Readonly<Record<FieldTypeName, readonly FieldTypeName[]>> = {
|
|
81
|
+
text: ["longText"],
|
|
82
|
+
longText: [],
|
|
83
|
+
number: ["currency", "percent"],
|
|
84
|
+
currency: ["number"],
|
|
85
|
+
percent: ["number"],
|
|
86
|
+
date: ["datetime"],
|
|
87
|
+
datetime: [],
|
|
88
|
+
boolean: [],
|
|
89
|
+
select: ["text", "longText"],
|
|
90
|
+
multiSelect: [],
|
|
91
|
+
relation: [],
|
|
92
|
+
user: [],
|
|
93
|
+
email: ["text", "longText"],
|
|
94
|
+
phone: ["text", "longText"],
|
|
95
|
+
url: ["text", "longText"],
|
|
96
|
+
formula: [],
|
|
97
|
+
document: [],
|
|
98
|
+
timezone: ["text", "longText"],
|
|
99
|
+
richText: [],
|
|
100
|
+
slug: ["text", "longText"],
|
|
101
|
+
image: [],
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
export function isLosslessChange(from: FieldTypeName, to: FieldTypeName): boolean {
|
|
105
|
+
return from === to || LOSSLESS_TYPE_CHANGES[from].includes(to);
|
|
106
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Formula language: tokens, AST and errors. See the SDK README for the grammar.
|
|
2
|
+
|
|
3
|
+
/** The value types a formula expression can have. `null` is the type of the literal `null`. */
|
|
4
|
+
export type FormulaType = "number" | "text" | "boolean" | "date" | "datetime" | "null";
|
|
5
|
+
|
|
6
|
+
export interface Span {
|
|
7
|
+
start: number;
|
|
8
|
+
end: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type FormulaErrorCode =
|
|
12
|
+
| "formula_syntax"
|
|
13
|
+
| "formula_type"
|
|
14
|
+
| "formula_unknown_field"
|
|
15
|
+
| "formula_unknown_function"
|
|
16
|
+
| "formula_cycle"
|
|
17
|
+
| "formula_too_complex";
|
|
18
|
+
|
|
19
|
+
/** A structured formula error, with the character span it points at. */
|
|
20
|
+
export interface FormulaIssue {
|
|
21
|
+
code: FormulaErrorCode;
|
|
22
|
+
message: string;
|
|
23
|
+
span: Span;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class FormulaError extends Error {
|
|
27
|
+
override name = "FormulaError";
|
|
28
|
+
constructor(readonly issue: FormulaIssue) {
|
|
29
|
+
super(issue.message);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function formulaError(code: FormulaErrorCode, message: string, span: Span): FormulaError {
|
|
34
|
+
return new FormulaError({ code, message, span });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type BinaryOperator =
|
|
38
|
+
| "+"
|
|
39
|
+
| "-"
|
|
40
|
+
| "*"
|
|
41
|
+
| "/"
|
|
42
|
+
| "%"
|
|
43
|
+
| "&"
|
|
44
|
+
| "="
|
|
45
|
+
| "!="
|
|
46
|
+
| "<"
|
|
47
|
+
| "<="
|
|
48
|
+
| ">"
|
|
49
|
+
| ">="
|
|
50
|
+
| "and"
|
|
51
|
+
| "or";
|
|
52
|
+
|
|
53
|
+
export type FormulaNode =
|
|
54
|
+
| { kind: "number"; value: number; text: string; span: Span }
|
|
55
|
+
| { kind: "string"; value: string; span: Span }
|
|
56
|
+
| { kind: "boolean"; value: boolean; span: Span }
|
|
57
|
+
| { kind: "null"; span: Span }
|
|
58
|
+
| { kind: "field"; name: string; span: Span }
|
|
59
|
+
| { kind: "unary"; op: "-" | "not"; operand: FormulaNode; span: Span }
|
|
60
|
+
| { kind: "binary"; op: BinaryOperator; left: FormulaNode; right: FormulaNode; span: Span }
|
|
61
|
+
| { kind: "call"; name: string; args: FormulaNode[]; span: Span };
|
|
62
|
+
|
|
63
|
+
export const FORMULA_LIMITS = {
|
|
64
|
+
/** Characters in one expression. */
|
|
65
|
+
maxLength: 2000,
|
|
66
|
+
/** Nodes in one parsed expression. */
|
|
67
|
+
maxNodes: 400,
|
|
68
|
+
/** Nesting depth. */
|
|
69
|
+
maxDepth: 40,
|
|
70
|
+
/** Characters in one string literal. */
|
|
71
|
+
maxStringLength: 500,
|
|
72
|
+
} as const;
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
// Formula type checker and SQLite compiler. One pass over the AST: every node gets a type, and
|
|
2
|
+
// compiles to a SQLite expression only once its operands type-check.
|
|
3
|
+
//
|
|
4
|
+
// Safety: the only SQL text that does not come from this file is the field references, which the
|
|
5
|
+
// host supplies from validated identifiers. Numbers are re-printed from parsed values, strings are
|
|
6
|
+
// single-quoted with quotes doubled, and function names map to a fixed table. Nothing from the
|
|
7
|
+
// source is spliced into SQL verbatim.
|
|
8
|
+
import {
|
|
9
|
+
FormulaError,
|
|
10
|
+
type FormulaIssue,
|
|
11
|
+
type FormulaNode,
|
|
12
|
+
type FormulaType,
|
|
13
|
+
formulaError,
|
|
14
|
+
type Span,
|
|
15
|
+
} from "./ast.ts";
|
|
16
|
+
import { parseFormula } from "./parser.ts";
|
|
17
|
+
|
|
18
|
+
/** A field a formula may reference: its formula type and a trusted SQL expression for it. */
|
|
19
|
+
export type FormulaFieldRef =
|
|
20
|
+
| { type: Exclude<FormulaType, "null">; sql: string }
|
|
21
|
+
/** Another formula field, compiled on demand (cycles are reported). */
|
|
22
|
+
| { expression: string };
|
|
23
|
+
|
|
24
|
+
export interface FormulaEnvironment {
|
|
25
|
+
/** Fields of the same record, by name. Names are case-sensitive. */
|
|
26
|
+
fields: Record<string, FormulaFieldRef>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CompiledFormula {
|
|
30
|
+
/** The expression's type. A bare `null` formula is refused, so this is never "null". */
|
|
31
|
+
type: Exclude<FormulaType, "null">;
|
|
32
|
+
/** A SQLite expression. Booleans are 0/1 integers, dates ISO-8601 text. */
|
|
33
|
+
sql: string;
|
|
34
|
+
/** Field names the formula reads (directly). */
|
|
35
|
+
fields: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface Typed {
|
|
39
|
+
type: FormulaType;
|
|
40
|
+
sql: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const DATE_UNITS = ["day", "week", "month", "year"] as const;
|
|
44
|
+
type DateUnit = (typeof DATE_UNITS)[number];
|
|
45
|
+
|
|
46
|
+
/** Function signatures, for error messages and the README. */
|
|
47
|
+
export const FORMULA_FUNCTIONS: Record<string, string> = {
|
|
48
|
+
if: "if(condition, then, else)",
|
|
49
|
+
coalesce: "coalesce(value, fallback, ...)",
|
|
50
|
+
isBlank: "isBlank(value)",
|
|
51
|
+
concat: "concat(value, ...)",
|
|
52
|
+
length: "length(text)",
|
|
53
|
+
lower: "lower(text)",
|
|
54
|
+
upper: "upper(text)",
|
|
55
|
+
trim: "trim(text)",
|
|
56
|
+
round: "round(number, digits?)",
|
|
57
|
+
floor: "floor(number)",
|
|
58
|
+
ceil: "ceil(number)",
|
|
59
|
+
abs: "abs(number)",
|
|
60
|
+
min: "min(number, number, ...)",
|
|
61
|
+
max: "max(number, number, ...)",
|
|
62
|
+
today: "today()",
|
|
63
|
+
now: "now()",
|
|
64
|
+
dateAdd: 'dateAdd(date, amount, "day" | "week" | "month" | "year")',
|
|
65
|
+
dateDiff: 'dateDiff(start, end, "day" | "week" | "month" | "year")',
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const FUNCTION_LOOKUP = new Map(Object.keys(FORMULA_FUNCTIONS).map((n) => [n.toLowerCase(), n]));
|
|
69
|
+
|
|
70
|
+
function sqlString(value: string): string {
|
|
71
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function sqlNumber(value: number): string {
|
|
75
|
+
// Re-printed from the parsed value, so only digits, '.', 'e', '+', '-' can appear.
|
|
76
|
+
const text = Number.isInteger(value) ? value.toFixed(0) : String(value);
|
|
77
|
+
return /^-?[0-9.e+-]+$/i.test(text) ? text : "NULL";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function typeError(message: string, span: Span): FormulaError {
|
|
81
|
+
return formulaError("formula_type", message, span);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isTemporal(type: FormulaType): boolean {
|
|
85
|
+
return type === "date" || type === "datetime";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The common type of two operands (null fits anything; date and datetime meet at datetime). */
|
|
89
|
+
function unify(a: FormulaType, b: FormulaType): FormulaType | null {
|
|
90
|
+
if (a === "null") return b;
|
|
91
|
+
if (b === "null") return a;
|
|
92
|
+
if (a === b) return a;
|
|
93
|
+
if (isTemporal(a) && isTemporal(b)) return "datetime";
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Text form of a value, for concatenation: numbers without a trailing ".0". */
|
|
98
|
+
function asText(value: Typed): string {
|
|
99
|
+
switch (value.type) {
|
|
100
|
+
case "text":
|
|
101
|
+
return value.sql;
|
|
102
|
+
case "number":
|
|
103
|
+
return `(CASE WHEN ${value.sql} = CAST(${value.sql} AS INTEGER) THEN CAST(CAST(${value.sql} AS INTEGER) AS TEXT) ELSE CAST(${value.sql} AS TEXT) END)`;
|
|
104
|
+
case "boolean":
|
|
105
|
+
return `(CASE WHEN ${value.sql} IS NULL THEN NULL WHEN ${value.sql} THEN 'true' ELSE 'false' END)`;
|
|
106
|
+
case "null":
|
|
107
|
+
return "NULL";
|
|
108
|
+
default:
|
|
109
|
+
return value.sql;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
class Compiler {
|
|
114
|
+
readonly fieldsRead = new Set<string>();
|
|
115
|
+
|
|
116
|
+
constructor(
|
|
117
|
+
readonly env: FormulaEnvironment,
|
|
118
|
+
readonly resolving: Set<string>,
|
|
119
|
+
) {}
|
|
120
|
+
|
|
121
|
+
expect(node: FormulaNode, allowed: FormulaType[], what: string): Typed {
|
|
122
|
+
const value = this.compile(node);
|
|
123
|
+
if (value.type !== "null" && !allowed.includes(value.type)) {
|
|
124
|
+
throw typeError(`${what} must be ${allowed.join(" or ")}, not ${value.type}`, node.span);
|
|
125
|
+
}
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A date argument: a date/datetime expression, or a literal such as "2026-03-01". */
|
|
130
|
+
temporal(node: FormulaNode, what: string): Typed {
|
|
131
|
+
if (node.kind === "string") {
|
|
132
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(node.value))
|
|
133
|
+
return { type: "date", sql: sqlString(node.value) };
|
|
134
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?Z$/.test(node.value)) {
|
|
135
|
+
return { type: "datetime", sql: sqlString(node.value) };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return this.expect(node, ["date", "datetime"], what);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
compile(node: FormulaNode): Typed {
|
|
142
|
+
switch (node.kind) {
|
|
143
|
+
case "number":
|
|
144
|
+
return { type: "number", sql: sqlNumber(node.value) };
|
|
145
|
+
case "string":
|
|
146
|
+
return { type: "text", sql: sqlString(node.value) };
|
|
147
|
+
case "boolean":
|
|
148
|
+
return { type: "boolean", sql: node.value ? "1" : "0" };
|
|
149
|
+
case "null":
|
|
150
|
+
return { type: "null", sql: "NULL" };
|
|
151
|
+
case "field":
|
|
152
|
+
return this.field(node.name, node.span);
|
|
153
|
+
case "unary": {
|
|
154
|
+
if (node.op === "-") {
|
|
155
|
+
const operand = this.expect(node.operand, ["number"], "The operand of -");
|
|
156
|
+
return { type: "number", sql: `(-${operand.sql})` };
|
|
157
|
+
}
|
|
158
|
+
const operand = this.expect(node.operand, ["boolean"], "The operand of not");
|
|
159
|
+
return { type: "boolean", sql: `(NOT ${operand.sql})` };
|
|
160
|
+
}
|
|
161
|
+
case "binary":
|
|
162
|
+
return this.binary(node);
|
|
163
|
+
case "call":
|
|
164
|
+
return this.call(node);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
field(name: string, span: Span): Typed {
|
|
169
|
+
if (!Object.hasOwn(this.env.fields, name)) {
|
|
170
|
+
const known = Object.keys(this.env.fields);
|
|
171
|
+
const hint = known.find((k) => k.toLowerCase() === name.toLowerCase());
|
|
172
|
+
throw formulaError(
|
|
173
|
+
"formula_unknown_field",
|
|
174
|
+
hint
|
|
175
|
+
? `Unknown field "${name}". Did you mean "${hint}"? Names are case-sensitive.`
|
|
176
|
+
: `Unknown field "${name}". Fields on this record: ${known.join(", ") || "none"}`,
|
|
177
|
+
span,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
this.fieldsRead.add(name);
|
|
181
|
+
const ref = this.env.fields[name] as FormulaFieldRef;
|
|
182
|
+
if ("sql" in ref) return { type: ref.type, sql: ref.sql };
|
|
183
|
+
if (this.resolving.has(name)) {
|
|
184
|
+
throw formulaError(
|
|
185
|
+
"formula_cycle",
|
|
186
|
+
`Formula field "${name}" refers back to itself (through ${[...this.resolving].join(" → ")})`,
|
|
187
|
+
span,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
const inner = new Compiler(this.env, new Set([...this.resolving, name]));
|
|
191
|
+
let compiled: Typed;
|
|
192
|
+
try {
|
|
193
|
+
compiled = inner.compile(parseFormula(ref.expression));
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error instanceof FormulaError && error.issue.code === "formula_cycle") throw error;
|
|
196
|
+
throw typeError(`Formula field "${name}" has errors of its own`, span);
|
|
197
|
+
}
|
|
198
|
+
return { type: compiled.type, sql: `(${compiled.sql})` };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
binary(node: Extract<FormulaNode, { kind: "binary" }>): Typed {
|
|
202
|
+
const { op } = node;
|
|
203
|
+
if (op === "and" || op === "or") {
|
|
204
|
+
const left = this.expect(node.left, ["boolean"], `The left side of ${op}`);
|
|
205
|
+
const right = this.expect(node.right, ["boolean"], `The right side of ${op}`);
|
|
206
|
+
return { type: "boolean", sql: `(${left.sql} ${op.toUpperCase()} ${right.sql})` };
|
|
207
|
+
}
|
|
208
|
+
if (op === "&") {
|
|
209
|
+
const left = this.compile(node.left);
|
|
210
|
+
const right = this.compile(node.right);
|
|
211
|
+
return {
|
|
212
|
+
type: "text",
|
|
213
|
+
sql: `(coalesce(${asText(left)}, '') || coalesce(${asText(right)}, ''))`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
if (op === "+" || op === "-" || op === "*" || op === "/" || op === "%") {
|
|
217
|
+
const left = this.compile(node.left);
|
|
218
|
+
const right = this.compile(node.right);
|
|
219
|
+
if (op === "+" && (left.type === "text" || right.type === "text")) {
|
|
220
|
+
throw typeError("Use & or concat() to join text, not +", node.span);
|
|
221
|
+
}
|
|
222
|
+
if ((op === "+" || op === "-") && isTemporal(left.type)) {
|
|
223
|
+
throw typeError(`Use dateAdd() to move a date, not ${op}`, node.span);
|
|
224
|
+
}
|
|
225
|
+
for (const [side, value] of [
|
|
226
|
+
["left", left],
|
|
227
|
+
["right", right],
|
|
228
|
+
] as const) {
|
|
229
|
+
if (value.type !== "number" && value.type !== "null") {
|
|
230
|
+
throw typeError(
|
|
231
|
+
`The ${side} side of ${op} must be a number, not ${value.type}`,
|
|
232
|
+
side === "left" ? node.left.span : node.right.span,
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (op === "/") {
|
|
237
|
+
return { type: "number", sql: `(CAST(${left.sql} AS REAL) / NULLIF(${right.sql}, 0))` };
|
|
238
|
+
}
|
|
239
|
+
if (op === "%") return { type: "number", sql: `(${left.sql} % NULLIF(${right.sql}, 0))` };
|
|
240
|
+
return { type: "number", sql: `(${left.sql} ${op} ${right.sql})` };
|
|
241
|
+
}
|
|
242
|
+
// Comparisons.
|
|
243
|
+
const left = this.compile(node.left);
|
|
244
|
+
const right = this.compile(node.right);
|
|
245
|
+
if (left.type === "null" || right.type === "null") {
|
|
246
|
+
throw typeError("Compare with null using isBlank(value)", node.span);
|
|
247
|
+
}
|
|
248
|
+
const common = unify(left.type, right.type);
|
|
249
|
+
if (!common) {
|
|
250
|
+
throw typeError(`Cannot compare ${left.type} with ${right.type}`, node.span);
|
|
251
|
+
}
|
|
252
|
+
if (common === "boolean" && op !== "=" && op !== "!=") {
|
|
253
|
+
throw typeError(`Booleans can only be compared with = and !=`, node.span);
|
|
254
|
+
}
|
|
255
|
+
const sqlOp = op === "!=" ? "<>" : op;
|
|
256
|
+
if (common === "datetime" && left.type !== right.type) {
|
|
257
|
+
return {
|
|
258
|
+
type: "boolean",
|
|
259
|
+
sql: `(julianday(${left.sql}) ${sqlOp} julianday(${right.sql}))`,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return { type: "boolean", sql: `(${left.sql} ${sqlOp} ${right.sql})` };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
arity(node: Extract<FormulaNode, { kind: "call" }>, name: string, min: number, max: number) {
|
|
266
|
+
if (node.args.length < min || node.args.length > max) {
|
|
267
|
+
throw typeError(
|
|
268
|
+
`${name} takes ${min === max ? min : `${min} to ${max === Infinity ? "any number of" : max}`} argument${max === 1 ? "" : "s"}: ${FORMULA_FUNCTIONS[name]}`,
|
|
269
|
+
node.span,
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
unit(node: FormulaNode | undefined, fn: string, span: Span): DateUnit {
|
|
275
|
+
if (node?.kind !== "string" || !DATE_UNITS.includes(node.value as DateUnit)) {
|
|
276
|
+
throw typeError(
|
|
277
|
+
`The unit of ${fn} must be a quoted literal: "day", "week", "month" or "year"`,
|
|
278
|
+
node?.span ?? span,
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
return node.value as DateUnit;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
call(node: Extract<FormulaNode, { kind: "call" }>): Typed {
|
|
285
|
+
const name = FUNCTION_LOOKUP.get(node.name.toLowerCase());
|
|
286
|
+
if (!name) {
|
|
287
|
+
throw formulaError(
|
|
288
|
+
"formula_unknown_function",
|
|
289
|
+
`Unknown function "${node.name}". Available: ${Object.keys(FORMULA_FUNCTIONS).join(", ")}`,
|
|
290
|
+
node.span,
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
const args = node.args;
|
|
294
|
+
switch (name) {
|
|
295
|
+
case "if": {
|
|
296
|
+
this.arity(node, name, 3, 3);
|
|
297
|
+
const condition = this.expect(args[0] as FormulaNode, ["boolean"], "The condition of if");
|
|
298
|
+
const then = this.compile(args[1] as FormulaNode);
|
|
299
|
+
const otherwise = this.compile(args[2] as FormulaNode);
|
|
300
|
+
const type = unify(then.type, otherwise.type);
|
|
301
|
+
if (!type) {
|
|
302
|
+
throw typeError(
|
|
303
|
+
`Both branches of if must have the same type (got ${then.type} and ${otherwise.type})`,
|
|
304
|
+
node.span,
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
type,
|
|
309
|
+
sql: `(CASE WHEN ${condition.sql} THEN ${then.sql} ELSE ${otherwise.sql} END)`,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
case "coalesce": {
|
|
313
|
+
this.arity(node, name, 2, 20);
|
|
314
|
+
const values = args.map((arg) => this.compile(arg));
|
|
315
|
+
let type: FormulaType = "null";
|
|
316
|
+
for (const value of values) {
|
|
317
|
+
const next = unify(type, value.type);
|
|
318
|
+
if (!next) {
|
|
319
|
+
throw typeError("All arguments of coalesce must have the same type", node.span);
|
|
320
|
+
}
|
|
321
|
+
type = next;
|
|
322
|
+
}
|
|
323
|
+
return { type, sql: `coalesce(${values.map((v) => v.sql).join(", ")})` };
|
|
324
|
+
}
|
|
325
|
+
case "isBlank": {
|
|
326
|
+
this.arity(node, name, 1, 1);
|
|
327
|
+
const value = this.compile(args[0] as FormulaNode);
|
|
328
|
+
const blank =
|
|
329
|
+
value.type === "text"
|
|
330
|
+
? `(${value.sql} IS NULL OR trim(${value.sql}) = '')`
|
|
331
|
+
: `(${value.sql} IS NULL)`;
|
|
332
|
+
return { type: "boolean", sql: blank };
|
|
333
|
+
}
|
|
334
|
+
case "concat": {
|
|
335
|
+
this.arity(node, name, 1, 20);
|
|
336
|
+
const parts = args.map((arg) => `coalesce(${asText(this.compile(arg))}, '')`);
|
|
337
|
+
return { type: "text", sql: `(${parts.join(" || ")})` };
|
|
338
|
+
}
|
|
339
|
+
case "length":
|
|
340
|
+
case "lower":
|
|
341
|
+
case "upper":
|
|
342
|
+
case "trim": {
|
|
343
|
+
this.arity(node, name, 1, 1);
|
|
344
|
+
const value = this.expect(args[0] as FormulaNode, ["text"], `The argument of ${name}`);
|
|
345
|
+
return { type: name === "length" ? "number" : "text", sql: `${name}(${value.sql})` };
|
|
346
|
+
}
|
|
347
|
+
case "round": {
|
|
348
|
+
this.arity(node, name, 1, 2);
|
|
349
|
+
const value = this.expect(args[0] as FormulaNode, ["number"], "The value to round");
|
|
350
|
+
const digitsNode = args[1];
|
|
351
|
+
let digits = 0;
|
|
352
|
+
if (digitsNode) {
|
|
353
|
+
if (digitsNode.kind !== "number" || !Number.isInteger(digitsNode.value)) {
|
|
354
|
+
throw typeError("round's digits must be a whole number literal", digitsNode.span);
|
|
355
|
+
}
|
|
356
|
+
digits = digitsNode.value;
|
|
357
|
+
if (digits < 0 || digits > 10) {
|
|
358
|
+
throw typeError("round's digits must be between 0 and 10", digitsNode.span);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return { type: "number", sql: `round(${value.sql}, ${digits})` };
|
|
362
|
+
}
|
|
363
|
+
case "floor":
|
|
364
|
+
case "ceil": {
|
|
365
|
+
this.arity(node, name, 1, 1);
|
|
366
|
+
const v = this.expect(args[0] as FormulaNode, ["number"], `The argument of ${name}`).sql;
|
|
367
|
+
// SQLite's math functions are optional, so floor/ceil are built from CAST (truncation).
|
|
368
|
+
const sql =
|
|
369
|
+
name === "floor"
|
|
370
|
+
? `(CASE WHEN ${v} IS NULL THEN NULL WHEN ${v} >= 0 OR ${v} = CAST(${v} AS INTEGER) THEN CAST(${v} AS INTEGER) ELSE CAST(${v} AS INTEGER) - 1 END)`
|
|
371
|
+
: `(CASE WHEN ${v} IS NULL THEN NULL WHEN ${v} <= 0 OR ${v} = CAST(${v} AS INTEGER) THEN CAST(${v} AS INTEGER) ELSE CAST(${v} AS INTEGER) + 1 END)`;
|
|
372
|
+
return { type: "number", sql };
|
|
373
|
+
}
|
|
374
|
+
case "abs": {
|
|
375
|
+
this.arity(node, name, 1, 1);
|
|
376
|
+
const v = this.expect(args[0] as FormulaNode, ["number"], "The argument of abs");
|
|
377
|
+
return { type: "number", sql: `abs(${v.sql})` };
|
|
378
|
+
}
|
|
379
|
+
case "min":
|
|
380
|
+
case "max": {
|
|
381
|
+
this.arity(node, name, 2, 20);
|
|
382
|
+
const values = args.map((arg) => this.expect(arg, ["number"], `Arguments of ${name}`));
|
|
383
|
+
return { type: "number", sql: `${name}(${values.map((v) => v.sql).join(", ")})` };
|
|
384
|
+
}
|
|
385
|
+
case "today":
|
|
386
|
+
this.arity(node, name, 0, 0);
|
|
387
|
+
return { type: "date", sql: "date('now')" };
|
|
388
|
+
case "now":
|
|
389
|
+
this.arity(node, name, 0, 0);
|
|
390
|
+
return { type: "datetime", sql: "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" };
|
|
391
|
+
case "dateAdd": {
|
|
392
|
+
this.arity(node, name, 3, 3);
|
|
393
|
+
const date = this.temporal(args[0] as FormulaNode, "dateAdd's date");
|
|
394
|
+
const amount = this.expect(args[1] as FormulaNode, ["number"], "dateAdd's amount");
|
|
395
|
+
const unit = this.unit(args[2], name, node.span);
|
|
396
|
+
const n = unit === "week" ? `(${amount.sql}) * 7` : amount.sql;
|
|
397
|
+
const modifier = `printf('%+d ${unit === "week" ? "day" : unit}s', CAST(${n} AS INTEGER))`;
|
|
398
|
+
const sql =
|
|
399
|
+
date.type === "date"
|
|
400
|
+
? `date(${date.sql}, ${modifier})`
|
|
401
|
+
: `strftime('%Y-%m-%dT%H:%M:%fZ', ${date.sql}, ${modifier})`;
|
|
402
|
+
return { type: date.type === "null" ? "date" : date.type, sql };
|
|
403
|
+
}
|
|
404
|
+
case "dateDiff": {
|
|
405
|
+
this.arity(node, name, 3, 3);
|
|
406
|
+
const start = this.temporal(args[0] as FormulaNode, "dateDiff's start");
|
|
407
|
+
const end = this.temporal(args[1] as FormulaNode, "dateDiff's end");
|
|
408
|
+
const unit = this.unit(args[2], name, node.span);
|
|
409
|
+
const days = `(julianday(${end.sql}) - julianday(${start.sql}))`;
|
|
410
|
+
let sql: string;
|
|
411
|
+
if (unit === "day") sql = `CAST(${days} AS INTEGER)`;
|
|
412
|
+
else if (unit === "week") sql = `CAST(${days} / 7 AS INTEGER)`;
|
|
413
|
+
else {
|
|
414
|
+
const months = `((CAST(strftime('%Y', ${end.sql}) AS INTEGER) * 12 + CAST(strftime('%m', ${end.sql}) AS INTEGER)) - (CAST(strftime('%Y', ${start.sql}) AS INTEGER) * 12 + CAST(strftime('%m', ${start.sql}) AS INTEGER)))`;
|
|
415
|
+
sql = unit === "month" ? months : `(${months} / 12)`;
|
|
416
|
+
}
|
|
417
|
+
return { type: "number", sql };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
throw formulaError("formula_unknown_function", `Unknown function "${node.name}"`, node.span);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Parses, type-checks and compiles a formula against the fields of one record. Throws
|
|
426
|
+
* FormulaError (see `issue` for the code and span).
|
|
427
|
+
*/
|
|
428
|
+
export function compileFormula(
|
|
429
|
+
expression: string,
|
|
430
|
+
env: FormulaEnvironment,
|
|
431
|
+
self?: string,
|
|
432
|
+
): CompiledFormula {
|
|
433
|
+
const ast = parseFormula(expression);
|
|
434
|
+
const compiler = new Compiler(env, new Set(self ? [self] : []));
|
|
435
|
+
const result = compiler.compile(ast);
|
|
436
|
+
if (result.type === "null") {
|
|
437
|
+
throw typeError("A formula cannot always be null", ast.span);
|
|
438
|
+
}
|
|
439
|
+
return { type: result.type, sql: result.sql, fields: [...compiler.fieldsRead] };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Like compileFormula, but returns the issue instead of throwing. */
|
|
443
|
+
export function checkFormula(
|
|
444
|
+
expression: string,
|
|
445
|
+
env: FormulaEnvironment,
|
|
446
|
+
self?: string,
|
|
447
|
+
): { ok: true; formula: CompiledFormula } | { ok: false; issue: FormulaIssue } {
|
|
448
|
+
try {
|
|
449
|
+
return { ok: true, formula: compileFormula(expression, env, self) };
|
|
450
|
+
} catch (error) {
|
|
451
|
+
if (error instanceof FormulaError) return { ok: false, issue: error.issue };
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
}
|