Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(forms): share poll responses and make anonymous polls truly anonymous (#8529)

Wolf Mermelstein9e3db8c076ba
diff --git a/.sqlx/query-fea822d1f32f5546c5e2338475a96946e52271743b821bbcb7a6ab834c462964.json b/.sqlx/query-08a0a89334beef9d9d5b09fd5d553a9e85681f99a4e1699432e7800b66f959cd.json
similarity index 62%
rename from .sqlx/query-fea822d1f32f5546c5e2338475a96946e52271743b821bbcb7a6ab834c462964.json
rename to .sqlx/query-08a0a89334beef9d9d5b09fd5d553a9e85681f99a4e1699432e7800b66f959cd.json
index 58277404f1..b0f7c7127b 100644
--- a/.sqlx/query-fea822d1f32f5546c5e2338475a96946e52271743b821bbcb7a6ab834c462964.json
+++ b/.sqlx/query-08a0a89334beef9d9d5b09fd5d553a9e85681f99a4e1699432e7800b66f959cd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT access_level::text\n FROM entity_access\n JOIN database_entities d ON d.database_id = entity_access.entity_id\n WHERE entity_id = $1\n AND entity_type = 'database'\n AND source_id = ANY($2)\n\n UNION ALL\n\n SELECT 'edit'\n FROM forms f\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n ",
+ "query": "\n SELECT access_level::text\n FROM entity_access\n JOIN database_entities d ON d.database_id = entity_access.entity_id\n WHERE entity_id = $1\n AND entity_type = 'database'\n AND source_id = ANY($2)\n\n UNION ALL\n\n SELECT 'edit'\n FROM forms f\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n\n UNION ALL\n\n SELECT 'view'\n FROM forms f\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = $1\n AND f.trashed_at IS NULL\n AND f.responses_visible\n AND ea.source_id = ANY($2)\n AND ea.access_level = 'view'\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "fea822d1f32f5546c5e2338475a96946e52271743b821bbcb7a6ab834c462964"
+ "hash": "08a0a89334beef9d9d5b09fd5d553a9e85681f99a4e1699432e7800b66f959cd"
}
diff --git a/.sqlx/query-963e1402539cc6ff0e3f4dd1f995e5635b1b36c4b70179e415d53f08b58a6c5c.json b/.sqlx/query-0eddedea5dd1c4c93ef4cb17b0d36de6b308810ccdb0d73013fb6351f47a0d00.json
similarity index 71%
rename from .sqlx/query-963e1402539cc6ff0e3f4dd1f995e5635b1b36c4b70179e415d53f08b58a6c5c.json
rename to .sqlx/query-0eddedea5dd1c4c93ef4cb17b0d36de6b308810ccdb0d73013fb6351f47a0d00.json
index e0eb1fcc30..a1db236977 100644
--- a/.sqlx/query-963e1402539cc6ff0e3f4dd1f995e5635b1b36c4b70179e415d53f08b58a6c5c.json
+++ b/.sqlx/query-0eddedea5dd1c4c93ef4cb17b0d36de6b308810ccdb0d73013fb6351f47a0d00.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT entity_id AS \"entity_id!\", access_level AS \"access_level!: AccessLevel\"\n FROM entity_access\n JOIN database_entities d ON d.database_id = entity_access.entity_id\n WHERE entity_type = 'database'\n AND source_id = ANY($1)\n\n UNION ALL\n\n SELECT f.database_id, 'edit'::\"AccessLevel\"\n FROM entity_access ea\n JOIN forms f ON f.id = ea.entity_id\n JOIN database_entities d ON d.database_id = f.database_id\n WHERE ea.entity_type = 'form'\n AND ea.source_id = ANY($1)\n AND ea.access_level IN ('edit', 'owner')\n AND f.trashed_at IS NULL\n ",
+ "query": "\n SELECT entity_id AS \"entity_id!\", access_level AS \"access_level!: AccessLevel\"\n FROM entity_access\n JOIN database_entities d ON d.database_id = entity_access.entity_id\n WHERE entity_type = 'database'\n AND source_id = ANY($1)\n\n UNION ALL\n\n SELECT f.database_id, 'edit'::\"AccessLevel\"\n FROM entity_access ea\n JOIN forms f ON f.id = ea.entity_id\n JOIN database_entities d ON d.database_id = f.database_id\n WHERE ea.entity_type = 'form'\n AND ea.source_id = ANY($1)\n AND ea.access_level IN ('edit', 'owner')\n AND f.trashed_at IS NULL\n\n UNION ALL\n\n SELECT f.database_id, 'view'::\"AccessLevel\"\n FROM entity_access ea\n JOIN forms f ON f.id = ea.entity_id\n JOIN database_entities d ON d.database_id = f.database_id\n WHERE ea.entity_type = 'form'\n AND ea.source_id = ANY($1)\n AND ea.access_level = 'view'\n AND f.responses_visible\n AND f.trashed_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -36,5 +36,5 @@
null
]
},
- "hash": "963e1402539cc6ff0e3f4dd1f995e5635b1b36c4b70179e415d53f08b58a6c5c"
+ "hash": "0eddedea5dd1c4c93ef4cb17b0d36de6b308810ccdb0d73013fb6351f47a0d00"
}
diff --git a/.sqlx/query-546d1f5d50af8525fd40adb78d71efd9ccbc890793260aea954ac250df778ab1.json b/.sqlx/query-2c9eabbdb8d3445dc1a5522a810a49c7fe14d300f0057f8030ed1559efe09bcd.json
similarity index 75%
rename from .sqlx/query-546d1f5d50af8525fd40adb78d71efd9ccbc890793260aea954ac250df778ab1.json
rename to .sqlx/query-2c9eabbdb8d3445dc1a5522a810a49c7fe14d300f0057f8030ed1559efe09bcd.json
index 8c4cccb82d..52df12277a 100644
--- a/.sqlx/query-546d1f5d50af8525fd40adb78d71efd9ccbc890793260aea954ac250df778ab1.json
+++ b/.sqlx/query-2c9eabbdb8d3445dc1a5522a810a49c7fe14d300f0057f8030ed1559efe09bcd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL SELECT team_id::text FROM team_user WHERE user_id = $1\n UNION ALL SELECT $1\n)\nSELECT r.id, r.table_id, row_table.database_id, r.position, r.created_by,\n row_database.user_id AS owner_id, r.created_at, r.updated_at\nFROM database_rows r\nJOIN database_tables row_table ON row_table.id = r.table_id\nJOIN database_entities row_database ON row_database.database_id = row_table.database_id\nWHERE r.id = ANY($2)\n AND row_database.trashed_at IS NULL\n AND (\n EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = row_database.database_id AND ea.entity_type = 'database'\n AND ea.source_id IN (SELECT source_id FROM user_source_ids))\n -- Editors of a live form over the database edit its rows.\n OR EXISTS (SELECT 1 FROM forms f\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = row_database.database_id AND f.trashed_at IS NULL\n AND ea.access_level IN ('edit', 'owner')\n AND ea.source_id IN (SELECT source_id FROM user_source_ids))\n )\nORDER BY r.created_at DESC, r.id DESC\n",
+ "query": "WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL SELECT team_id::text FROM team_user WHERE user_id = $1\n UNION ALL SELECT $1\n)\nSELECT r.id, r.table_id, row_table.database_id, r.position, r.created_by,\n row_database.user_id AS owner_id, r.created_at, r.updated_at\nFROM database_rows r\nJOIN database_tables row_table ON row_table.id = r.table_id\nJOIN database_entities row_database ON row_database.database_id = row_table.database_id\nWHERE r.id = ANY($2)\n AND row_database.trashed_at IS NULL\n AND (\n EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = row_database.database_id AND ea.entity_type = 'database'\n AND ea.source_id IN (SELECT source_id FROM user_source_ids))\n -- Editors of a live form over the database edit its rows; viewers\n -- read them when the form shares its responses.\n OR EXISTS (SELECT 1 FROM forms f\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = row_database.database_id AND f.trashed_at IS NULL\n AND (ea.access_level IN ('edit', 'owner')\n OR (ea.access_level = 'view' AND f.responses_visible))\n AND ea.source_id IN (SELECT source_id FROM user_source_ids))\n )\nORDER BY r.created_at DESC, r.id DESC\n",
"describe": {
"columns": [
{
@@ -61,5 +61,5 @@
false
]
},
- "hash": "546d1f5d50af8525fd40adb78d71efd9ccbc890793260aea954ac250df778ab1"
+ "hash": "2c9eabbdb8d3445dc1a5522a810a49c7fe14d300f0057f8030ed1559efe09bcd"
}
diff --git a/.sqlx/query-3f85ee4390d09bfcab88d8ee59d48529c7195d82dc4100a296ef57f4d8356681.json b/.sqlx/query-3f85ee4390d09bfcab88d8ee59d48529c7195d82dc4100a296ef57f4d8356681.json
new file mode 100644
index 0000000000..dd87dc01ac
--- /dev/null
+++ b/.sqlx/query-3f85ee4390d09bfcab88d8ee59d48529c7195d82dc4100a296ef57f4d8356681.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM form_submission_receipts WHERE form_id = $1 AND user_id = $2\n ) AS \"held!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "held!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3f85ee4390d09bfcab88d8ee59d48529c7195d82dc4100a296ef57f4d8356681"
+}
diff --git a/.sqlx/query-4ae6fd1db92a42958902f55c453d640afaeedf7eca9890354eb73044fe56877a.json b/.sqlx/query-4ae6fd1db92a42958902f55c453d640afaeedf7eca9890354eb73044fe56877a.json
new file mode 100644
index 0000000000..15d3a5e7a9
--- /dev/null
+++ b/.sqlx/query-4ae6fd1db92a42958902f55c453d640afaeedf7eca9890354eb73044fe56877a.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT row_id AS \"row_id!\", respondent_id AS \"respondent_id!\"\n FROM form_responses\n WHERE form_id = $1 AND status = 'submitted'\n AND row_id IS NOT NULL AND respondent_id IS NOT NULL\n ORDER BY submitted_at, id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "row_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "respondent_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "4ae6fd1db92a42958902f55c453d640afaeedf7eca9890354eb73044fe56877a"
+}
diff --git a/.sqlx/query-b211c6a5cb5dc8ffdb922121bf6992b0038f9de5a80a6e860378a96cc754b097.json b/.sqlx/query-626d8e77c99963524fd19b859776d548de1fe1f2c8b6a844da034e080d2e6b25.json
similarity index 70%
rename from .sqlx/query-b211c6a5cb5dc8ffdb922121bf6992b0038f9de5a80a6e860378a96cc754b097.json
rename to .sqlx/query-626d8e77c99963524fd19b859776d548de1fe1f2c8b6a844da034e080d2e6b25.json
index d412a4a34b..85a7917d09 100644
--- a/.sqlx/query-b211c6a5cb5dc8ffdb922121bf6992b0038f9de5a80a6e860378a96cc754b097.json
+++ b/.sqlx/query-626d8e77c99963524fd19b859776d548de1fe1f2c8b6a844da034e080d2e6b25.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT r.id AS \"id!\", ea.access_level AS \"access_level!: AccessLevel\"\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN database_entities d ON d.database_id = t.database_id\n JOIN entity_access ea ON ea.entity_id = d.database_id\n WHERE r.id = ANY($1)\n AND ea.entity_type = 'database'\n AND ea.source_id = ANY($2)\n\n UNION ALL\n\n SELECT r.id, 'edit'::\"AccessLevel\"\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = ANY($1)\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n ",
+ "query": "\n SELECT r.id AS \"id!\", ea.access_level AS \"access_level!: AccessLevel\"\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN database_entities d ON d.database_id = t.database_id\n JOIN entity_access ea ON ea.entity_id = d.database_id\n WHERE r.id = ANY($1)\n AND ea.entity_type = 'database'\n AND ea.source_id = ANY($2)\n\n UNION ALL\n\n SELECT r.id, 'edit'::\"AccessLevel\"\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = ANY($1)\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n\n UNION ALL\n\n SELECT r.id, 'view'::\"AccessLevel\"\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = ANY($1)\n AND f.trashed_at IS NULL\n AND f.responses_visible\n AND ea.source_id = ANY($2)\n AND ea.access_level = 'view'\n ",
"describe": {
"columns": [
{
@@ -37,5 +37,5 @@
null
]
},
- "hash": "b211c6a5cb5dc8ffdb922121bf6992b0038f9de5a80a6e860378a96cc754b097"
+ "hash": "626d8e77c99963524fd19b859776d548de1fe1f2c8b6a844da034e080d2e6b25"
}
diff --git a/.sqlx/query-e30105d1ce1d17aa6b38c609ff2cc579ed426936d0f6c54708e39f8a7da80067.json b/.sqlx/query-82b80450caa3471f6d2a274dfe15aa4d53091a956586f73549ac2abd70b8877f.json
similarity index 68%
rename from .sqlx/query-e30105d1ce1d17aa6b38c609ff2cc579ed426936d0f6c54708e39f8a7da80067.json
rename to .sqlx/query-82b80450caa3471f6d2a274dfe15aa4d53091a956586f73549ac2abd70b8877f.json
index 240866a897..e094b0d17f 100644
--- a/.sqlx/query-e30105d1ce1d17aa6b38c609ff2cc579ed426936d0f6c54708e39f8a7da80067.json
+++ b/.sqlx/query-82b80450caa3471f6d2a274dfe15aa4d53091a956586f73549ac2abd70b8877f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO forms (\n id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id,\n accent_color, created_at, updated_at, name_follows_database, is_hidden_in_drive\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,\n $19, $20\n )\n ON CONFLICT (table_id) DO NOTHING\n ",
+ "query": "\n INSERT INTO forms (\n id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id,\n accent_color, created_at, updated_at, name_follows_database, is_hidden_in_drive, responses_visible, anonymous\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,\n $19, $20, $21, $22\n )\n ON CONFLICT (table_id) DO NOTHING\n ",
"describe": {
"columns": [],
"parameters": {
@@ -24,10 +24,12 @@
"Timestamptz",
"Timestamptz",
"Bool",
+ "Bool",
+ "Bool",
"Bool"
]
},
"nullable": []
},
- "hash": "e30105d1ce1d17aa6b38c609ff2cc579ed426936d0f6c54708e39f8a7da80067"
+ "hash": "82b80450caa3471f6d2a274dfe15aa4d53091a956586f73549ac2abd70b8877f"
}
diff --git a/.sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json b/.sqlx/query-9854fed3737c65c1444772604a28ff25eb13d1c3cc79b8bcf622b3e56410687a.json
similarity index 77%
rename from .sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json
rename to .sqlx/query-9854fed3737c65c1444772604a28ff25eb13d1c3cc79b8bcf622b3e56410687a.json
index af019e46dd..01db4a30a4 100644
--- a/.sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json
+++ b/.sqlx/query-9854fed3737c65c1444772604a28ff25eb13d1c3cc79b8bcf622b3e56410687a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET\n description = COALESCE($2, description),\n confirmation_message = COALESCE($3, confirmation_message),\n audience = COALESCE($4, audience),\n status = COALESCE($5, status),\n closes_at = CASE WHEN $6 THEN $7 ELSE closes_at END,\n tally_visible = COALESCE($8, tally_visible),\n logo_file_id = CASE WHEN $10 THEN $11 ELSE logo_file_id END,\n cover_file_id = CASE WHEN $12 THEN $13 ELSE cover_file_id END,\n accent_color = CASE WHEN $14 THEN $15 ELSE accent_color END,\n updated_at = $9\n WHERE id = $1\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
+ "query": "\n UPDATE forms SET\n description = COALESCE($2, description),\n confirmation_message = COALESCE($3, confirmation_message),\n audience = COALESCE($4, audience),\n status = COALESCE($5, status),\n closes_at = CASE WHEN $6 THEN $7 ELSE closes_at END,\n tally_visible = COALESCE($8, tally_visible),\n logo_file_id = CASE WHEN $10 THEN $11 ELSE logo_file_id END,\n cover_file_id = CASE WHEN $12 THEN $13 ELSE cover_file_id END,\n accent_color = CASE WHEN $14 THEN $15 ELSE accent_color END,\n responses_visible = COALESCE($16, responses_visible),\n anonymous = COALESCE($17, anonymous),\n updated_at = $9\n WHERE id = $1\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -130,7 +140,9 @@
"Bool",
"Uuid",
"Bool",
- "Text"
+ "Text",
+ "Bool",
+ "Bool"
]
},
"nullable": [
@@ -155,8 +167,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e"
+ "hash": "9854fed3737c65c1444772604a28ff25eb13d1c3cc79b8bcf622b3e56410687a"
}
diff --git a/.sqlx/query-a8ff2585e3785a94e7900900f2de9557e708871c152add1c6385550b56233534.json b/.sqlx/query-a8ff2585e3785a94e7900900f2de9557e708871c152add1c6385550b56233534.json
new file mode 100644
index 0000000000..60ba7e5bf8
--- /dev/null
+++ b/.sqlx/query-a8ff2585e3785a94e7900900f2de9557e708871c152add1c6385550b56233534.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO form_submission_receipts (form_id, user_id) VALUES ($1, $2)\n ON CONFLICT DO NOTHING\n RETURNING 1 AS \"one!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "one!",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "a8ff2585e3785a94e7900900f2de9557e708871c152add1c6385550b56233534"
+}
diff --git a/.sqlx/query-0f45184a2df57c6c6de81a21ae086f69b28c225b58290112ada906ba3ced27ac.json b/.sqlx/query-a9d746d70e665165ed3a6412d51d5428da14bc21ec0886cd46554e569780ccc3.json
similarity index 65%
rename from .sqlx/query-0f45184a2df57c6c6de81a21ae086f69b28c225b58290112ada906ba3ced27ac.json
rename to .sqlx/query-a9d746d70e665165ed3a6412d51d5428da14bc21ec0886cd46554e569780ccc3.json
index 29a91e932c..1840826fb2 100644
--- a/.sqlx/query-0f45184a2df57c6c6de81a21ae086f69b28c225b58290112ada906ba3ced27ac.json
+++ b/.sqlx/query-a9d746d70e665165ed3a6412d51d5428da14bc21ec0886cd46554e569780ccc3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT ea.access_level::text\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN database_entities d ON d.database_id = t.database_id\n JOIN entity_access ea ON ea.entity_id = d.database_id\n WHERE r.id = $1\n AND ea.entity_type = 'database'\n AND ea.source_id = ANY($2)\n\n UNION ALL\n\n SELECT 'edit'\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n ",
+ "query": "\n SELECT ea.access_level::text\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN database_entities d ON d.database_id = t.database_id\n JOIN entity_access ea ON ea.entity_id = d.database_id\n WHERE r.id = $1\n AND ea.entity_type = 'database'\n AND ea.source_id = ANY($2)\n\n UNION ALL\n\n SELECT 'edit'\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n\n UNION ALL\n\n SELECT 'view'\n FROM database_rows r\n JOIN database_tables t ON t.id = r.table_id\n JOIN forms f ON f.database_id = t.database_id\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE r.id = $1\n AND f.trashed_at IS NULL\n AND f.responses_visible\n AND ea.source_id = ANY($2)\n AND ea.access_level = 'view'\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "0f45184a2df57c6c6de81a21ae086f69b28c225b58290112ada906ba3ced27ac"
+ "hash": "a9d746d70e665165ed3a6412d51d5428da14bc21ec0886cd46554e569780ccc3"
}
diff --git a/.sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json b/.sqlx/query-aa10ca7c0ac5cba95be3e13063fde1f4ffe439b5250e25ead8df49d694937d50.json
similarity index 89%
rename from .sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json
rename to .sqlx/query-aa10ca7c0ac5cba95be3e13063fde1f4ffe439b5250e25ead8df49d694937d50.json
index 46eb8e8510..78fcc6b27c 100644
--- a/.sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json
+++ b/.sqlx/query-aa10ca7c0ac5cba95be3e13063fde1f4ffe439b5250e25ead8df49d694937d50.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET name = $2, updated_at = $3\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
+ "query": "\n UPDATE forms SET name = $2, updated_at = $3\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -143,8 +153,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd"
+ "hash": "aa10ca7c0ac5cba95be3e13063fde1f4ffe439b5250e25ead8df49d694937d50"
}
diff --git a/.sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json b/.sqlx/query-aa8cd811238f3ce85b7828232b8de835d6ca087aa1352346e33f92f6231db395.json
similarity index 85%
rename from .sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json
rename to .sqlx/query-aa8cd811238f3ce85b7828232b8de835d6ca087aa1352346e33f92f6231db395.json
index e0df2313e5..e0cb19bade 100644
--- a/.sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json
+++ b/.sqlx/query-aa8cd811238f3ce85b7828232b8de835d6ca087aa1352346e33f92f6231db395.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE database_id = $1 AND trashed_at IS NULL\n ORDER BY created_at, id\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n FROM forms WHERE database_id = $1 AND trashed_at IS NULL\n ORDER BY created_at, id\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -141,8 +151,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283"
+ "hash": "aa8cd811238f3ce85b7828232b8de835d6ca087aa1352346e33f92f6231db395"
}
diff --git a/.sqlx/query-3c2e84eee359fa261d9a6cc84f15c74fa57d4d5909d84547a642f110c8bc24d8.json b/.sqlx/query-c20fe67ae6ec1f5396697a14c679c9ad789db49dd1b76331c2eb220fd10b00fe.json
similarity index 70%
rename from .sqlx/query-3c2e84eee359fa261d9a6cc84f15c74fa57d4d5909d84547a642f110c8bc24d8.json
rename to .sqlx/query-c20fe67ae6ec1f5396697a14c679c9ad789db49dd1b76331c2eb220fd10b00fe.json
index 6225ee4aaf..6bd95e50e0 100644
--- a/.sqlx/query-3c2e84eee359fa261d9a6cc84f15c74fa57d4d5909d84547a642f110c8bc24d8.json
+++ b/.sqlx/query-c20fe67ae6ec1f5396697a14c679c9ad789db49dd1b76331c2eb220fd10b00fe.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT f.id\n FROM forms f\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND ea.access_level IN ('edit', 'owner')\n ORDER BY f.id\n ",
+ "query": "\n SELECT DISTINCT f.id\n FROM forms f\n JOIN database_entities d ON d.database_id = f.database_id\n JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'\n WHERE f.database_id = $1\n AND f.trashed_at IS NULL\n AND ea.source_id = ANY($2)\n AND (\n ea.access_level IN ('edit', 'owner')\n OR (ea.access_level = 'view' AND f.responses_visible)\n )\n ORDER BY f.id\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
false
]
},
- "hash": "3c2e84eee359fa261d9a6cc84f15c74fa57d4d5909d84547a642f110c8bc24d8"
+ "hash": "c20fe67ae6ec1f5396697a14c679c9ad789db49dd1b76331c2eb220fd10b00fe"
}
diff --git a/.sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json b/.sqlx/query-d68ac2f747c41c83b3f68f76f7c8da82d511655038891d6b3778b9b1dc895d58.json
similarity index 87%
rename from .sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json
rename to .sqlx/query-d68ac2f747c41c83b3f68f76f7c8da82d511655038891d6b3778b9b1dc895d58.json
index bd308439c0..7a06fe272b 100644
--- a/.sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json
+++ b/.sqlx/query-d68ac2f747c41c83b3f68f76f7c8da82d511655038891d6b3778b9b1dc895d58.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE id = $1\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n FROM forms WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -141,8 +151,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7"
+ "hash": "d68ac2f747c41c83b3f68f76f7c8da82d511655038891d6b3778b9b1dc895d58"
}
diff --git a/.sqlx/query-daede917c65e32ebeb521d85c0322b99127004ee8172cc107a0bb28aec2afdb3.json b/.sqlx/query-daede917c65e32ebeb521d85c0322b99127004ee8172cc107a0bb28aec2afdb3.json
new file mode 100644
index 0000000000..000fccdb83
--- /dev/null
+++ b/.sqlx/query-daede917c65e32ebeb521d85c0322b99127004ee8172cc107a0bb28aec2afdb3.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT f.anonymous <> $2 AND EXISTS (\n SELECT 1 FROM form_responses\n WHERE form_id = f.id AND status = 'submitted'\n ) AS \"locked!\"\n FROM forms f WHERE f.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "locked!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "daede917c65e32ebeb521d85c0322b99127004ee8172cc107a0bb28aec2afdb3"
+}
diff --git a/.sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json b/.sqlx/query-e6f05b9d1442f41f8000823fcd934804d24d2a893203d95a48fd5723ff826795.json
similarity index 89%
rename from .sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json
rename to .sqlx/query-e6f05b9d1442f41f8000823fcd934804d24d2a893203d95a48fd5723ff826795.json
index 816ec1d12e..016d800223 100644
--- a/.sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json
+++ b/.sqlx/query-e6f05b9d1442f41f8000823fcd934804d24d2a893203d95a48fd5723ff826795.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET updated_at = $2\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
+ "query": "\n UPDATE forms SET updated_at = $2\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -142,8 +152,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c"
+ "hash": "e6f05b9d1442f41f8000823fcd934804d24d2a893203d95a48fd5723ff826795"
}
diff --git a/.sqlx/query-f813ae457fcfd45630232c6256878f992c5940fa685326e4b5234f05f29be8a9.json b/.sqlx/query-f813ae457fcfd45630232c6256878f992c5940fa685326e4b5234f05f29be8a9.json
new file mode 100644
index 0000000000..1456cf2970
--- /dev/null
+++ b/.sqlx/query-f813ae457fcfd45630232c6256878f992c5940fa685326e4b5234f05f29be8a9.json
@@ -0,0 +1,61 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO form_responses (id, form_id, row_id, status, submitted_at, updated_at)\n VALUES ($1, $2, $3, 'submitted', $4, $4)\n RETURNING id, form_id, status, stopped_at_section, row_id, submitted_at, updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "form_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "stopped_at_section",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "row_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "submitted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "f813ae457fcfd45630232c6256878f992c5940fa685326e4b5234f05f29be8a9"
+}
diff --git a/.sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json b/.sqlx/query-fde092e1c4c55a6a4b7770b56f947d78a5d2a70eb11c3fcb64e2c3a4b0804492.json
similarity index 85%
rename from .sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json
rename to .sqlx/query-fde092e1c4c55a6a4b7770b56f947d78a5d2a70eb11c3fcb64e2c3a4b0804492.json
index 0904b176a0..ae7a2ecc38 100644
--- a/.sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json
+++ b/.sqlx/query-fde092e1c4c55a6a4b7770b56f947d78a5d2a70eb11c3fcb64e2c3a4b0804492.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE id = ANY($1) AND trashed_at IS NULL\n ORDER BY id\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous\n FROM forms WHERE id = ANY($1) AND trashed_at IS NULL\n ORDER BY id\n ",
"describe": {
"columns": [
{
@@ -112,6 +112,16 @@
"ordinal": 21,
"name": "project_id",
"type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "responses_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 23,
+ "name": "anonymous",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -141,8 +151,10 @@
true,
false,
false,
- true
+ true,
+ false,
+ false
]
},
- "hash": "a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b"
+ "hash": "fde092e1c4c55a6a4b7770b56f947d78a5d2a70eb11c3fcb64e2c3a4b0804492"
}
diff --git a/Cargo.lock b/Cargo.lock
index f9537ba582..ff862373e8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8533,6 +8533,7 @@ dependencies = [
"tokio",
"tower 0.5.3",
"tracing",
+ "tracing-subscriber",
"utoipa",
"uuid",
"workspace-hack",
diff --git a/apps/docs/AI/mcp/tools/set-form-access.mdx b/apps/docs/AI/mcp/tools/set-form-access.mdx
index e3afcaaf65..751ef73c6e 100644
--- a/apps/docs/AI/mcp/tools/set-form-access.mdx
+++ b/apps/docs/AI/mcp/tools/set-form-access.mdx
@@ -6,7 +6,7 @@ description: >-
# SetFormAccess
-Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Public allows anonymous responses. View allows responding without database access; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open.
+Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Optional responsesVisible lets View holders read response rows; optional anonymous makes the form anonymous to everyone, its owner included (who responded is kept apart from the responses), and is refused once anyone has responded. Public allows anonymous responses. View allows responding without database access unless responses are shared; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open.
## Parameters
diff --git a/apps/web/src/features/block-form/components/poll/poll-bars.tsx b/apps/web/src/features/block-form/components/poll/poll-bars.tsx
index ff9cbde4ec..7561f18142 100644
--- a/apps/web/src/features/block-form/components/poll/poll-bars.tsx
+++ b/apps/web/src/features/block-form/components/poll/poll-bars.tsx
@@ -2,7 +2,7 @@ import CheckCircle from '@icon/system/fill/check-circle-fill.svg';
import Circle from '@icon/system/regular/circle.svg';
import { Key } from '@solid-primitives/keyed';
import { cn } from '@ui';
-import { For, Show } from 'solid-js';
+import { For, type JSX, Show } from 'solid-js';
import type { PollBar } from '../../core/tally';
/**
@@ -154,7 +154,7 @@ export function PollBars(props: {
type="button"
aria-expanded={results().expanded}
class="ml-auto shrink-0 rounded text-link outline-none hover:underline focus-visible:ring-2 focus-visible:ring-edge-focus"
- onClick={results().onOpen}
+ onClick={() => results().onOpen()}
>
{results().label}
</button>
@@ -165,38 +165,69 @@ export function PollBars(props: {
);
}
-/** The tally spelled out, for respondents who cannot open the responses. */
+/**
+ * Who voted for what: each option with the people who chose it, the viewer
+ * marked as "you". Shown only when the tally names voters to this viewer.
+ */
export function PollResults(props: {
+ ref?: (element: HTMLElement) => void;
bars: readonly PollBar[];
- summary: string;
+ /** The viewer, marked among the voters. */
+ viewerId: string | undefined;
+ renderPerson: (userId: string) => JSX.Element;
+ /** Open the full Responses table. */
+ onOpenResponses?: () => void;
}) {
return (
<section
+ ref={props.ref}
aria-label="Poll results"
- class="rounded-lg border border-edge-muted bg-panel px-3 py-2"
+ class="flex flex-col gap-3 rounded-lg border border-edge-muted bg-panel px-3 py-2.5"
>
- <table class="w-full text-xs">
- <caption class="sr-only">Votes per option</caption>
- <tbody>
- <For each={props.bars}>
- {(bar) => (
- <tr>
- <th scope="row" class="py-0.5 text-left font-normal text-ink">
- {bar.label}
- <Show when={bar.mine}>
- <span class="ml-1 text-ink-muted">(your vote)</span>
- </Show>
- </th>
- <td class="py-0.5 text-right text-ink-muted tabular-nums">
- {bar.count === 1 ? '1 vote' : `${bar.count} votes`} ·{' '}
- {bar.percent}%
- </td>
- </tr>
- )}
- </For>
- </tbody>
- </table>
- <p class="mt-1 text-[11px] text-ink-muted">{props.summary}</p>
+ <For each={props.bars}>
+ {(bar) => (
+ <div class="flex flex-col gap-1.5">
+ <div class="flex items-baseline justify-between gap-2 text-xs">
+ <span class="min-w-0 font-medium text-ink wrap-anywhere">
+ {bar.label}
+ </span>
+ <span class="shrink-0 text-ink-muted tabular-nums">
+ {bar.count === 1 ? '1 vote' : `${bar.count} votes`}
+ </span>
+ </div>
+ <Show
+ when={(bar.voters ?? []).length > 0}
+ fallback={<p class="text-xs text-ink-muted">No votes yet</p>}
+ >
+ <ul class="flex flex-col gap-1 text-xs text-ink">
+ <For each={bar.voters}>
+ {(voter) => (
+ <li class="flex min-w-0 items-center gap-1.5">
+ {props.renderPerson(voter)}
+ <Show when={voter === props.viewerId}>
+ <span class="shrink-0 text-ink-muted">(you)</span>
+ </Show>
+ </li>
+ )}
+ </For>
+ </ul>
+ </Show>
+ </div>
+ )}
+ </For>
+ <Show when={props.onOpenResponses}>
+ {(open) => (
+ <div class="flex justify-end border-t border-edge-divider pt-2 text-[11px]">
+ <button
+ type="button"
+ class="text-accent-ink hover:underline"
+ onClick={() => open()()}
+ >
+ Responses table
+ </button>
+ </div>
+ )}
+ </Show>
</section>
);
}
diff --git a/apps/web/src/features/block-form/components/poll/poll-composer.test.tsx b/apps/web/src/features/block-form/components/poll/poll-composer.test.tsx
index fc6ed98fb0..8763894f24 100644
--- a/apps/web/src/features/block-form/components/poll/poll-composer.test.tsx
+++ b/apps/web/src/features/block-form/components/poll/poll-composer.test.tsx
@@ -43,12 +43,16 @@ describe('PollComposer', () => {
});
fireEvent.click(screen.getByLabelText('Multiple answers'));
fireEvent.click(screen.getByLabelText('Show results to respondents'));
+ fireEvent.click(screen.getByLabelText('Share responses with team'));
+ fireEvent.click(screen.getByLabelText('Anonymous'));
fireEvent.submit(screen.getByRole('form', { name: 'New poll' }));
expect(post).toHaveBeenCalledWith({
question: 'Where should we meet?',
options: ['Office', 'Cafe', 'Online'],
multi: true,
showResults: false,
+ shareResponses: true,
+ anonymous: true,
});
});
diff --git a/apps/web/src/features/block-form/components/poll/poll-composer.tsx b/apps/web/src/features/block-form/components/poll/poll-composer.tsx
index e664ad897e..504c58cc73 100644
--- a/apps/web/src/features/block-form/components/poll/poll-composer.tsx
+++ b/apps/web/src/features/block-form/components/poll/poll-composer.tsx
@@ -10,11 +10,14 @@ export type PollComposerDraft = {
options: string[];
multi: boolean;
showResults: boolean;
+ shareResponses: boolean;
+ anonymous: boolean;
};
/**
* The `/poll` composer: a question, two options to start with and Add
- * option, Multiple answers, and Show results to respondents (on by default).
+ * option, Multiple answers, Show results to respondents (on by default),
+ * Share responses with team, and Anonymous.
*/
export function PollComposer(props: {
pending: boolean;
@@ -26,6 +29,8 @@ export function PollComposer(props: {
const [options, setOptions] = createSignal(['', '']);
const [multi, setMulti] = createSignal(false);
const [showResults, setShowResults] = createSignal(true);
+ const [shareResponses, setShareResponses] = createSignal(false);
+ const [anonymous, setAnonymous] = createSignal(false);
const optionInputs: HTMLInputElement[] = [];
const focusOption = (index: number) =>
queueMicrotask(() => optionInputs[index]?.focus());
@@ -46,6 +51,8 @@ export function PollComposer(props: {
options: options(),
multi: multi(),
showResults: showResults(),
+ shareResponses: shareResponses(),
+ anonymous: anonymous(),
});
}}
>
@@ -151,6 +158,30 @@ export function PollComposer(props: {
: 'Only you and other editors can see the counts.'}
</p>
</div>
+ <div class="flex flex-col gap-1.5">
+ <Checkbox checked={shareResponses()} onChange={setShareResponses}>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm">
+ Share responses with team
+ </Checkbox.Label>
+ </Checkbox>
+ <p class="pl-6 text-xs leading-5 text-ink-muted">
+ {shareResponses()
+ ? 'Everyone who can vote can also see each response.'
+ : 'Only you and other editors can open the Responses table.'}
+ </p>
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <Checkbox checked={anonymous()} onChange={setAnonymous}>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm">Anonymous</Checkbox.Label>
+ </Checkbox>
+ <p class="pl-6 text-xs leading-5 text-ink-muted">
+ {anonymous()
+ ? 'Nobody in Macro, you included, can see who voted for what. People can still only vote once, and can’t change their vote.'
+ : 'Each response names who voted.'}
+ </p>
+ </div>
</div>
</fieldset>
<Show when={props.error}>
diff --git a/apps/web/src/features/block-form/context/form-context.tsx b/apps/web/src/features/block-form/context/form-context.tsx
index 9a9148acf6..2ce9f3941d 100644
--- a/apps/web/src/features/block-form/context/form-context.tsx
+++ b/apps/web/src/features/block-form/context/form-context.tsx
@@ -42,6 +42,7 @@ export type FormRefusal =
| 'table-already-has-form'
| 'already-responded'
| 'no-response'
+ | 'anonymous-response-final'
| 'unknown-question'
| 'repeated-answer'
| 'missing-answer'
@@ -181,6 +182,8 @@ export type FormMetadataPatch = {
status?: FormStatus;
closesAt?: string | null;
tallyVisible?: boolean;
+ responsesVisible?: boolean;
+ anonymous?: boolean;
/** A static file id, or `null` to remove it. */
logoFileId?: string | null;
/** A static file id, or `null` to remove it. */
@@ -201,10 +204,16 @@ export type SubmitOutcome =
/** The viewer's own response: `null` before they respond. */
export type MyResponse = {
status: 'submitted' | 'stopped';
- submittedAt: string;
+ /** Unknown for a response to an anonymous form. */
+ submittedAt: string | undefined;
answers: SubmittedAnswer[];
/** The booking step, while the saved answers still pass the form's gates. */
booking: UnlockedBooking | null;
+ /**
+ * Responded to an anonymous form: nothing links the response to the
+ * viewer, so its answers and time aren't known and it can't change.
+ */
+ anonymous?: true;
};
export type MyResponseSource = {
@@ -217,7 +226,13 @@ export type QuestionTally = {
questionId: string;
responses: number;
buckets: (
- | { kind: 'option'; optionId: string; count: number }
+ | {
+ kind: 'option';
+ optionId: string;
+ count: number;
+ /** Who chose it, as user ids; absent when the viewer may not see voters. */
+ voters?: string[];
+ }
| { kind: 'checkbox'; checked: boolean; count: number }
)[];
};
@@ -292,6 +307,8 @@ export type EditorsProps = {
export type ResponsesGridProps = {
databaseId: string;
tableId: string;
+ /** Hide this column, as when the form withholds who responded. */
+ hideColumnId?: string | null;
};
/**
@@ -389,6 +406,8 @@ export type FormContext = {
renderEntityLabel: (entity: FormEntityReference) => JSX.Element;
/** The other editors who selected something, as the app shows people. */
renderEditors: (props: EditorsProps) => JSX.Element;
+ /** A person's avatar and name, as the app shows people. */
+ renderPerson: (userId: string) => JSX.Element;
};
};
diff --git a/apps/web/src/features/block-form/core/form-model.ts b/apps/web/src/features/block-form/core/form-model.ts
index 156dad0e2a..6397d081c4 100644
--- a/apps/web/src/features/block-form/core/form-model.ts
+++ b/apps/web/src/features/block-form/core/form-model.ts
@@ -16,7 +16,7 @@ export type FormAudience = 'members' | 'public';
export type FormStatus = 'open' | 'closed';
-/** What the viewer may do: view = respond; edit = build, and edit responses (edit on the linked database). */
+/** What the viewer may do: view = respond (and read shared responses); edit = build, and edit responses (edit on the linked database). */
export type FormAccess = 'view' | 'edit' | 'owner';
export type SectionKind = 'questions' | 'gate' | 'booking';
@@ -213,6 +213,8 @@ export type FormMetadata = {
status: FormStatus;
closesAt: string | null;
tallyVisible: boolean;
+ responsesVisible: boolean;
+ anonymous: boolean;
confirmationMessage: string;
branding: FormBranding;
submittedColumnId: string | null;
diff --git a/apps/web/src/features/block-form/core/sentences.test.ts b/apps/web/src/features/block-form/core/sentences.test.ts
index ec61ccfd93..db613ace9a 100644
--- a/apps/web/src/features/block-form/core/sentences.test.ts
+++ b/apps/web/src/features/block-form/core/sentences.test.ts
@@ -77,6 +77,8 @@ describe('availability', () => {
status: 'open',
closesAt: '2026-10-03T17:00:00Z',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/core/tally.test.ts b/apps/web/src/features/block-form/core/tally.test.ts
index 3b820d1dc5..c760e8b5fe 100644
--- a/apps/web/src/features/block-form/core/tally.test.ts
+++ b/apps/web/src/features/block-form/core/tally.test.ts
@@ -14,6 +14,8 @@ const lunch: FormDetail = {
status: 'open',
closesAt: null,
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/core/tally.ts b/apps/web/src/features/block-form/core/tally.ts
index 2faf615a1d..410b1e960c 100644
--- a/apps/web/src/features/block-form/core/tally.ts
+++ b/apps/web/src/features/block-form/core/tally.ts
@@ -27,6 +27,8 @@ export type PollBar = {
/** Share of the votes, 0–100, rounded. */
percent: number;
mine: boolean;
+ /** Who chose it, as user ids; absent when the viewer may not see voters. */
+ voters?: readonly string[];
};
/** One bar per option, in option order, zero counts included. */
@@ -34,7 +36,8 @@ export function pollBars(
poll: Poll,
counts: ReadonlyMap<string, number> | undefined,
responses: number,
- mine: readonly string[]
+ mine: readonly string[],
+ voters?: ReadonlyMap<string, readonly string[]>
): PollBar[] {
return poll.column.options.map((option) => {
const count = counts?.get(option.id) ?? 0;
@@ -44,6 +47,7 @@ export function pollBars(
count,
percent: responses > 0 ? Math.round((count / responses) * 100) : 0,
mine: mine.includes(option.id),
+ voters: voters ? (voters.get(option.id) ?? []) : undefined,
};
});
}
diff --git a/apps/web/src/features/block-form/form-block.test.tsx b/apps/web/src/features/block-form/form-block.test.tsx
index 736a17597d..f5f36abaa9 100644
--- a/apps/web/src/features/block-form/form-block.test.tsx
+++ b/apps/web/src/features/block-form/form-block.test.tsx
@@ -101,6 +101,8 @@ beforeEach(() => {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: 'Thank you',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/form-context-production.tsx b/apps/web/src/features/block-form/form-context-production.tsx
index 733de79802..73b03b9e46 100644
--- a/apps/web/src/features/block-form/form-context-production.tsx
+++ b/apps/web/src/features/block-form/form-context-production.tsx
@@ -27,7 +27,7 @@ import { errAsync, ResultAsync } from 'neverthrow';
import type { DatabaseRelatedDestination } from '../database/core/database-relations';
import type { FormContext, FormWriteFailure } from './context/form-context';
import { FormConditionEditor } from './form-condition-editor';
-import { FormEditors } from './form-editors';
+import { FormEditors, FormPerson } from './form-editors';
import { FormEntityPicker, FormRelationPicker } from './form-pickers';
import { FormResponsesGrid } from './form-responses-grid';
import {
@@ -174,6 +174,7 @@ export function createAppFormContext(host: FormHostActions): FormContext {
<FormResponsesGrid
databaseId={props.databaseId}
tableId={props.tableId}
+ hideColumnId={props.hideColumnId}
onOpenRelated={host.openRelated}
/>
),
@@ -184,6 +185,7 @@ export function createAppFormContext(host: FormHostActions): FormContext {
/>
),
renderEditors: (props) => <FormEditors {...props} />,
+ renderPerson: (userId) => <FormPerson userId={userId} />,
},
};
}
diff --git a/apps/web/src/features/block-form/form-editors.tsx b/apps/web/src/features/block-form/form-editors.tsx
index 5097d4e410..b9cc8c6db8 100644
--- a/apps/web/src/features/block-form/form-editors.tsx
+++ b/apps/web/src/features/block-form/form-editors.tsx
@@ -43,3 +43,13 @@ export function FormEditors(props: EditorsProps) {
</AvatarGroup>
);
}
+
+/** A person as the app shows people: their avatar and name. */
+export function FormPerson(props: { userId: string }) {
+ return (
+ <span class="flex min-w-0 items-center gap-1.5">
+ <UserIcon id={props.userId} size="sm" suppressClick />
+ <span class="truncate">{nameOf(props.userId)}</span>
+ </span>
+ );
+}
diff --git a/apps/web/src/features/block-form/form-global-sharing.test.tsx b/apps/web/src/features/block-form/form-global-sharing.test.tsx
index bd7e5db99f..ac046207ee 100644
--- a/apps/web/src/features/block-form/form-global-sharing.test.tsx
+++ b/apps/web/src/features/block-form/form-global-sharing.test.tsx
@@ -73,6 +73,8 @@ function rsvp(access: FormDetail['access']): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
@@ -201,6 +203,8 @@ describe('openFormShareModal', () => {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/form-responses-grid.tsx b/apps/web/src/features/block-form/form-responses-grid.tsx
index 54c4fd6218..ece55eae12 100644
--- a/apps/web/src/features/block-form/form-responses-grid.tsx
+++ b/apps/web/src/features/block-form/form-responses-grid.tsx
@@ -15,14 +15,24 @@ import { allRecordsView } from '../database/core/views';
export function FormResponsesGrid(props: {
databaseId: string;
tableId: string;
+ hideColumnId?: string | null;
onOpenRelated: (destination: DatabaseRelatedDestination) => void;
}) {
useDatabaseTableChangedSync(() => props.databaseId);
const detail = useDatabaseDetailQuery(() => props.databaseId);
- const table = () =>
- detail.isSuccess
- ? detail.data.tables.find((entry) => entry.table.id === props.tableId)
- : undefined;
+ const table = () => {
+ if (!detail.isSuccess) return undefined;
+ const found = detail.data.tables.find(
+ (entry) => entry.table.id === props.tableId
+ );
+ if (!found || !props.hideColumnId) return found;
+ return {
+ ...found,
+ columns: found.columns.filter(
+ (column) => column.column.id !== props.hideColumnId
+ ),
+ };
+ };
const canEdit = () =>
detail.isSuccess &&
(detail.data.grant === 'edit' || detail.data.grant === 'owner');
diff --git a/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts b/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
index 8a1ab2ba3e..e12d18c9c7 100644
--- a/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
@@ -48,6 +48,8 @@ function detail(layout: FormLayout): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/primitives/create-builder.test.ts b/apps/web/src/features/block-form/primitives/create-builder.test.ts
index 1bd5c37b61..ce7a396a29 100644
--- a/apps/web/src/features/block-form/primitives/create-builder.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder.test.ts
@@ -38,6 +38,8 @@ function detail(layout: FormLayout): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: 'column-submitted',
diff --git a/apps/web/src/features/block-form/primitives/create-poll-voting.test.ts b/apps/web/src/features/block-form/primitives/create-poll-voting.test.ts
index 138be99305..a39963ee8c 100644
--- a/apps/web/src/features/block-form/primitives/create-poll-voting.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-poll-voting.test.ts
@@ -38,12 +38,59 @@ const tally: QuestionTally[] = [
];
describe('createPollVoting', () => {
+ it('keeps a vote on an anonymous poll final, and refuses a second one without editing', async () => {
+ const calls: string[] = [];
+ const notices: string[] = [];
+ await createRoot(async (dispose) => {
+ const [mine, setMine] = createSignal<MyResponse | null>(null);
+ const voting = createPollVoting({
+ poll: () => poll,
+ anonymous: () => true,
+ mine,
+ tally: () => tally,
+ submit: () => {
+ calls.push('POST');
+ return errAsync({
+ message: 'you already responded',
+ refusal: 'already-responded',
+ });
+ },
+ editMine: () => {
+ calls.push('PUT');
+ return okAsync({
+ kind: 'submitted',
+ responseId: 'response',
+ booking: null,
+ });
+ },
+ notify: (message) => notices.push(message),
+ });
+ await voting.vote('tacos');
+ expect(calls).toEqual(['POST']);
+ expect(notices).toEqual(['You already voted in this anonymous poll.']);
+ expect(voting.voted()).toBe(true);
+ expect(voting.final()).toBe(true);
+ setMine({
+ status: 'submitted',
+ booking: null,
+ submittedAt: undefined,
+ answers: [],
+ anonymous: true,
+ });
+ await voting.vote('pho');
+ expect(calls).toEqual(['POST']);
+ expect(voting.myVote()).toEqual([]);
+ dispose();
+ });
+ });
+
it('casts a first vote as a submission, then changes it by editing the response', async () => {
const calls: [string, SubmittedAnswer[]][] = [];
await createRoot(async (dispose) => {
const [mine, setMine] = createSignal<MyResponse | null>(null);
const voting = createPollVoting({
poll: () => poll,
+ anonymous: () => false,
mine,
tally: () => tally,
submit: (answers) => {
@@ -115,6 +162,7 @@ describe('createPollVoting', () => {
await createRoot(async (dispose) => {
const voting = createPollVoting({
poll: () => poll,
+ anonymous: () => false,
mine: () => null,
tally: () => undefined,
submit: () =>
diff --git a/apps/web/src/features/block-form/primitives/create-poll-voting.ts b/apps/web/src/features/block-form/primitives/create-poll-voting.ts
index 2455f139cd..5efec994be 100644
--- a/apps/web/src/features/block-form/primitives/create-poll-voting.ts
+++ b/apps/web/src/features/block-form/primitives/create-poll-voting.ts
@@ -11,10 +11,12 @@ import { type Poll, type PollBar, pollBars, pollSummary } from '../core/tally';
/**
* Voting on a poll: a vote is a submission, changing it edits the viewer's
- * response. Results come from the tally, refreshed as votes land.
+ * response. Results come from the tally, refreshed as votes land. A vote on
+ * an anonymous poll is final, and which option it was isn't known after.
*/
export function createPollVoting(options: {
poll: Accessor<Poll>;
+ anonymous: Accessor<boolean>;
mine: Accessor<MyResponse | null | undefined>;
tally: Accessor<QuestionTally[] | undefined>;
submit: (
@@ -28,6 +30,8 @@ export function createPollVoting(options: {
/** The vote as just cast, ahead of the stored response being read again. */
const [cast, setCast] = createSignal<string[]>();
const [pending, setPending] = createSignal(false);
+ /** The server refused a vote on an anonymous poll this viewer voted in. */
+ const [votedElsewhere, setVotedElsewhere] = createSignal(false);
const stored = (): string[] => {
const mine = options.mine();
@@ -41,7 +45,10 @@ export function createPollVoting(options: {
);
};
const myVote = () => cast() ?? stored();
- const voted = () => myVote().length > 0;
+ const voted = () =>
+ myVote().length > 0 || !!options.mine()?.anonymous || votedElsewhere();
+ /** Voted on an anonymous poll, so the vote can't change. */
+ const final = () => options.anonymous() && voted();
const questionTally = () =>
options
.tally()
@@ -57,10 +64,20 @@ export function createPollVoting(options: {
)
);
};
+ /** Who chose each option, when the tally names voters to this viewer. */
+ const voters = () => {
+ const tally = questionTally();
+ const named = tally?.buckets.flatMap((bucket) =>
+ bucket.kind === 'option' && bucket.voters
+ ? [[bucket.optionId, bucket.voters] as const]
+ : []
+ );
+ return named && named.length > 0 ? new Map(named) : undefined;
+ };
const responses = () => questionTally()?.responses ?? 0;
async function vote(optionId: string) {
- if (pending()) return;
+ if (pending() || final()) return;
const poll = options.poll();
const current = myVote();
const next = poll.multi
@@ -83,8 +100,16 @@ export function createPollVoting(options: {
let result = await (editing
? options.editMine(answers)
: options.submit(answers));
- if (result.isErr() && result.error.refusal === 'already-responded')
+ if (result.isErr() && result.error.refusal === 'already-responded') {
+ if (options.anonymous()) {
+ setPending(false);
+ setCast(undefined);
+ setVotedElsewhere(true);
+ options.notify('You already voted in this anonymous poll.');
+ return;
+ }
result = await options.editMine(answers);
+ }
setPending(false);
if (result.isErr()) {
setCast(undefined);
@@ -100,11 +125,14 @@ export function createPollVoting(options: {
return {
myVote,
voted,
+ final,
pending,
vote,
bars: (): PollBar[] =>
- pollBars(options.poll(), counts(), responses(), myVote()),
+ pollBars(options.poll(), counts(), responses(), myVote(), voters()),
summary: () => pollSummary(responses(), options.poll().multi),
hasTally: () => !!questionTally(),
+ /** Whether the tally says who voted for what. */
+ hasVoters: () => !!voters(),
};
}
diff --git a/apps/web/src/features/block-form/primitives/create-respond.test.ts b/apps/web/src/features/block-form/primitives/create-respond.test.ts
index ebb98603d7..eee630324a 100644
--- a/apps/web/src/features/block-form/primitives/create-respond.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-respond.test.ts
@@ -23,6 +23,8 @@ function offsite(): FormDetail {
status: 'open',
closesAt: '2026-10-03T17:00:00Z',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: 'See you there.',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
@@ -132,6 +134,8 @@ describe('createRespond', () => {
status: 'closed',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: 'See you there.',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/primitives/create-respond.ts b/apps/web/src/features/block-form/primitives/create-respond.ts
index 9df0886337..5080676bb8 100644
--- a/apps/web/src/features/block-form/primitives/create-respond.ts
+++ b/apps/web/src/features/block-form/primitives/create-respond.ts
@@ -148,7 +148,11 @@ export function createRespond(options: RespondOptions) {
);
// Signed in, on either audience, a respondent keeps their identity and can
// edit while the form is open; anonymous visitors cannot.
- const canEdit = () => options.signedIn() && availability().kind === 'open';
+ // A response to an anonymous form is final.
+ const canEdit = () =>
+ options.signedIn() &&
+ availability().kind === 'open' &&
+ !options.detail().form.anonymous;
const firstSectionIndex = () => {
const step = nextStep(layout(), -1, answers());
diff --git a/apps/web/src/features/block-form/queries/form-detail.test.ts b/apps/web/src/features/block-form/queries/form-detail.test.ts
index 4bed6047b6..60b0b8eee6 100644
--- a/apps/web/src/features/block-form/queries/form-detail.test.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.test.ts
@@ -113,6 +113,8 @@ describe('the booking step', () => {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
@@ -258,6 +260,7 @@ describe('the booking step', () => {
).toEqual({ kind: 'stopped', sectionId: 'fit', message: 'Not a fit yet.' });
expect(
toMyResponse({
+ kind: 'saved',
response: {
id: 'response-1',
formId: 'form-1',
diff --git a/apps/web/src/features/block-form/queries/form-detail.ts b/apps/web/src/features/block-form/queries/form-detail.ts
index 61fd2ed524..9ea7d2f643 100644
--- a/apps/web/src/features/block-form/queries/form-detail.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.ts
@@ -32,6 +32,8 @@ export function toFormMetadata(form: Form): FormMetadata {
status: form.status,
closesAt: form.closesAt ?? null,
tallyVisible: form.tallyVisible,
+ responsesVisible: form.responsesVisible,
+ anonymous: form.anonymous,
confirmationMessage: form.confirmationMessage,
branding: {
logoFileId: form.branding.logoFileId ?? null,
@@ -276,6 +278,15 @@ export function toSubmitOutcome(outcome: SubmissionOutcome): SubmitOutcome {
}
export function toMyResponse(mine: WireMyResponse): MyResponse {
+ if (mine.kind === 'anonymous')
+ return {
+ status: 'submitted',
+ submittedAt: undefined,
+ answers: [],
+ booking: null,
+ anonymous: true,
+ };
+ // Before `kind`, the service sent only saved responses.
return {
status: mine.response.status,
submittedAt: mine.response.submittedAt,
diff --git a/apps/web/src/features/block-form/queries/form-publication.test.ts b/apps/web/src/features/block-form/queries/form-publication.test.ts
index cb04733f57..f3a53c7ae8 100644
--- a/apps/web/src/features/block-form/queries/form-publication.test.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.test.ts
@@ -14,6 +14,8 @@ const detail: FormCollaboration['detail'] = {
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: 'Thank you',
diff --git a/apps/web/src/features/block-form/queries/form-sources.test.ts b/apps/web/src/features/block-form/queries/form-sources.test.ts
index e233818b87..93e9836b3e 100644
--- a/apps/web/src/features/block-form/queries/form-sources.test.ts
+++ b/apps/web/src/features/block-form/queries/form-sources.test.ts
@@ -39,6 +39,8 @@ vi.mock('@queries/storage/forms', () => ({
status: 'open',
closesAt: null,
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/queries/form-sources.ts b/apps/web/src/features/block-form/queries/form-sources.ts
index 590ead78bc..0e49a0be79 100644
--- a/apps/web/src/features/block-form/queries/form-sources.ts
+++ b/apps/web/src/features/block-form/queries/form-sources.ts
@@ -89,6 +89,7 @@ function refusalOf(code: FormErrorCode): FormRefusal {
.with('tableAlreadyHasForm', () => 'table-already-has-form')
.with('alreadyResponded', () => 'already-responded')
.with('noResponse', () => 'no-response')
+ .with('anonymousResponseFinal', () => 'anonymous-response-final')
.with('unknownQuestion', () => 'unknown-question')
.with('repeatedAnswer', () => 'repeated-answer')
.with('missingAnswer', () => 'missing-answer')
@@ -282,7 +283,12 @@ export function createTallySource(
match(bucket.value)
.returnType<QuestionTally['buckets']>()
.with({ kind: 'option' }, ({ option }) => [
- { kind: 'option', optionId: option, count: bucket.count },
+ {
+ kind: 'option',
+ optionId: option,
+ count: bucket.count,
+ voters: bucket.voters ?? undefined,
+ },
])
.with({ kind: 'checkbox' }, ({ checked }) => [
{ kind: 'checkbox', checked, count: bucket.count },
diff --git a/apps/web/src/features/block-form/queries/publish-poll.test.ts b/apps/web/src/features/block-form/queries/publish-poll.test.ts
index 5792949b1d..ea86eb4253 100644
--- a/apps/web/src/features/block-form/queries/publish-poll.test.ts
+++ b/apps/web/src/features/block-form/queries/publish-poll.test.ts
@@ -22,15 +22,15 @@ const storage = vi.hoisted(() => ({
createForm: vi.fn(),
putFormLayout: vi.fn(),
updateForm: vi.fn(),
- applyDatabaseOps: vi.fn(),
+ createDatabaseColumn: vi.fn(),
}));
vi.mock('@queries/storage/forms', () => ({
createForm: storage.createForm,
putFormLayout: storage.putFormLayout,
updateForm: storage.updateForm,
}));
-vi.mock('@queries/storage/databases', () => ({
- applyDatabaseOps: storage.applyDatabaseOps,
+vi.mock('@block-database/queries/columns', () => ({
+ createDatabaseColumn: storage.createDatabaseColumn,
}));
const draft = {
@@ -38,6 +38,8 @@ const draft = {
options: ['Pizza', 'Salad'],
multi: false,
showResults: true,
+ shareResponses: false,
+ anonymous: false,
};
function created(sections: { id: string; kind: string }[]) {
@@ -56,7 +58,7 @@ describe('publishPoll', () => {
storage.createForm.mockReturnValue(
created([{ id: 'section-1', kind: 'questions' }])
);
- storage.applyDatabaseOps.mockReturnValue(
+ storage.createDatabaseColumn.mockReturnValue(
errAsync({ code: 'INVALID_OP', message: 'No.' })
);
const discarded: string[] = [];
@@ -78,11 +80,43 @@ describe('publishPoll', () => {
expect(result._unsafeUnwrapErr().message).toBe(
'The new form has no section to hold the question.'
);
- expect(storage.applyDatabaseOps).not.toHaveBeenCalled();
+ expect(storage.createDatabaseColumn).not.toHaveBeenCalled();
expect(discarded).toEqual(['form-1']);
});
});
+it('creates an anonymous poll anonymous and patches tally and shared responses after the layout is valid', async () => {
+ storage.createForm.mockReturnValue(
+ created([{ id: 'section-1', kind: 'questions' }])
+ );
+ storage.createDatabaseColumn.mockReturnValue(okAsync('column-1'));
+ storage.putFormLayout.mockReturnValue(okAsync({ detail: { sections: [] } }));
+ storage.updateForm.mockReturnValue(okAsync(undefined));
+ const result = await publishPoll(
+ {
+ question: 'Lunch?',
+ options: ['Pizza', 'Salad'],
+ multi: false,
+ showResults: false,
+ shareResponses: true,
+ anonymous: true,
+ },
+ () => okAsync(undefined)
+ );
+ expect(result.isOk()).toBe(true);
+ expect(storage.createForm).toHaveBeenCalledWith(
+ {
+ name: 'Lunch?',
+ source: { kind: 'new', isHiddenInDrive: true, anonymous: true },
+ },
+ 'poll'
+ );
+ expect(storage.updateForm).toHaveBeenCalledWith('form-1', {
+ tallyVisible: false,
+ responsesVisible: true,
+ });
+});
+
it('rejects duplicate options without creating a form or silently dropping a choice', async () => {
const result = await publishPoll(
{
@@ -90,6 +124,8 @@ it('rejects duplicate options without creating a form or silently dropping a cho
options: ['Pizza', ' pizza ', 'Salad'],
multi: false,
showResults: true,
+ shareResponses: false,
+ anonymous: false,
},
() => okAsync(undefined)
);
diff --git a/apps/web/src/features/block-form/queries/publish-poll.ts b/apps/web/src/features/block-form/queries/publish-poll.ts
index d845064a54..fbfe50facd 100644
--- a/apps/web/src/features/block-form/queries/publish-poll.ts
+++ b/apps/web/src/features/block-form/queries/publish-poll.ts
@@ -2,7 +2,8 @@
* `/poll` (RFC 03 §3): a poll is a form with one required choice question.
* Create the form (and its database), add the Select column with the options
* under ids minted here, place it as the only question, and set whether
- * respondents see the results.
+ * respondents see the results. An anonymous poll is anonymous from creation,
+ * so its table never gets a Respondent column.
*/
import { createDatabaseColumn } from '@block-database/queries/columns';
import { createForm, putFormLayout, updateForm } from '@queries/storage/forms';
@@ -19,6 +20,8 @@ export type PollDraft = {
options: string[];
multi: boolean;
showResults: boolean;
+ shareResponses: boolean;
+ anonymous: boolean;
};
/** What a half-made poll leaves behind, for the caller to put in the trash. */
@@ -39,7 +42,14 @@ export function publishPoll(
if (labels.length < 2)
return errAsync({ message: 'Give at least two options.' });
return createForm(
- { name: question, source: { kind: 'new', isHiddenInDrive: true } },
+ {
+ name: question,
+ source: {
+ kind: 'new',
+ isHiddenInDrive: true,
+ anonymous: draft.anonymous,
+ },
+ },
'poll'
)
.mapErr(writeFailureOf)
@@ -97,9 +107,10 @@ export function publishPoll(
})
)
.andThen(() =>
- updateForm(formId, { tallyVisible: draft.showResults }).mapErr(
- writeFailureOf
- )
+ updateForm(formId, {
+ tallyVisible: draft.showResults,
+ responsesVisible: draft.shareResponses,
+ }).mapErr(writeFailureOf)
)
.orElse(abandon)
.map(() => ({
diff --git a/apps/web/src/features/block-form/tests/mock-context.ts b/apps/web/src/features/block-form/tests/mock-context.ts
index 08caa14bc1..70e5895a75 100644
--- a/apps/web/src/features/block-form/tests/mock-context.ts
+++ b/apps/web/src/features/block-form/tests/mock-context.ts
@@ -212,6 +212,7 @@ export function createMockFormContext(options: {
renderEntityLabel: (entity) => entity.entityId,
renderEditors: (props) =>
`${props.peers.map((peer) => peer.userId).join(', ')} on ${props.selected}`,
+ renderPerson: (userId) => userId,
},
...options.overrides,
};
diff --git a/apps/web/src/features/block-form/views/builder-view.test.tsx b/apps/web/src/features/block-form/views/builder-view.test.tsx
index 9982091535..4af975dff1 100644
--- a/apps/web/src/features/block-form/views/builder-view.test.tsx
+++ b/apps/web/src/features/block-form/views/builder-view.test.tsx
@@ -100,6 +100,8 @@ function rsvp(): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/views/form-card-view.test.tsx b/apps/web/src/features/block-form/views/form-card-view.test.tsx
index 34ca7de90a..ab150484bd 100644
--- a/apps/web/src/features/block-form/views/form-card-view.test.tsx
+++ b/apps/web/src/features/block-form/views/form-card-view.test.tsx
@@ -1,9 +1,16 @@
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { FormContext } from '../context/form-context';
+import type { FormContext, QuestionTally } from '../context/form-context';
import { FormProvider } from '../context/form-context';
import type { FormDetail } from '../core/form-model';
-import { createMockFormContext } from '../tests/mock-context';
+import { createMockFormContext, MOCK_VIEWER_ID } from '../tests/mock-context';
import { FormCardView } from './form-card-view';
afterEach(cleanup);
@@ -21,6 +28,8 @@ function lunchPoll(access: FormDetail['access']): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
@@ -64,23 +73,30 @@ function lunchPoll(access: FormDetail['access']): FormDetail {
};
}
-const tally: FormContext['responses']['createTally'] = () => ({
- value: () => [
- {
- questionId: 'question',
- responses: 4,
- buckets: [
- { kind: 'option', optionId: 'tacos', count: 3 },
- { kind: 'option', optionId: 'pho', count: 1 },
- ],
- },
- ],
- failure: () => undefined,
-});
+/** Three for tacos and one for pho, naming the voters when `voters` holds them. */
+function tallyOf(voters?: {
+ tacos: string[];
+ pho: string[];
+}): FormContext['responses']['createTally'] {
+ const buckets: QuestionTally['buckets'] = [
+ { kind: 'option', optionId: 'tacos', count: 3, voters: voters?.tacos },
+ { kind: 'option', optionId: 'pho', count: 1, voters: voters?.pho },
+ ];
+ return () => ({
+ value: () => [{ questionId: 'question', responses: 4, buckets }],
+ failure: () => undefined,
+ });
+}
+
+const namedVoters = {
+ tacos: ['macro|[email protected]', MOCK_VIEWER_ID, 'macro|[email protected]'],
+ pho: ['macro|[email protected]'],
+};
function mount(
access: FormDetail['access'],
- change: (detail: FormDetail) => void = () => {}
+ change: (detail: FormDetail) => void = () => {},
+ tally = tallyOf()
) {
const detail = lunchPoll(access);
change(detail);
@@ -117,25 +133,89 @@ describe('FormCardView poll', () => {
expect(screen.getByText('4 votes · one vote each')).toBeTruthy();
});
- it('shows respondents the tally in place behind Results', () => {
- const { onOpen, onOpenResponses } = mount('view');
+ it('offers respondents no Results when the bars already show everything they may see', () => {
+ mount('view');
+ expect(screen.queryByRole('button', { name: 'Results' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Responses' })).toBeNull();
+ });
+
+ it('shows who chose each option behind Results, marking the viewer', () => {
+ const { onOpen, onOpenResponses } = mount(
+ 'view',
+ (detail) => {
+ detail.form.responsesVisible = true;
+ },
+ tallyOf(namedVoters)
+ );
const results = screen.getByRole('button', { name: 'Results' });
expect(results.getAttribute('aria-expanded')).toBe('false');
fireEvent.click(results);
- expect(screen.getByRole('region', { name: 'Poll results' })).toBeTruthy();
- expect(screen.getByText('3 votes · 75%')).toBeTruthy();
+ const region = screen.getByRole('region', { name: 'Poll results' });
+ const tacos = within(region).getByText('3 votes').closest('div')
+ ?.parentElement as HTMLElement;
+ expect(within(tacos).getByText('macro|[email protected]')).toBeTruthy();
+ expect(within(tacos).getByText(MOCK_VIEWER_ID)).toBeTruthy();
+ expect(within(tacos).getByText('(you)')).toBeTruthy();
+ expect(within(region).getByText('macro|[email protected]')).toBeTruthy();
+ expect(within(region).getAllByText('(you)')).toHaveLength(1);
+ fireEvent.click(
+ within(region).getByRole('button', { name: 'Responses table' })
+ );
+ expect(onOpenResponses).toHaveBeenCalledTimes(1);
expect(onOpen).not.toHaveBeenCalled();
+ });
+
+ it('expands Results in place when the voters arrive after the card first renders', () => {
+ const [loaded, setLoaded] = createSignal(false);
+ const named = tallyOf(namedVoters)(
+ () => 'poll-1',
+ () => true
+ );
+ const late: FormContext['responses']['createTally'] = () => ({
+ value: () => (loaded() ? named.value() : undefined),
+ failure: () => undefined,
+ });
+ const { onOpenResponses } = mount(
+ 'view',
+ (detail) => {
+ detail.form.responsesVisible = true;
+ },
+ late
+ );
+ expect(screen.getByRole('button', { name: 'Responses' })).toBeTruthy();
+ setLoaded(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Results' }));
+ expect(screen.getByRole('region', { name: 'Poll results' })).toBeTruthy();
expect(onOpenResponses).not.toHaveBeenCalled();
});
- it('sends editors to the Responses tab', () => {
- const { onOpen, onOpenResponses } = mount('edit');
- expect(screen.queryByText('can edit')).toBeNull();
+ it('sends anyone to the Responses tab when shared responses name nobody', () => {
+ const { onOpen, onOpenResponses } = mount('view', (detail) => {
+ detail.form.responsesVisible = true;
+ detail.form.anonymous = true;
+ });
+ expect(screen.queryByRole('button', { name: 'Results' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Responses' }));
expect(onOpenResponses).toHaveBeenCalledTimes(1);
expect(onOpen).not.toHaveBeenCalled();
});
+ it('shows editors who voted for what behind Results', () => {
+ mount('edit', () => {}, tallyOf(namedVoters));
+ expect(screen.queryByText('can edit')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Results' }));
+ expect(screen.getByText('macro|[email protected]')).toBeTruthy();
+ });
+
+ it('sends editors of an anonymous poll to the Responses tab', () => {
+ const { onOpenResponses } = mount('edit', (detail) => {
+ detail.form.anonymous = true;
+ });
+ expect(screen.queryByRole('button', { name: 'Results' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Responses' }));
+ expect(onOpenResponses).toHaveBeenCalledTimes(1);
+ });
+
it('stops voting once the poll’s closing time has passed, and says it is closed', () => {
mount('view', (detail) => {
detail.form.closesAt = '2020-01-01T00:00:00Z';
diff --git a/apps/web/src/features/block-form/views/form-card-view.tsx b/apps/web/src/features/block-form/views/form-card-view.tsx
index 2b2b4d7997..96e49c58e3 100644
--- a/apps/web/src/features/block-form/views/form-card-view.tsx
+++ b/apps/web/src/features/block-form/views/form-card-view.tsx
@@ -11,9 +11,10 @@ import { createPollVoting } from '../primitives/create-poll-voting';
import { RespondView } from './respond-view';
/**
- * A poll's card body: vote and see the tally. "Responses" takes editors to
- * the Responses tab; respondents, who cannot read the table, see the tally
- * spelled out in place.
+ * A poll's card body: vote and see the tally. When the tally names voters
+ * (editors, or respondents of a poll that shares its responses, never an
+ * anonymous one), Results shows who chose each option; otherwise those who
+ * may read the responses get "Responses", the Responses tab.
*/
function PollCardBody(props: {
detail: FormDetail;
@@ -22,6 +23,8 @@ function PollCardBody(props: {
}) {
const context = useFormContext();
const isEditor = () => props.detail.access !== 'view';
+ const canReadResponses = () =>
+ isEditor() || props.detail.form.responsesVisible;
const [showingResults, setShowingResults] = createSignal(false);
const availability = () =>
formAvailability(props.detail.form, props.detail.tableGone, new Date());
@@ -33,6 +36,7 @@ function PollCardBody(props: {
);
const voting = createPollVoting({
poll: () => props.poll,
+ anonymous: () => props.detail.form.anonymous,
mine: mine.response,
tally: tally.value,
submit: (answers) =>
@@ -49,7 +53,7 @@ function PollCardBody(props: {
bars={voting.bars()}
showResults={voting.hasTally()}
multi={props.poll.multi}
- disabled={!context.viewer.userId() || !open()}
+ disabled={!context.viewer.userId() || !open() || voting.final()}
pending={voting.pending()}
summary={voting.summary()}
hiddenNote={
@@ -63,28 +67,49 @@ function PollCardBody(props: {
fireAndForget(voting.vote(optionId), 'poll-voting')
}
results={
- isEditor()
+ voting.hasVoters()
? {
- label: 'Responses',
- expanded: undefined,
- onOpen: props.onOpenResponses,
+ label: showingResults() ? 'Hide results' : 'Results',
+ expanded: showingResults(),
+ onOpen: () => setShowingResults(!showingResults()),
}
- : voting.hasTally()
+ : canReadResponses()
? {
- label: showingResults() ? 'Hide results' : 'Results',
- expanded: showingResults(),
- onOpen: () => setShowingResults(!showingResults()),
+ label: 'Responses',
+ expanded: undefined,
+ onOpen: props.onOpenResponses,
}
: undefined
}
/>
+ <Show when={props.detail.form.anonymous}>
+ <p class="text-xs text-ink-muted">
+ {voting.final()
+ ? 'You voted. Anonymous poll: votes aren’t linked to people, so yours can’t be changed.'
+ : 'Anonymous poll: votes aren’t linked to people, not even for the poll’s owner.'}
+ </p>
+ </Show>
<Show when={!open()}>
<p class="text-xs text-ink-muted">
{availabilityLine(availability(), new Date())}
</p>
</Show>
- <Show when={!isEditor() && showingResults()}>
- <PollResults bars={voting.bars()} summary={voting.summary()} />
+ <Show when={voting.hasVoters() && showingResults()}>
+ <PollResults
+ ref={(element) =>
+ // A card in a message is a fixed-height embed: bring the opened
+ // results into view instead of leaving them below its fold.
+ requestAnimationFrame(() =>
+ element.scrollIntoView?.({ block: 'nearest' })
+ )
+ }
+ bars={voting.bars()}
+ viewerId={context.viewer.userId()}
+ renderPerson={context.ui.renderPerson}
+ onOpenResponses={
+ canReadResponses() ? props.onOpenResponses : undefined
+ }
+ />
</Show>
</div>
);
diff --git a/apps/web/src/features/block-form/views/form-page-view.test.tsx b/apps/web/src/features/block-form/views/form-page-view.test.tsx
index 112d665c96..6f4f0975f7 100644
--- a/apps/web/src/features/block-form/views/form-page-view.test.tsx
+++ b/apps/web/src/features/block-form/views/form-page-view.test.tsx
@@ -53,6 +53,8 @@ const detail: FormDetail = {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/features/block-form/views/form-page-view.tsx b/apps/web/src/features/block-form/views/form-page-view.tsx
index 82bd4e58c6..53be52690c 100644
--- a/apps/web/src/features/block-form/views/form-page-view.tsx
+++ b/apps/web/src/features/block-form/views/form-page-view.tsx
@@ -120,7 +120,8 @@ function EditorTabs(props: {
}
/**
- * The form page: editors get Build, Responses and Share; viewers land on the respond page.
+ * The form page: editors get Build, Responses and Share; viewers land on
+ * the respond page, or the Responses table when those rows are shared.
*/
type FormPageProps = {
source: FormDetailSource;
@@ -242,17 +243,31 @@ export function FormPageView(props: FormPageProps) {
<Show
when={detail().access !== 'view'}
fallback={
- <div
- ref={respondScroll}
- class="h-full min-h-0 overflow-y-auto touch:pb-(--mobile-content-inset-bottom)"
+ <Show
+ when={
+ props.tab === 'responses' && detail().form.responsesVisible
+ }
+ fallback={
+ <div
+ ref={respondScroll}
+ class="h-full min-h-0 overflow-y-auto touch:pb-(--mobile-content-inset-bottom)"
+ >
+ <RespondView
+ detail={detail()}
+ refetch={props.source.refetch}
+ compact={false}
+ scrollContainer={() => respondScroll}
+ onOpenResponses={
+ detail().form.responsesVisible
+ ? () => props.onTabChange('responses')
+ : undefined
+ }
+ />
+ </div>
+ }
>
- <RespondView
- detail={detail()}
- refetch={props.source.refetch}
- compact={false}
- scrollContainer={() => respondScroll}
- />
- </div>
+ <ResponsesView detail={detail()} />
+ </Show>
}
>
<EditorPanels {...props} detail={detail()} tabsId={tabsId} />
diff --git a/apps/web/src/features/block-form/views/respond-view.test.tsx b/apps/web/src/features/block-form/views/respond-view.test.tsx
index 989dbfd9d8..1317e447d2 100644
--- a/apps/web/src/features/block-form/views/respond-view.test.tsx
+++ b/apps/web/src/features/block-form/views/respond-view.test.tsx
@@ -37,6 +37,8 @@ function offsite(): FormDetail {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: 'See you there!',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
@@ -405,6 +407,39 @@ describe('RespondView', () => {
).toBeTruthy();
});
+ it('shows an anonymous respondent that they responded, with no answers to show or edit', () => {
+ const detail = offsite();
+ detail.form.responsesVisible = true;
+ detail.form.anonymous = true;
+ const { context } = createMockFormContext({
+ detail,
+ mine: {
+ status: 'submitted',
+ booking: null,
+ submittedAt: undefined,
+ answers: [],
+ anonymous: true,
+ },
+ });
+ let opened = 0;
+ render(() => (
+ <FormProvider value={context}>
+ <RespondView
+ detail={detail}
+ compact={false}
+ refetch={async () => true}
+ onOpenResponses={() => opened++}
+ />
+ </FormProvider>
+ ));
+ expect(screen.queryByRole('button', { name: 'Edit my response' })).toBe(
+ null
+ );
+ expect(screen.queryByRole('region', { name: 'Your answers' })).toBe(null);
+ fireEvent.click(screen.getByRole('button', { name: 'See responses' }));
+ expect(opened).toBe(1);
+ });
+
it('shows a closed form’s saved response with the reason it can no longer be edited', () => {
const detail = offsite();
detail.form.status = 'closed';
diff --git a/apps/web/src/features/block-form/views/respond-view.tsx b/apps/web/src/features/block-form/views/respond-view.tsx
index d5b59abb72..c59f2f408d 100644
--- a/apps/web/src/features/block-form/views/respond-view.tsx
+++ b/apps/web/src/features/block-form/views/respond-view.tsx
@@ -56,6 +56,8 @@ export function RespondView(props: {
scrollContainer?: () => HTMLElement | undefined;
/** Read the form again; resolves whether the read succeeded. */
refetch: () => Promise<boolean>;
+ /** Open the Responses table, offered when the form shares its responses. */
+ onOpenResponses?: () => void;
}) {
const context = useFormContext();
// One per mount: a form can show as a page and a card at once.
@@ -413,7 +415,13 @@ export function RespondView(props: {
message={form().confirmationMessage}
fresh={confirmation().fresh}
submittedAt={confirmation().submittedAt}
- receipt={receipt(confirmation().answers)}
+ receipt={
+ // An anonymous response's answers are known only to the
+ // visit that gave them.
+ form().anonymous && !confirmation().fresh
+ ? []
+ : receipt(confirmation().answers)
+ }
canEdit={confirmation().canEdit}
compact={props.compact}
renderEntityLabel={context.ui.renderEntityLabel}
@@ -423,15 +431,27 @@ export function RespondView(props: {
}}
notice={
<>
- <Show when={!confirmation().fresh && !open()}>
+ <Show
+ when={
+ !confirmation().fresh && !open() && !form().anonymous
+ }
+ >
<p class="text-xs text-ink">
This form is closed, so your response can’t be changed.
</p>
</Show>
<Show when={confirmation().alreadyResponded}>
<p class="text-xs text-ink">
- You had already responded, so the answers you just gave
- weren’t sent. This is your saved response.
+ {form().anonymous
+ ? 'You had already responded, so the answers you just gave weren’t sent.'
+ : 'You had already responded, so the answers you just gave weren’t sent. This is your saved response.'}
+ </p>
+ </Show>
+ <Show when={!confirmation().fresh && form().anonymous}>
+ <p class="text-xs text-ink">
+ You responded. This form is anonymous, so your answers
+ aren’t kept with your name and can’t be shown or
+ changed.
</p>
</Show>
</>
@@ -451,9 +471,24 @@ export function RespondView(props: {
Book a time
</Button>
</Show>
+ <Show when={props.onOpenResponses}>
+ {(open) => (
+ <Button
+ variant="secondary"
+ class="self-start"
+ onClick={() => open()()}
+ >
+ See responses
+ </Button>
+ )}
+ </Show>
<p class="px-1 text-xs text-ink-muted">
- Stored as a row in a database the form owner controls.
- Your answers are visible to the form’s editors.
+ Stored as a row in a database the form owner controls.{' '}
+ {props.detail.form.anonymous
+ ? 'This form is anonymous: nobody in Macro, its owner included, can see which response is yours, and it can’t be changed.'
+ : props.detail.form.responsesVisible
+ ? 'Everyone who can open this form sees your answers and your name.'
+ : 'Your answers are visible to the form’s editors.'}
</p>
</>
}
diff --git a/apps/web/src/features/block-form/views/responses-view.tsx b/apps/web/src/features/block-form/views/responses-view.tsx
index 5585a810f5..0d405d3daf 100644
--- a/apps/web/src/features/block-form/views/responses-view.tsx
+++ b/apps/web/src/features/block-form/views/responses-view.tsx
@@ -37,34 +37,38 @@ export function ResponsesView(props: { detail: FormDetail }) {
};
return (
<div class="@container/responses flex size-full min-h-0 flex-col bg-canvas-base">
- <div class="flex flex-col gap-3 px-4 pt-4 pb-3 @2xl/responses:px-6">
- <Show
- when={!summary.failure()}
- fallback={
- <p class="text-xs text-failure-ink">
- The response counts couldn’t be loaded.
- </p>
- }
- >
- <StatTiles
- loading={!summary.value()}
- tiles={responseTiles(
- summary.value() ?? {
- submitted: 0,
- stopped: 0,
- stoppedBySection: [],
- rows: 0,
- },
- reach(),
- (sectionId) => sectionName(props.detail.layout, sectionId)
- )}
- />
- </Show>
- </div>
+ {/* The ledger's counts are editor-only; viewers of shared responses get the table. */}
+ <Show when={props.detail.access !== 'view'}>
+ <div class="flex flex-col gap-3 px-4 pt-4 pb-3 @2xl/responses:px-6">
+ <Show
+ when={!summary.failure()}
+ fallback={
+ <p class="text-xs text-failure-ink">
+ The response counts couldn’t be loaded.
+ </p>
+ }
+ >
+ <StatTiles
+ loading={!summary.value()}
+ tiles={responseTiles(
+ summary.value() ?? {
+ submitted: 0,
+ stopped: 0,
+ stoppedBySection: [],
+ rows: 0,
+ },
+ reach(),
+ (sectionId) => sectionName(props.detail.layout, sectionId)
+ )}
+ />
+ </Show>
+ </div>
+ </Show>
<div class="flex min-h-0 flex-1 flex-col">
{context.ui.renderResponsesGrid({
databaseId: form().databaseId,
tableId: form().tableId,
+ hideColumnId: form().anonymous ? form().respondentColumnId : null,
})}
</div>
</div>
diff --git a/apps/web/src/features/block-form/views/share-tab-view.tsx b/apps/web/src/features/block-form/views/share-tab-view.tsx
index cad95c5013..6e9d966302 100644
--- a/apps/web/src/features/block-form/views/share-tab-view.tsx
+++ b/apps/web/src/features/block-form/views/share-tab-view.tsx
@@ -1,6 +1,6 @@
import { fireAndForget } from '@core/util/fireAndForget';
import UsersThree from '@icon/system/regular/users-three.svg';
-import { Button, Input, ToggleSwitch } from '@ui';
+import { Button, Input, ToggleSwitch, Tooltip } from '@ui';
import { ResultAsync } from 'neverthrow';
import { createSignal, Show } from 'solid-js';
import { AudiencePanel } from '../components/share/audience-panel';
@@ -20,8 +20,9 @@ import type { Preview } from '../primitives/create-preview';
/**
* The Share tab (RFC 02 §2, §6): who can respond, the respond link, whether
- * the form takes responses and until when, how the respond page is branded,
- * and the people it is shared with through the share dialog.
+ * the form takes responses and until when, whether responses and names are
+ * shared, how the respond page is branded, and the people it is shared with
+ * through the share dialog.
*/
export function ShareTabView(props: {
detail: FormDetail;
@@ -36,6 +37,12 @@ export function ShareTabView(props: {
const isOwner = () => props.detail.access === 'owner';
const canEdit = () => props.detail.access !== 'view';
const [pending, setPending] = createSignal(false);
+ const summary = context.responses.createSummary(
+ () => form().id,
+ () => isOwner()
+ );
+ /** Whether the form is anonymous is fixed once anyone has responded. */
+ const anonymityLocked = () => (summary.value()?.submitted ?? 0) > 0;
const writes = new Set<ResultAsync<void, FormWriteFailure>>();
props.trackWrites(() =>
ResultAsync.combine([...writes]).map(() => undefined)
@@ -171,6 +178,41 @@ export function ShareTabView(props: {
)
}
/>
+ <ToggleSwitch
+ size="md"
+ label="Share responses with team"
+ labelClass="text-sm text-ink"
+ checked={form().responsesVisible}
+ disabled={!isOwner() || pending()}
+ onChange={(responsesVisible) =>
+ fireAndForget(
+ update({ responsesVisible }, 'Sharing responses'),
+ 'form-share'
+ )
+ }
+ />
+ <Tooltip
+ label={
+ anonymityLocked()
+ ? 'People have responded, so this can’t change.'
+ : 'Nobody in Macro, you included, sees who gave which response.'
+ }
+ class="self-start"
+ >
+ <ToggleSwitch
+ size="md"
+ label="Anonymous"
+ labelClass="text-sm text-ink"
+ checked={form().anonymous}
+ disabled={!isOwner() || pending() || anonymityLocked()}
+ onChange={(anonymous) =>
+ fireAndForget(
+ update({ anonymous }, 'Anonymous responses'),
+ 'form-share'
+ )
+ }
+ />
+ </Tooltip>
<label class="flex flex-col gap-1">
<span class="text-xs font-medium text-ink-muted">
Confirmation message
@@ -194,8 +236,8 @@ export function ShareTabView(props: {
</label>
<Show when={!isOwner()}>
<p class="text-xs text-ink-muted">
- Only the owner can change who responds, close the form or show
- results.
+ Only the owner can change who responds, close the form, show
+ results, share responses or make them anonymous.
</p>
</Show>
</div>
diff --git a/apps/web/src/features/drive-view/queries/drive-forms.test.ts b/apps/web/src/features/drive-view/queries/drive-forms.test.ts
index d914bae6e8..8523b44c3a 100644
--- a/apps/web/src/features/drive-view/queries/drive-forms.test.ts
+++ b/apps/web/src/features/drive-view/queries/drive-forms.test.ts
@@ -23,6 +23,8 @@ const listed: ListedForm[] = [
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
@@ -46,6 +48,8 @@ const listed: ListedForm[] = [
respondentColumnId: null,
audience: 'members',
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
diff --git a/apps/web/src/lib/core/component/AI/component/tool/forms/ResultDetails.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/forms/ResultDetails.test.tsx
index 88e6adad9c..193863219d 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/forms/ResultDetails.test.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/forms/ResultDetails.test.tsx
@@ -31,6 +31,8 @@ const result: FormMutation = {
status: 'open',
closesAt: null,
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
submittedColumnId: null,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
index 83c21c1a14..73198ed124 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
@@ -73,6 +73,8 @@ function pollDetail(
status: 'open',
closesAt: null,
tallyVisible: true,
+ responsesVisible: false,
+ anonymous: false,
confirmationMessage: '',
submittedColumnId: null,
respondentColumnId: null,
diff --git a/apps/web/src/lib/queries/storage/forms-preview.test.ts b/apps/web/src/lib/queries/storage/forms-preview.test.ts
index 19736a5dfe..b7a399bb6c 100644
--- a/apps/web/src/lib/queries/storage/forms-preview.test.ts
+++ b/apps/web/src/lib/queries/storage/forms-preview.test.ts
@@ -64,6 +64,8 @@ it('updates an already cached card title after renaming a form', async () => {
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
@@ -157,6 +159,8 @@ it('refreshes the linked database’s card after renaming a form, without guessi
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
@@ -228,6 +232,8 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
@@ -253,6 +259,8 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
@@ -276,6 +284,8 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: '',
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 58f71857e6..9bc9d8be65 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -2705,6 +2705,7 @@ export const CreateForm = z.object({
const schemas = [
z.object({
isHiddenInDrive: z.boolean().optional(),
+ anonymous: z.boolean().optional(),
kind: z.literal('new'),
}),
z.object({
@@ -3528,6 +3529,8 @@ export const MutationResult = z.object({
}
}),
tallyVisible: z.boolean(),
+ responsesVisible: z.boolean(),
+ anonymous: z.boolean(),
status: z.any().superRefine((x, ctx) => {
const schemas = [z.literal('open'), z.literal('closed')];
const errors = schemas.reduce<z.ZodError[]>(
@@ -11064,6 +11067,8 @@ export const ListResult = z.object({
}
}),
tallyVisible: z.boolean(),
+ responsesVisible: z.boolean(),
+ anonymous: z.boolean(),
status: z.any().superRefine((x, ctx) => {
const schemas = [z.literal('open'), z.literal('closed')];
const errors = schemas.reduce<z.ZodError[]>(
@@ -13843,6 +13848,8 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
}
}),
tallyVisible: z.boolean(),
+ responsesVisible: z.boolean(),
+ anonymous: z.boolean(),
status: z.any().superRefine((x, ctx) => {
const schemas = [z.literal('open'), z.literal('closed')];
const errors = schemas.reduce<z.ZodError[]>(
@@ -14462,6 +14469,8 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
}
}),
tallyVisible: z.boolean(),
+ responsesVisible: z.boolean(),
+ anonymous: z.boolean(),
status: z.any().superRefine((x, ctx) => {
const schemas = [z.literal('open'), z.literal('closed')];
const errors = schemas.reduce<z.ZodError[]>(
@@ -16363,6 +16372,8 @@ export const SetFormAccess = z.object({
.union([z.string().datetime({ offset: true }), z.null()])
.optional(),
tallyVisible: z.boolean(),
+ responsesVisible: z.union([z.boolean(), z.null()]).optional(),
+ anonymous: z.union([z.boolean(), z.null()]).optional(),
channelGrants: z
.array(
z.any().superRefine((x, ctx) => {
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index ab7a7bf77a..a28616aeb2 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -453,6 +453,11 @@ export type FormSource =
* for a channel poll.
*/
isHiddenInDrive?: boolean;
+ /**
+ * Make the form anonymous from the start: its table gets no
+ * Respondent column.
+ */
+ anonymous?: boolean;
kind: 'new';
}
| {
@@ -3940,8 +3945,9 @@ export type SessionArchiveCause =
| 'pull_request_merged'
| 'runtime_closed';
/**
- * The caller's level on a form: view responds, edit changes questions and
- * reads responses, owner also sets the audience, closes and trashes it.
+ * The caller's level on a form: view responds (and reads responses when
+ * they are shared), edit changes questions and reads responses, owner
+ * also sets the audience, closes and trashes it.
*/
export type FormAccess = 'view' | 'edit' | 'owner';
/**
@@ -7880,7 +7886,8 @@ export interface Form {
submittedColumnId?: string | null;
/**
* The person column each signed-in submission names its respondent in;
- * `null` once deleted.
+ * `null` once deleted, and on a form created anonymous. An anonymous
+ * form never writes it.
*/
respondentColumnId?: string | null;
audience: Audience;
@@ -7888,6 +7895,16 @@ export interface Form {
* Whether respondents may read option tallies.
*/
tallyVisible: boolean;
+ /**
+ * Whether people with View may read individual response rows.
+ */
+ responsesVisible: boolean;
+ /**
+ * Whether nobody, the owner included, can see who gave which response.
+ * Who responded is kept apart from the responses, only so nobody
+ * responds twice. Fixed once anyone has responded.
+ */
+ anonymous: boolean;
status: FormStatus;
/**
* When it stops taking responses, if it does.
@@ -15623,7 +15640,7 @@ export interface SetFavoriteResponse {
favorite: boolean;
}
/**
- * Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Public allows anonymous responses. View allows responding without database access; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open.
+ * Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Optional responsesVisible lets View holders read response rows; optional anonymous makes the form anonymous to everyone, its owner included (who responded is kept apart from the responses), and is refused once anyone has responded. Public allows anonymous responses. View allows responding without database access unless responses are shared; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open.
*/
export interface SetFormAccess {
formId: FormId;
@@ -15643,6 +15660,15 @@ export interface AccessDraft {
* Whether respondents can see aggregate choice tallies.
*/
tallyVisible: boolean;
+ /**
+ * Whether people with View may read individual response rows.
+ */
+ responsesVisible?: boolean | null;
+ /**
+ * Whether nobody, the owner included, can see who gave which response;
+ * refused once anyone has responded.
+ */
+ anonymous?: boolean | null;
/**
* Direct channel changes only; this does not post messages or send invitations.
*/
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
index 1e5a95057d..1377b133e9 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
@@ -16,6 +16,10 @@ import type { FormSubmittedColumnId } from './formSubmittedColumnId';
* A form: a view of one database table whose rows are its responses.
*/
export interface Form {
+ /** Whether nobody, the owner included, can see who gave which response.
+Who responded is kept apart from the responses, only so nobody
+responds twice. Fixed once anyone has responded. */
+ anonymous: boolean;
/** Who may respond. */
audience: Audience;
/** Its logo, cover image and accent color. */
@@ -44,8 +48,11 @@ a form attached to an existing table has its own name. */
/** The folder it is filed in; `null` at the root. */
projectId: FormProjectId;
/** The person column each signed-in submission names its respondent in;
-`null` once deleted. */
+`null` once deleted, and on a form created anonymous. An anonymous
+form never writes it. */
respondentColumnId: FormRespondentColumnId;
+ /** Whether people with View may read individual response rows. */
+ responsesVisible: boolean;
/** Whether its owner closed it. */
status: FormStatus;
/** The date column each submission stamps; `null` once deleted. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formAccess.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formAccess.ts
index 2d87703ddd..0edd64bff1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formAccess.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formAccess.ts
@@ -6,8 +6,9 @@
*/
/**
- * The caller's level on a form: view responds, edit changes questions and
-reads responses, owner also sets the audience, closes and trashes it.
+ * The caller's level on a form: view responds (and reads responses when
+they are shared), edit changes questions and reads responses, owner
+also sets the audience, closes and trashes it.
*/
export type FormAccess = (typeof FormAccess)[keyof typeof FormAccess];
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formErrorCode.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formErrorCode.ts
index 168642254a..ddf42aca38 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formErrorCode.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formErrorCode.ts
@@ -21,6 +21,7 @@ export const FormErrorCode = {
tableGone: 'tableGone',
alreadyResponded: 'alreadyResponded',
noResponse: 'noResponse',
+ anonymousResponseFinal: 'anonymousResponseFinal',
unknownQuestion: 'unknownQuestion',
repeatedAnswer: 'repeatedAnswer',
missingAnswer: 'missingAnswer',
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formRespondentColumnId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formRespondentColumnId.ts
index 518290184d..82b501cf7f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formRespondentColumnId.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formRespondentColumnId.ts
@@ -7,6 +7,7 @@
/**
* The person column each signed-in submission names its respondent in;
-`null` once deleted.
+`null` once deleted, and on a form created anonymous. An anonymous
+form never writes it.
*/
export type FormRespondentColumnId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSourceOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSourceOneOf.ts
index 0bfddf6d0f..7ce680477a 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSourceOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSourceOneOf.ts
@@ -11,6 +11,9 @@ import type { FormSourceOneOfKind } from './formSourceOneOfKind';
starts with only the form's own columns.
*/
export type FormSourceOneOf = {
+ /** Make the form anonymous from the start: its table gets no
+Respondent column. */
+ anonymous?: boolean;
/** Keep the form, and the database made for it, out of Drive, as
for a channel poll. */
isHiddenInDrive?: boolean;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 121be3086e..68437078e0 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1446,6 +1446,10 @@ export * from './messageTimelineQueryLimit';
export * from './messageTriggeredBy';
export * from './messageTriggeredVia';
export * from './myResponse';
+export * from './myResponseOneOf';
+export * from './myResponseOneOfKind';
+export * from './myResponseOneOfThree';
+export * from './myResponseOneOfThreeKind';
export * from './newAttachment';
export * from './newAttachmentHeight';
export * from './newAttachmentWidth';
@@ -2145,6 +2149,7 @@ export * from './takenIdOneOfSevenKind';
export * from './takenIdOneOfThree';
export * from './takenIdOneOfThreeKind';
export * from './tallyBucket';
+export * from './tallyBucketVoters';
export * from './tallyValue';
export * from './tallyValueOneOf';
export * from './tallyValueOneOfKind';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponse.ts
index 77416598d2..2a1bcccfae 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponse.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponse.ts
@@ -4,21 +4,10 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { Answer } from './answer';
-import type { FormResponse } from './formResponse';
-import type { UnlockedBooking } from './unlockedBooking';
+import type { MyResponseOneOf } from './myResponseOneOf';
+import type { MyResponseOneOfThree } from './myResponseOneOfThree';
/**
- * A signed-in respondent's own response, with its answers as the row
-holds them now.
+ * A signed-in respondent's own response.
*/
-export interface MyResponse {
- /** The row's cells for the form's current questions, the empty ones
-left out; none when the row is gone. */
- answers: Answer[];
- /** The form's booking step, while the saved row still passes the form's
-current required questions and gates. */
- booking?: UnlockedBooking;
- /** The ledger entry. */
- response: FormResponse;
-}
+export type MyResponse = MyResponseOneOf | MyResponseOneOfThree;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOf.ts
new file mode 100644
index 0000000000..d07998e9bd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOf.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { Answer } from './answer';
+import type { FormResponse } from './formResponse';
+import type { MyResponseOneOfKind } from './myResponseOneOfKind';
+import type { UnlockedBooking } from './unlockedBooking';
+
+/**
+ * Their ledger entry, with its answers as the row holds them now.
+ */
+export type MyResponseOneOf = {
+ /** The row's cells for the form's current questions, the empty ones
+left out; none when the row is gone. */
+ answers: Answer[];
+ /** The form's booking step, while the saved row still passes the
+form's current required questions and gates. */
+ booking?: UnlockedBooking;
+ kind: MyResponseOneOfKind;
+ /** The ledger entry. */
+ response: FormResponse;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfKind.ts
new file mode 100644
index 0000000000..8c32c7182c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfKind.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type MyResponseOneOfKind =
+ (typeof MyResponseOneOfKind)[keyof typeof MyResponseOneOfKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const MyResponseOneOfKind = {
+ saved: 'saved',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThree.ts
new file mode 100644
index 0000000000..f8e30df452
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThree.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MyResponseOneOfThreeKind } from './myResponseOneOfThreeKind';
+
+/**
+ * They responded to an anonymous form. Nothing links them to their
+response, so there is nothing more to show.
+ */
+export type MyResponseOneOfThree = {
+ kind: MyResponseOneOfThreeKind;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThreeKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThreeKind.ts
new file mode 100644
index 0000000000..2ab9dec872
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/myResponseOneOfThreeKind.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type MyResponseOneOfThreeKind =
+ (typeof MyResponseOneOfThreeKind)[keyof typeof MyResponseOneOfThreeKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const MyResponseOneOfThreeKind = {
+ anonymous: 'anonymous',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucket.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucket.ts
index 328269a5b0..0eb8828f96 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucket.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucket.ts
@@ -4,6 +4,8 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+
+import type { TallyBucketVoters } from './tallyBucketVoters';
import type { TallyValue } from './tallyValue';
/**
@@ -17,4 +19,9 @@ export interface TallyBucket {
count: number;
/** The value. */
value: TallyValue;
+ /** Who chose it, as Macro user ids in submission order: present only
+for the form's editors, or its viewers when it shares its responses,
+and never when it hides respondents. Rows no signed-in respondent
+submitted count without a voter. */
+ voters?: TallyBucketVoters;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucketVoters.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucketVoters.ts
new file mode 100644
index 0000000000..830fef911a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/tallyBucketVoters.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Who chose it, as Macro user ids in submission order: present only
+for the form's editors, or its viewers when it shares its responses,
+and never when it hides respondents. Rows no signed-in respondent
+submitted count without a voter.
+ */
+export type TallyBucketVoters = string[] | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateForm.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateForm.ts
index 4a490f2cff..e749d8a74c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateForm.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateForm.ts
@@ -23,6 +23,9 @@ export interface UpdateForm {
* @pattern ^#[0-9a-fA-F]{6}$
*/
accentColor?: UpdateFormAccentColor;
+ /** Whether nobody can see who gave which response; refused once anyone
+has responded. */
+ anonymous?: boolean;
/** Who may respond from now on. */
audience?: Audience;
/** When it stops taking responses, or `null` for never. */
@@ -35,6 +38,8 @@ export interface UpdateForm {
description?: string;
/** A new logo, or `null` to remove it. */
logoFileId?: UpdateFormLogoFileId;
+ /** Whether people with View may read individual response rows. */
+ responsesVisible?: boolean;
/** Open or close it. */
status?: FormStatus;
/** Whether respondents may read option tallies. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 6ac2740ea6..1f2ca5d12e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -22641,6 +22641,11 @@ export const listFormsResponseBrandingAccentColorRegExpTwo = new RegExp(
export const listFormsResponseItem = zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -22699,8 +22704,11 @@ export const listFormsResponseItem = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
),
+ responsesVisible: zod
+ .boolean()
+ .describe('Whether people with View may read individual response rows.'),
status: zod
.enum(['open', 'closed'])
.describe(
@@ -22736,6 +22744,12 @@ export const createFormBody = zod
.union([
zod
.object({
+ anonymous: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Make the form anonymous from the start: its table gets no\nRespondent column.'
+ ),
isHiddenInDrive: zod
.boolean()
.optional()
@@ -22774,10 +22788,15 @@ export const listAccessibleFormsResponseItem = zod
access: zod
.enum(['view', 'edit', 'owner'])
.describe(
- "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it."
+ "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it."
),
form: zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -22840,7 +22859,12 @@ export const listAccessibleFormsResponseItem = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
+ ),
+ responsesVisible: zod
+ .boolean()
+ .describe(
+ 'Whether people with View may read individual response rows.'
),
status: zod
.enum(['open', 'closed'])
@@ -22889,10 +22913,15 @@ export const getFormResponse = zod
access: zod
.enum(['view', 'edit', 'owner'])
.describe(
- "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it."
+ "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it."
),
form: zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -22953,7 +22982,12 @@ export const getFormResponse = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
+ ),
+ responsesVisible: zod
+ .boolean()
+ .describe(
+ 'Whether people with View may read individual response rows.'
),
status: zod
.enum(['open', 'closed'])
@@ -23408,6 +23442,12 @@ export const updateFormBody = zod
.regex(updateFormBodyAccentColorRegExp)
.nullish()
.describe('A new accent color, or `null` for the default.'),
+ anonymous: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether nobody can see who gave which response; refused once anyone\nhas responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.optional()
@@ -23429,6 +23469,10 @@ export const updateFormBody = zod
.uuid()
.nullish()
.describe('A new logo, or `null` to remove it.'),
+ responsesVisible: zod
+ .boolean()
+ .optional()
+ .describe('Whether people with View may read individual response rows.'),
status: zod
.enum(['open', 'closed'])
.optional()
@@ -23450,6 +23494,11 @@ export const updateFormResponseBrandingAccentColorRegExpTwo = new RegExp(
export const updateFormResponse = zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -23508,8 +23557,11 @@ export const updateFormResponse = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
),
+ responsesVisible: zod
+ .boolean()
+ .describe('Whether people with View may read individual response rows.'),
status: zod
.enum(['open', 'closed'])
.describe(
@@ -23550,10 +23602,15 @@ export const collaborateFormResponse = zod
access: zod
.enum(['view', 'edit', 'owner'])
.describe(
- "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it."
+ "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it."
),
form: zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -23620,7 +23677,12 @@ export const collaborateFormResponse = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
+ ),
+ responsesVisible: zod
+ .boolean()
+ .describe(
+ 'Whether people with View may read individual response rows.'
),
status: zod
.enum(['open', 'closed'])
@@ -24500,10 +24562,15 @@ export const putFormLayoutResponse = zod
access: zod
.enum(['view', 'edit', 'owner'])
.describe(
- "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it."
+ "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it."
),
form: zod
.object({
+ anonymous: zod
+ .boolean()
+ .describe(
+ 'Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded.'
+ ),
audience: zod
.enum(['members', 'public'])
.describe('Who may respond to a form.'),
@@ -24570,7 +24637,12 @@ export const putFormLayoutResponse = zod
.uuid()
.nullable()
.describe(
- 'The person column each signed-in submission names its respondent in;\n`null` once deleted.'
+ 'The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it.'
+ ),
+ responsesVisible: zod
+ .boolean()
+ .describe(
+ 'Whether people with View may read individual response rows.'
),
status: zod
.enum(['open', 'closed'])
@@ -25492,222 +25564,240 @@ export const getMyFormResponseParams = zod.object({
});
export const getMyFormResponseResponse = zod
- .object({
- answers: zod
- .array(
- zod
- .object({
- question: zod.uuid().describe('The question.'),
- value: zod
- .union([
- zod
- .object({
- type: zod.enum(['text']),
- value: zod.string().describe('Free text.'),
- })
- .describe('Free text.'),
- zod
- .object({
- type: zod.enum(['number']),
- value: zod.number().describe('A finite number.'),
- })
- .describe('A finite number.'),
- zod
- .object({
- type: zod.enum(['boolean']),
- value: zod.boolean().describe('A checkbox.'),
- })
- .describe('A checkbox.'),
- zod
- .object({
- type: zod.enum(['date']),
- value: zod.iso.datetime({}).describe('A date-time.'),
- })
- .describe('A date-time.'),
- zod
- .object({
- type: zod.enum(['date_range']),
- value: zod
+ .union([
+ zod
+ .object({
+ answers: zod
+ .array(
+ zod
+ .object({
+ question: zod.uuid().describe('The question.'),
+ value: zod
+ .union([
+ zod
.object({
- end: zod.iso
- .datetime({})
- .describe('Where it ends; never before the start.'),
- start: zod.iso
- .datetime({})
- .describe('Where it starts.'),
+ type: zod.enum(['text']),
+ value: zod.string().describe('Free text.'),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod.number().describe('A finite number.'),
+ })
+ .describe('A finite number.'),
+ zod
+ .object({
+ type: zod.enum(['boolean']),
+ value: zod.boolean().describe('A checkbox.'),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum(['date']),
+ value: zod.iso.datetime({}).describe('A date-time.'),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum(['date_range']),
+ value: zod
+ .object({
+ end: zod.iso
+ .datetime({})
+ .describe(
+ 'Where it ends; never before the start.'
+ ),
+ start: zod.iso
+ .datetime({})
+ .describe('Where it starts.'),
+ })
+ .describe(
+ 'A span of time from `start` to `end`, both included. A write whose end\ncomes before its start is refused.'
+ ),
})
.describe(
- 'A span of time from `start` to `end`, both included. A write whose end\ncomes before its start is refused.'
+ 'A span of time; its end may not come before its start.'
),
- })
- .describe(
- 'A span of time; its end may not come before its start.'
- ),
- zod
- .object({
- type: zod.enum(['link']),
- value: zod
- .array(zod.string())
+ zod
+ .object({
+ type: zod.enum(['link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ })
.describe(
'Complete http or https URLs; at most one for a single-valued column.'
),
- })
- .describe(
- 'Complete http or https URLs; at most one for a single-valued column.'
- ),
- zod
- .object({
- type: zod.enum(['options']),
- value: zod
- .array(
- zod
- .union([
+ zod
+ .object({
+ type: zod.enum(['options']),
+ value: zod
+ .array(
zod
- .object({
- id: zod
- .uuid()
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe('An option the column has.'),
+ })
.describe('An option the column has.'),
- })
- .describe('An option the column has.'),
- zod
- .object({
- label: zod
- .string()
+ zod
+ .object({
+ label: zod
+ .string()
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ })
.describe(
"An option's label, matched without regard to case. An unknown label\nis refused."
),
- })
+ ])
.describe(
- "An option's label, matched without regard to case. An unknown label\nis refused."
- ),
- ])
- .describe(
- 'A select option, by its id or by its label.'
+ 'A select option, by its id or by its label.'
+ )
)
- )
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ })
.describe(
'Options of a select or tag column; at most one for a single-valued\ncolumn.'
),
- })
- .describe(
- 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
- ),
- zod
- .object({
- type: zod.enum(['entities']),
- value: zod
- .array(
- zod
- .object({
- entityId: zod.string().describe("The entity's id."),
- entityType: zod
- .enum([
- 'USER',
- 'DOCUMENT',
- 'TASK',
- 'COMPANY',
- 'CONTACT',
- 'CALL_RECORD',
- 'CHANNEL',
- 'CHAT',
- 'PROJECT',
- 'THREAD',
- 'CALENDAR_EVENT',
- 'INITIATIVE',
- ])
- .describe(
- 'A kind of Macro entity a reference column can point at.'
- ),
- })
- .describe('A reference to one Macro entity.')
- )
+ zod
+ .object({
+ type: zod.enum(['entities']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entityId: zod
+ .string()
+ .describe("The entity's id."),
+ entityType: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ })
+ .describe('A reference to one Macro entity.')
+ )
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ })
.describe(
'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
),
- })
- .describe(
- 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
- ),
- zod
- .object({
- type: zod.enum(['rows']),
- value: zod
- .array(zod.uuid())
+ zod
+ .object({
+ type: zod.enum(['rows']),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ })
.describe(
'Rows of the table a relation column points at.'
),
- })
- .describe('Rows of the table a relation column points at.'),
- zod
- .object({
- type: zod.enum(['clear']),
- })
- .describe('No value: the cell is emptied.'),
- ])
+ zod
+ .object({
+ type: zod.enum(['clear']),
+ })
+ .describe('No value: the cell is emptied.'),
+ ])
+ .describe(
+ "A cell's value. It must fit the column's type: text for a text column,\noptions of the column for a select, and so on."
+ ),
+ })
.describe(
- "A cell's value. It must fit the column's type: text for a text column,\noptions of the column for a select, and so on."
+ "One question's answer: a value for its column, typed as the column's\ncells are."
+ )
+ )
+ .describe(
+ "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
+ ),
+ booking: zod
+ .object({
+ description: zod
+ .string()
+ .describe('What respondents read before choosing a time.'),
+ section: zod.uuid().describe('The booking section.'),
+ target: zod
+ .object({
+ eventTypeId: zod.uuid().describe('The event type to book.'),
+ profileId: zod
+ .uuid()
+ .describe('The scheduling profile that owns the event.'),
+ })
+ .describe(
+ 'An existing native Macro scheduling event offered after an accepted response.'
),
+ title: zod.string().describe('Its title.'),
})
+ .optional()
.describe(
- "One question's answer: a value for its column, typed as the column's\ncells are."
- )
- )
- .describe(
- "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
- ),
- booking: zod
- .object({
- description: zod
- .string()
- .describe('What respondents read before choosing a time.'),
- section: zod.uuid().describe('The booking section.'),
- target: zod
+ 'A booking step a passing response has unlocked, with its destination.'
+ ),
+ kind: zod.enum(['saved']),
+ response: zod
.object({
- eventTypeId: zod.uuid().describe('The event type to book.'),
- profileId: zod
+ formId: zod.uuid().describe('The form.'),
+ id: zod.uuid().describe('The entry.'),
+ row: zod
.uuid()
- .describe('The scheduling profile that owns the event.'),
+ .nullable()
+ .describe(
+ 'The row holding the answers; `null` when stopped, or once the row was\ndeleted from the table.'
+ ),
+ status: zod
+ .enum(['submitted', 'stopped'])
+ .describe(
+ 'Whether a ledger entry is a saved response or a stop at a gate.'
+ ),
+ stoppedAtSection: zod
+ .uuid()
+ .nullable()
+ .describe('The gate that stopped it.'),
+ submittedAt: zod.iso
+ .datetime({})
+ .describe('When it was first submitted.'),
+ updatedAt: zod.iso.datetime({}).describe('When it last changed.'),
})
.describe(
- 'An existing native Macro scheduling event offered after an accepted response.'
+ "One entry of a form's submission ledger: who answered, when, and where\nthe answers went."
),
- title: zod.string().describe('Its title.'),
})
- .optional()
.describe(
- 'A booking step a passing response has unlocked, with its destination.'
+ 'Their ledger entry, with its answers as the row holds them now.'
),
- response: zod
+ zod
.object({
- formId: zod.uuid().describe('The form.'),
- id: zod.uuid().describe('The entry.'),
- row: zod
- .uuid()
- .nullable()
- .describe(
- 'The row holding the answers; `null` when stopped, or once the row was\ndeleted from the table.'
- ),
- status: zod
- .enum(['submitted', 'stopped'])
- .describe(
- 'Whether a ledger entry is a saved response or a stop at a gate.'
- ),
- stoppedAtSection: zod
- .uuid()
- .nullable()
- .describe('The gate that stopped it.'),
- submittedAt: zod.iso
- .datetime({})
- .describe('When it was first submitted.'),
- updatedAt: zod.iso.datetime({}).describe('When it last changed.'),
+ kind: zod.enum(['anonymous']),
})
.describe(
- "One entry of a form's submission ledger: who answered, when, and where\nthe answers went."
+ 'They responded to an anonymous form. Nothing links them to their\nresponse, so there is nothing more to show.'
),
- })
- .describe(
- "A signed-in respondent's own response, with its answers as the row\nholds them now."
- );
+ ])
+ .describe("A signed-in respondent's own response.");
/**
* @summary Replace the signed-in caller's answers while the form is open. A gate
@@ -26014,6 +26104,12 @@ export const getFormTallyResponse = zod
.describe('A checkbox state.'),
])
.describe('A value a tally counts.'),
+ voters: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ "Who chose it, as Macro user ids in submission order: present only\nfor the form's editors, or its viewers when it shares its responses,\nand never when it hides respondents. Rows no signed-in respondent\nsubmitted count without a voter."
+ ),
})
.describe('How many rows hold one value.')
)
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 28106aba22..4f3747ac76 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -31851,6 +31851,8 @@
"respondentColumnId",
"audience",
"tallyVisible",
+ "responsesVisible",
+ "anonymous",
"status",
"closesAt",
"confirmationMessage",
@@ -31861,6 +31863,10 @@
"isHiddenInDrive"
],
"properties": {
+ "anonymous": {
+ "type": "boolean",
+ "description": "Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded."
+ },
"audience": {
"$ref": "#/components/schemas/Audience",
"description": "Who may respond."
@@ -31916,7 +31922,11 @@
"respondentColumnId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The person column each signed-in submission names its respondent in;\n`null` once deleted."
+ "description": "The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it."
+ },
+ "responsesVisible": {
+ "type": "boolean",
+ "description": "Whether people with View may read individual response rows."
},
"status": {
"$ref": "#/components/schemas/FormStatus",
@@ -31945,7 +31955,7 @@
},
"FormAccess": {
"type": "string",
- "description": "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it.",
+ "description": "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it.",
"enum": ["view", "edit", "owner"]
},
"FormBranding": {
@@ -32030,6 +32040,7 @@
"tableGone",
"alreadyResponded",
"noResponse",
+ "anonymousResponseFinal",
"unknownQuestion",
"repeatedAnswer",
"missingAnswer",
@@ -32481,6 +32492,10 @@
"description": "A new database named like the form, whose one table, \"Responses\",\nstarts with only the form's own columns.",
"required": ["kind"],
"properties": {
+ "anonymous": {
+ "type": "boolean",
+ "description": "Make the form anonymous from the start: its table gets no\nRespondent column."
+ },
"isHiddenInDrive": {
"type": "boolean",
"description": "Keep the form, and the database made for it, out of Drive, as\nfor a channel poll."
@@ -36414,26 +36429,46 @@
"description": "Lifecycle events for the common message service, one per committed fact.\nReactions and typing never reach the topic."
},
"MyResponse": {
- "type": "object",
- "description": "A signed-in respondent's own response, with its answers as the row\nholds them now.",
- "required": ["response", "answers"],
- "properties": {
- "answers": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Answer"
- },
- "description": "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
- },
- "booking": {
- "$ref": "#/components/schemas/UnlockedBooking",
- "description": "The form's booking step, while the saved row still passes the form's\ncurrent required questions and gates."
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Their ledger entry, with its answers as the row holds them now.",
+ "required": ["response", "answers", "kind"],
+ "properties": {
+ "answers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Answer"
+ },
+ "description": "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
+ },
+ "booking": {
+ "$ref": "#/components/schemas/UnlockedBooking",
+ "description": "The form's booking step, while the saved row still passes the\nform's current required questions and gates."
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["saved"]
+ },
+ "response": {
+ "$ref": "#/components/schemas/FormResponse",
+ "description": "The ledger entry."
+ }
+ }
},
- "response": {
- "$ref": "#/components/schemas/FormResponse",
- "description": "The ledger entry."
+ {
+ "type": "object",
+ "description": "They responded to an anonymous form. Nothing links them to their\nresponse, so there is nothing more to show.",
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["anonymous"]
+ }
+ }
}
- }
+ ],
+ "description": "A signed-in respondent's own response."
},
"NewAttachment": {
"type": "object",
@@ -43584,6 +43619,13 @@
"value": {
"$ref": "#/components/schemas/TallyValue",
"description": "The value."
+ },
+ "voters": {
+ "type": ["array", "null"],
+ "items": {
+ "type": "string"
+ },
+ "description": "Who chose it, as Macro user ids in submission order: present only\nfor the form's editors, or its viewers when it shares its responses,\nand never when it hides respondents. Rows no signed-in respondent\nsubmitted count without a voter."
}
}
},
@@ -44748,6 +44790,10 @@
"description": "A new accent color, or `null` for the default.",
"pattern": "^#[0-9a-fA-F]{6}$"
},
+ "anonymous": {
+ "type": "boolean",
+ "description": "Whether nobody can see who gave which response; refused once anyone\nhas responded."
+ },
"audience": {
"$ref": "#/components/schemas/Audience",
"description": "Who may respond from now on."
@@ -44775,6 +44821,10 @@
"format": "uuid",
"description": "A new logo, or `null` to remove it."
},
+ "responsesVisible": {
+ "type": "boolean",
+ "description": "Whether people with View may read individual response rows."
+ },
"status": {
"$ref": "#/components/schemas/FormStatus",
"description": "Open or close it."
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 6da0f46d60..40e10cdcff 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -103,7 +103,7 @@
{
"name": "forms",
"description": "Build forms and read responses.",
- "index": "## forms\nBuild forms and read responses.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Form\nA form over a database table.\nExtends `MacroEntity`.\nFields: access, audience, closesAt, database, description, id, name, owner, status, table\n- `Form.editResponse`: editResponse(answers): Promise<FormSubmissionOutcome> — Replace the caller's answers while the form is open; gates are evaluated again.\n- `Form.myResponse`: myResponse(): Promise<MyFormResponse> — Read the caller's receipt and answers without reading anyone else's responses.\n- `Form.questions`: questions(): Promise<FormQuestion[]> — All questions in display order, skipping gates.\n- `Form.replaceLayout`: replaceLayout(sections): Promise<FormLayoutResult> — Save a replacement in the shared draft.\n- `Form.respondUrl`: respondUrl(): string — The respondent page, which public forms also expose without signing in.\n- `Form.responseSummary`: responseSummary(): Promise<FormResponseSummary> — Ledger counts and total table rows; requires edit access.\n- `Form.schema`: schema(): Promise<FormDetail> — The form's presentation and column facts; this never contains response rows.\n- `Form.sections`: sections(): Promise<FormSection[]> — Sections in display order.\n- `Form.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read the form's sharing grants.\n- `Form.submit`: submit(answers): Promise<FormSubmissionOutcome> — Submit answers.\n- `Form.tally`: tally(): Promise<FormQuestionTally[]> — Choice and checkbox counts, available to viewers when tally visibility is enabled.\n- `Form.update`: update(updates): Promise<Form> — Update presentation or owner-controlled settings; null explicitly clears the closing time.\n- `Form.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Update grants.\n- `Form.webUrl`: webUrl(): string — Open the form's builder in Macro.\n- `Form.byId`: static byId(client, id): Form — A form handle with details loaded on demand.\n- `Form.create`: static create(client, options): Promise<Form> — Create a form, optionally over a table of a database the caller owns.\n- `Form.list`: static list(client, database?): Promise<Form[]> — Forms shared with the caller, or live forms over a specified database.\n\n### FormReference\nA typed reference read from a form answer, without fetching the referenced entity.\nFields: entityType, id\n- `FormReference.byId`: static byId(entityType, id): FormReference — Construct a reference when its kind and identifier are known.\n\n### FormNamespace (`macro.forms`)\nForms collect answers into a database table without granting respondents table access.\n- `FormNamespace.byId`: byId(id): Form — A form handle.\n- `FormNamespace.create`: create(options): Promise<Form> — Create a form over an existing table, or create its own Responses database.\n- `FormNamespace.list`: list(database?): Promise<Form[]> — List forms shared with the caller, or forms over a database the caller can read.\n\n### FormOption\nA choice of one form question, resolved through that question's current options.\nFields: id, question\n- `FormOption.color`: color(): Promise<string | undefined> — The choice's color, when one is set.\n- `FormOption.detail`: detail(): Promise<QuestionOption> — The choice's label and color.\n- `FormOption.label`: label(): Promise<string> — The choice's label.\n- `FormOption.byId`: static byId(question, id): FormOption — A handle to a known choice of a question.\n\n### FormQuestion\nOne question, backed by a column.\nFields: form, id\n- `FormQuestion.column`: column(): Promise<DatabaseColumn> — The column behind the question.\n- `FormQuestion.detail`: detail(): Promise<FormQuestionDetail> — The question's current presentation and column facts.\n- `FormQuestion.options`: options(): Promise<FormOption[]> — Current choices, in display order.\n- `FormQuestion.title`: title(): Promise<string> — The question's current title (its column's name).\n- `FormQuestion.byId`: static byId(form, id): FormQuestion — A question handle within a form.\n\n### FormResponse\nA cached receipt for the caller's response; other respondents' receipts are private.\nFields: form, id\n- `FormResponse.answers`: answers(): Promise<FormAnswer[]> — Answers as submitted or last read.\n- `FormResponse.booking`: booking(): Promise<FormBookingStep | undefined> — The booking step unlocked by this saved response, if any.\n- `FormResponse.refresh`: refresh(): Promise<FormResponse> — Reload the caller's current receipt; requires a signed-in respondent.\n- `FormResponse.row`: row(): Promise<DatabaseRow | undefined> — The receipt's row, if any.\n- `FormResponse.status`: status(): Promise<ResponseStatus> — Whether this receipt was submitted or stopped by a gate.\n- `FormResponse.byId`: static byId(form, id, snapshot?): FormResponse — A response handle, optionally seeded with an already returned receipt.\n\n### FormSection\nAn ordered group of questions, or a gate between groups.\nFields: form, id\n- `FormSection.detail`: detail(): Promise<FormSectionDetail> — The section's current presentation.\n- `FormSection.questions`: questions(): Promise<FormQuestion[]> — Questions in display order; gates contain no questions.\n- `FormSection.title`: title(): Promise<string> — The section heading.\n- `FormSection.byId`: static byId(form, id): FormSection — A section handle within a form.\n\nTypes: `FormEntityHandle`, `FormAnswer`, `FormAnswerValue`, `FormBookingStep`, `FormBookingTarget`, `FormLayoutResult`, `FormQuestionPlacement`, `FormQuestionTally`, `FormResponseSummary`, `FormRuleTest`, `FormRules`, `FormSectionPlacement`, `FormSubmissionOutcome`, `MyFormResponse`\n"
+ "index": "## forms\nBuild forms and read responses.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Form\nA form over a database table.\nExtends `MacroEntity`.\nFields: access, audience, closesAt, database, description, id, name, owner, status, table\n- `Form.editResponse`: editResponse(answers): Promise<FormSubmissionOutcome> — Replace the caller's answers while the form is open; gates are evaluated again.\n- `Form.myResponse`: myResponse(): Promise<MyFormResponse> — Read the caller's receipt and answers without reading anyone else's responses.\n- `Form.questions`: questions(): Promise<FormQuestion[]> — All questions in display order, skipping gates.\n- `Form.replaceLayout`: replaceLayout(sections): Promise<FormLayoutResult> — Save a replacement in the shared draft.\n- `Form.respondUrl`: respondUrl(): string — The respondent page, which public forms also expose without signing in.\n- `Form.responseSummary`: responseSummary(): Promise<FormResponseSummary> — Ledger counts and total table rows; requires edit access.\n- `Form.schema`: schema(): Promise<FormDetail> — The form's presentation and column facts; this never contains response rows.\n- `Form.sections`: sections(): Promise<FormSection[]> — Sections in display order.\n- `Form.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read the form's sharing grants.\n- `Form.submit`: submit(answers): Promise<FormSubmissionOutcome> — Submit answers.\n- `Form.tally`: tally(): Promise<FormQuestionTally[]> — Choice and checkbox counts, available to viewers when tally visibility is enabled.\n- `Form.update`: update(updates): Promise<Form> — Update presentation or owner-controlled settings; null explicitly clears the closing time.\n- `Form.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Update grants.\n- `Form.webUrl`: webUrl(): string — Open the form's builder in Macro.\n- `Form.byId`: static byId(client, id): Form — A form handle with details loaded on demand.\n- `Form.create`: static create(client, options): Promise<Form> — Create a form, optionally over a table of a database the caller owns.\n- `Form.list`: static list(client, database?): Promise<Form[]> — Forms shared with the caller, or live forms over a specified database.\n\n### FormReference\nA typed reference read from a form answer, without fetching the referenced entity.\nFields: entityType, id\n- `FormReference.byId`: static byId(entityType, id): FormReference — Construct a reference when its kind and identifier are known.\n\n### FormNamespace (`macro.forms`)\nForms collect answers into a database table without granting respondents table access.\n- `FormNamespace.byId`: byId(id): Form — A form handle.\n- `FormNamespace.create`: create(options): Promise<Form> — Create a form over an existing table, or create its own Responses database.\n- `FormNamespace.list`: list(database?): Promise<Form[]> — List forms shared with the caller, or forms over a database the caller can read.\n\n### FormOption\nA choice of one form question, resolved through that question's current options.\nFields: id, question\n- `FormOption.color`: color(): Promise<string | undefined> — The choice's color, when one is set.\n- `FormOption.detail`: detail(): Promise<QuestionOption> — The choice's label and color.\n- `FormOption.label`: label(): Promise<string> — The choice's label.\n- `FormOption.byId`: static byId(question, id): FormOption — A handle to a known choice of a question.\n\n### FormQuestion\nOne question, backed by a column.\nFields: form, id\n- `FormQuestion.column`: column(): Promise<DatabaseColumn> — The column behind the question.\n- `FormQuestion.detail`: detail(): Promise<FormQuestionDetail> — The question's current presentation and column facts.\n- `FormQuestion.options`: options(): Promise<FormOption[]> — Current choices, in display order.\n- `FormQuestion.title`: title(): Promise<string> — The question's current title (its column's name).\n- `FormQuestion.byId`: static byId(form, id): FormQuestion — A question handle within a form.\n\n### FormResponse\nA cached receipt for the caller's response; other respondents' receipts are private.\nFields: form, id\n- `FormResponse.answers`: answers(): Promise<FormAnswer[]> — Answers as submitted or last read.\n- `FormResponse.booking`: booking(): Promise<FormBookingStep | undefined> — The booking step unlocked by this saved response, if any.\n- `FormResponse.refresh`: refresh(): Promise<FormResponse> — Reload the caller's current receipt; requires a signed-in respondent.\n- `FormResponse.row`: row(): Promise<DatabaseRow | undefined> — The receipt's row, if any.\n- `FormResponse.status`: status(): Promise<ResponseStatus> — Whether this receipt was submitted or stopped by a gate.\n- `FormResponse.byId`: static byId(form, id, snapshot?): FormResponse — A response handle, optionally seeded with an already returned receipt.\n\n### FormSection\nAn ordered group of questions, or a gate between groups.\nFields: form, id\n- `FormSection.detail`: detail(): Promise<FormSectionDetail> — The section's current presentation.\n- `FormSection.questions`: questions(): Promise<FormQuestion[]> — Questions in display order; gates contain no questions.\n- `FormSection.title`: title(): Promise<string> — The section heading.\n- `FormSection.byId`: static byId(form, id): FormSection — A section handle within a form.\n\nTypes: `FormEntityHandle`, `FormAnswer`, `FormAnswerValue`, `FormBookingStep`, `FormBookingTarget`, `FormLayoutResult`, `FormQuestionPlacement`, `FormQuestionTally`, `FormResponseSummary`, `FormRuleTest`, `FormRules`, `FormSectionPlacement`, `FormSubmissionOutcome`, `MyFormResponse`, `SavedFormResponse`\n"
},
{
"name": "notifications",
@@ -627,8 +627,8 @@
"FilterTest": "# Type Alias: FilterTest\n\n> **FilterTest** = \\{ `kind`: `\"presence\"`; `operator`: `PresenceOperator`; \\} \\| \\{ `kind`: `\"text\"`; `operator`: `TextOperator`; `value`: `string`; \\} \\| \\{ `kind`: `\"number\"`; `operator`: `NumberOperator`; `value`: `number`; \\} \\| \\{ `kind`: `\"date\"`; `operator`: `DateOperator`; `value`: `string`; \\} \\| \\{ `kind`: `\"dateRange\"`; `operator`: `DateRangeOperator`; `value`: `string`; \\} \\| \\{ `checked`: `boolean`; `kind`: `\"checkbox\"`; \\} \\| \\{ `kind`: `\"options\"`; `operator`: `SetOperator`; `options`: `string`[]; \\} \\| \\{ `entities`: `string`[]; `kind`: `\"entities\"`; `operator`: `SetOperator`; \\}\n\nWhat a column's cell must be, by the kind of value the column holds.\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"presence\"`; `operator`: `PresenceOperator`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"presence\"` | - |\n| `operator` | `PresenceOperator` | Empty, or not. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"text\"`; `operator`: `TextOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"text\"` | - |\n| `operator` | `TextOperator` | How the cell compares. |\n| `value` | `string` | The text compared against, ignoring case for the containment tests. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"number\"`; `operator`: `NumberOperator`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"number\"` | - |\n| `operator` | `NumberOperator` | How the cell compares. |\n| `value` | `number` | The number compared against; finite. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"date\"`; `operator`: `DateOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"date\"` | - |\n| `operator` | `DateOperator` | How the cell compares. |\n| `value` | `string` | The date-time compared against. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"dateRange\"`; `operator`: `DateRangeOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"dateRange\"` | - |\n| `operator` | `DateRangeOperator` | How the cell's range stands to the day. |\n| `value` | `string` | The start of the day compared against. |\n\n***\n\n### Type Literal\n\n\\{ `checked`: `boolean`; `kind`: `\"checkbox\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `checked` | `boolean` | Whether the box is checked. |\n| `kind` | `\"checkbox\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"options\"`; `operator`: `SetOperator`; `options`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"options\"` | - |\n| `operator` | `SetOperator` | How the cell's options relate to these. |\n| `options` | `string`[] | Options of the column; at least one. |\n\n***\n\n### Type Literal\n\n\\{ `entities`: `string`[]; `kind`: `\"entities\"`; `operator`: `SetOperator`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `entities` | `string`[] | Entity ids, or for a relation the related rows' ids; at least one. |\n| `kind` | `\"entities\"` | - |\n| `operator` | `SetOperator` | How the cell's references relate to these. |",
"FollowupState": "# Type Alias: FollowupState\n\n> **FollowupState** = `\"archiving\"` \\| `\"pending\"` \\| `\"returning\"` \\| `\"returned\"` \\| `\"cancelled\"` \\| `\"removed\"`\n\nDurable progress of an email operation.",
"storage.ForeignEntity": "# Type Alias: ForeignEntity\n\n> **ForeignEntity** = \\{ `createdAt`: `string`; `foreignEntityId`: `string`; `foreignEntitySource`: `string`; `id`: `string`; `metadata`: `unknown`; `storedForAuthEntity`: `string`; `storedForId`: `string`; `updatedAt`: `string`; \\}\n\nA persisted mapping to an entity owned by an external system.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Timestamp when the record was created. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId` | `string` | Identifier assigned by the external system. |\n| <a id=\"property-foreignentitysource\"></a> `foreignEntitySource` | `string` | Source system that owns the external identifier. |\n| <a id=\"property-id\"></a> `id` | `string` | Internal primary key for this foreign entity record. |\n| <a id=\"property-metadata\"></a> `metadata` | `unknown` | Arbitrary metadata stored with the mapping. |\n| <a id=\"property-storedforauthentity\"></a> `storedForAuthEntity` | `string` | Internal auth entity namespace this foreign entity is stored for. |\n| <a id=\"property-storedforid\"></a> `storedForId` | `string` | Internal entity identifier this foreign entity is stored for. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Timestamp when the record was last updated. |",
- "storage.Form": "# Type Alias: Form\n\n> **Form** = \\{ `audience`: `Audience`; `branding`: `FormBranding`; `closesAt`: `string` \\| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \\| `null`; `respondentColumnId`: `string` \\| `null`; `status`: `FormStatus`; `submittedColumnId`: `string` \\| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \\}\n\nA form: a view of one database table whose rows are its responses.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-audience\"></a> `audience` | `Audience` | Who may respond. |\n| <a id=\"property-branding\"></a> `branding` | `FormBranding` | Its logo, cover image and accent color. |\n| <a id=\"property-closesat\"></a> `closesAt` | `string` \\| `null` | When it stops taking responses, if it does. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage` | `string` | What a respondent reads once their response is saved; empty for the default. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was created. |\n| <a id=\"property-databaseid\"></a> `databaseId` | `string` | The database holding its responses. |\n| <a id=\"property-description\"></a> `description` | `string` | What respondents read under the name. |\n| <a id=\"property-id\"></a> `id` | `string` | The form. |\n| <a id=\"property-ishiddenindrive\"></a> `isHiddenInDrive` | `boolean` | Whether Drive leaves it, and the database behind it, out of its listings, as for a channel poll. |\n| <a id=\"property-name\"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Its owner. |\n| <a id=\"property-projectid\"></a> `projectId` | `string` \\| `null` | The folder it is filed in; `null` at the root. |\n| <a id=\"property-respondentcolumnid\"></a> `respondentColumnId` | `string` \\| `null` | The person column each signed-in submission names its respondent in; `null` once deleted. |\n| <a id=\"property-status\"></a> `status` | `FormStatus` | Whether its owner closed it. |\n| <a id=\"property-submittedcolumnid\"></a> `submittedColumnId` | `string` \\| `null` | The date column each submission stamps; `null` once deleted. |\n| <a id=\"property-tableid\"></a> `tableId` | `string` | The table whose rows are its responses. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible` | `boolean` | Whether respondents may read option tallies. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When its facts or layout last changed. |",
- "FormAccess": "# Type Alias: FormAccess\n\n> **FormAccess** = `\"view\"` \\| `\"edit\"` \\| `\"owner\"`\n\nThe caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it.",
+ "storage.Form": "# Type Alias: Form\n\n> **Form** = \\{ `anonymous`: `boolean`; `audience`: `Audience`; `branding`: `FormBranding`; `closesAt`: `string` \\| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \\| `null`; `respondentColumnId`: `string` \\| `null`; `responsesVisible`: `boolean`; `status`: `FormStatus`; `submittedColumnId`: `string` \\| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \\}\n\nA form: a view of one database table whose rows are its responses.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-anonymous\"></a> `anonymous` | `boolean` | Whether nobody, the owner included, can see who gave which response. Who responded is kept apart from the responses, only so nobody responds twice. Fixed once anyone has responded. |\n| <a id=\"property-audience\"></a> `audience` | `Audience` | Who may respond. |\n| <a id=\"property-branding\"></a> `branding` | `FormBranding` | Its logo, cover image and accent color. |\n| <a id=\"property-closesat\"></a> `closesAt` | `string` \\| `null` | When it stops taking responses, if it does. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage` | `string` | What a respondent reads once their response is saved; empty for the default. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was created. |\n| <a id=\"property-databaseid\"></a> `databaseId` | `string` | The database holding its responses. |\n| <a id=\"property-description\"></a> `description` | `string` | What respondents read under the name. |\n| <a id=\"property-id\"></a> `id` | `string` | The form. |\n| <a id=\"property-ishiddenindrive\"></a> `isHiddenInDrive` | `boolean` | Whether Drive leaves it, and the database behind it, out of its listings, as for a channel poll. |\n| <a id=\"property-name\"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Its owner. |\n| <a id=\"property-projectid\"></a> `projectId` | `string` \\| `null` | The folder it is filed in; `null` at the root. |\n| <a id=\"property-respondentcolumnid\"></a> `respondentColumnId` | `string` \\| `null` | The person column each signed-in submission names its respondent in; `null` once deleted, and on a form created anonymous. An anonymous form never writes it. |\n| <a id=\"property-responsesvisible\"></a> `responsesVisible` | `boolean` | Whether people with View may read individual response rows. |\n| <a id=\"property-status\"></a> `status` | `FormStatus` | Whether its owner closed it. |\n| <a id=\"property-submittedcolumnid\"></a> `submittedColumnId` | `string` \\| `null` | The date column each submission stamps; `null` once deleted. |\n| <a id=\"property-tableid\"></a> `tableId` | `string` | The table whose rows are its responses. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible` | `boolean` | Whether respondents may read option tallies. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When its facts or layout last changed. |",
+ "FormAccess": "# Type Alias: FormAccess\n\n> **FormAccess** = `\"view\"` \\| `\"edit\"` \\| `\"owner\"`\n\nThe caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it.",
"FormBranding": "# Type Alias: FormBranding\n\n> **FormBranding** = \\{ `accentColor`: `null` \\| `AccentColor`; `coverFileId`: `string` \\| `null`; `logoFileId`: `string` \\| `null`; \\}\n\nA form's logo, cover image and accent color, each unset by default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accentcolor\"></a> `accentColor` | `null` \\| `AccentColor` | - |\n| <a id=\"property-coverfileid\"></a> `coverFileId` | `string` \\| `null` | The static file shown as a banner across the top of the page. |\n| <a id=\"property-logofileid\"></a> `logoFileId` | `string` \\| `null` | The static file shown as the logo above the title. |",
"FormDetail": "# Type Alias: FormDetail\n\n> **FormDetail** = \\{ `access`: `FormAccess`; `form`: `storage.Form`; `sections`: `FormSectionDetail`[]; `tableGone`: `boolean`; \\}\n\nA form with its layout, as the caller may see it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `FormAccess` | The caller's level on it. |\n| <a id=\"property-form\"></a> `form` | `storage.Form` | The form's facts. |\n| <a id=\"property-sections\"></a> `sections` | `FormSectionDetail`[] | Its sections, in order. |\n| <a id=\"property-tablegone\"></a> `tableGone` | `boolean` | Whether its database is in the trash, so it has no table to show or write: its sections keep no questions and it takes no responses. |",
"FormPublicationProblem": "# Type Alias: FormPublicationProblem\n\n> **FormPublicationProblem** = \\{ `kind`: `\"invalidDraft\"`; \\} \\| \\{ `kind`: `\"layout\"`; `problem`: `LayoutProblem`; \\} \\| \\{ `kind`: `\"widgetMismatch\"`; `question`: `string`; \\} \\| \\{ `kind`: `\"fileUploadNeedsSignIn\"`; \\} \\| \\{ `kind`: `\"pending\"`; \\}\n\nAn editor's saved draft is not yet the version respondents can use.\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"invalidDraft\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"layout\"`; `problem`: `LayoutProblem`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"layout\"` | - |\n| `problem` | `LayoutProblem` | The invariant the editor needs to repair. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"widgetMismatch\"`; `question`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"widgetMismatch\"` | - |\n| `question` | `string` | The question to repair. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"fileUploadNeedsSignIn\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"pending\"`; \\}",
@@ -764,7 +764,7 @@
"UnlockedBooking": "# Type Alias: UnlockedBooking\n\n> **UnlockedBooking** = \\{ `description`: `string`; `section`: `string`; `target`: `BookingTarget`; `title`: `string`; \\}\n\nA booking step a passing response has unlocked, with its destination.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-description\"></a> `description` | `string` | What respondents read before choosing a time. |\n| <a id=\"property-section\"></a> `section` | `string` | The booking section. |\n| <a id=\"property-target\"></a> `target` | `BookingTarget` | The native booking event to open. |\n| <a id=\"property-title\"></a> `title` | `string` | Its title. |",
"UpdateChannelSharePermission": "# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| `storage.AccessLevel`; `channelId`: `string`; `operation`: `UpdateOperation`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| `storage.AccessLevel` | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | `UpdateOperation` | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |",
"UpdateCrmTeamSettingsRequest": "# Type Alias: UpdateCrmTeamSettingsRequest\n\n> **UpdateCrmTeamSettingsRequest** = \\{ `closed_stage_ids?`: `string`[] \\| `null`; `default_team_view_id?`: `string` \\| `null`; `delete_records_role?`: `null` \\| `CrmPermissionRole`; `edit_stages_role?`: `null` \\| `CrmPermissionRole`; `move_closed_deals_role?`: `null` \\| `CrmPermissionRole`; `team_views?`: `unknown`; \\}\n\nRequest body for `PUT /crm/settings`. Every field is optional:\nomitted fields keep their current values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-closed_stage_ids\"></a> `closed_stage_ids?` | `string`[] \\| `null` | New closed-stage set. Omit to keep the current value; pass `null` to clear it (falling back to the client label heuristic). |\n| <a id=\"property-default_team_view_id\"></a> `default_team_view_id?` | `string` \\| `null` | New default team view id. Omit to keep the current value; pass `null` to clear it. |\n| <a id=\"property-delete_records_role\"></a> `delete_records_role?` | `null` \\| `CrmPermissionRole` | - |\n| <a id=\"property-edit_stages_role\"></a> `edit_stages_role?` | `null` \\| `CrmPermissionRole` | - |\n| <a id=\"property-move_closed_deals_role\"></a> `move_closed_deals_role?` | `null` \\| `CrmPermissionRole` | - |\n| <a id=\"property-team_views\"></a> `team_views?` | `unknown` | Replacement team-views array (whole-blob, last write wins). |",
- "UpdateForm": "# Type Alias: UpdateForm\n\n> **UpdateForm** = \\{ `accentColor?`: `string` \\| `null`; `audience?`: `Audience`; `closesAt?`: `string` \\| `null`; `confirmationMessage?`: `string`; `coverFileId?`: `string` \\| `null`; `description?`: `string`; `logoFileId?`: `string` \\| `null`; `status?`: `FormStatus`; `tallyVisible?`: `boolean`; \\}\n\nA change to a form's facts; what is left out stays. The description,\nconfirmation message and branding take edit, the rest owner. A form is renamed\nthrough the entity mutation router.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accentcolor\"></a> `accentColor?` | `string` \\| `null` | A new accent color, or `null` for the default. |\n| <a id=\"property-audience\"></a> `audience?` | `Audience` | Who may respond from now on. |\n| <a id=\"property-closesat\"></a> `closesAt?` | `string` \\| `null` | When it stops taking responses, or `null` for never. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage?` | `string` | Its new confirmation message. |\n| <a id=\"property-coverfileid\"></a> `coverFileId?` | `string` \\| `null` | A new cover image, or `null` to remove it. |\n| <a id=\"property-description\"></a> `description?` | `string` | Its new description. |\n| <a id=\"property-logofileid\"></a> `logoFileId?` | `string` \\| `null` | A new logo, or `null` to remove it. |\n| <a id=\"property-status\"></a> `status?` | `FormStatus` | Open or close it. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible?` | `boolean` | Whether respondents may read option tallies. |",
+ "UpdateForm": "# Type Alias: UpdateForm\n\n> **UpdateForm** = \\{ `accentColor?`: `string` \\| `null`; `anonymous?`: `boolean`; `audience?`: `Audience`; `closesAt?`: `string` \\| `null`; `confirmationMessage?`: `string`; `coverFileId?`: `string` \\| `null`; `description?`: `string`; `logoFileId?`: `string` \\| `null`; `responsesVisible?`: `boolean`; `status?`: `FormStatus`; `tallyVisible?`: `boolean`; \\}\n\nA change to a form's facts; what is left out stays. The description,\nconfirmation message and branding take edit, the rest owner. A form is renamed\nthrough the entity mutation router.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accentcolor\"></a> `accentColor?` | `string` \\| `null` | A new accent color, or `null` for the default. |\n| <a id=\"property-anonymous\"></a> `anonymous?` | `boolean` | Whether nobody can see who gave which response; refused once anyone has responded. |\n| <a id=\"property-audience\"></a> `audience?` | `Audience` | Who may respond from now on. |\n| <a id=\"property-closesat\"></a> `closesAt?` | `string` \\| `null` | When it stops taking responses, or `null` for never. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage?` | `string` | Its new confirmation message. |\n| <a id=\"property-coverfileid\"></a> `coverFileId?` | `string` \\| `null` | A new cover image, or `null` to remove it. |\n| <a id=\"property-description\"></a> `description?` | `string` | Its new description. |\n| <a id=\"property-logofileid\"></a> `logoFileId?` | `string` \\| `null` | A new logo, or `null` to remove it. |\n| <a id=\"property-responsesvisible\"></a> `responsesVisible?` | `boolean` | Whether people with View may read individual response rows. |\n| <a id=\"property-status\"></a> `status?` | `FormStatus` | Open or close it. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible?` | `boolean` | Whether respondents may read option tallies. |",
"UpdateMeetingRequest": "# Type Alias: UpdateMeetingRequest\n\n> **UpdateMeetingRequest** = \\{ `clearSchedule?`: `boolean`; `scheduledEnd?`: `string` \\| `null`; `scheduledStart?`: `string` \\| `null`; `title?`: `string` \\| `null`; \\}\n\nChanges to a meeting's title or scheduled time; omitted values stay unchanged.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-clearschedule\"></a> `clearSchedule?` | `boolean` | Remove timed scheduling, for example when the calendar event becomes all-day. |\n| <a id=\"property-scheduledend\"></a> `scheduledEnd?` | `string` \\| `null` | Replacement scheduled end; requires a matching start. |\n| <a id=\"property-scheduledstart\"></a> `scheduledStart?` | `string` \\| `null` | Replacement scheduled start; requires a matching end. |\n| <a id=\"property-title\"></a> `title?` | `string` \\| `null` | Replacement title, when supplied. |",
"UpdateOperation": "# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`",
"UpdateSharePermissionRequestV2": "# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: `UpdateChannelSharePermission`[] \\| `null`; `linkShare?`: `null` \\| `storage.LinkShare`; `linkShareAccessLevel?`: `null` \\| `storage.AccessLevel`; `teamShareAccessLevel?`: `null` \\| `storage.AccessLevel`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | `UpdateChannelSharePermission`[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| `storage.LinkShare` | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| `storage.AccessLevel` | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| `storage.AccessLevel` | - |",
@@ -1608,7 +1608,8 @@
"FormRules": "# Type Alias: FormRules\n\n> **FormRules** = \\{ `conditions`: (\\{ `column`: `DatabaseColumn`; `kind`: `\"condition\"`; `test`: `FormRuleTest`; \\} \\| \\{ `kind`: `\"group\"`; \\} & `FormRules`)[]; `conjunction`: `FilterGroup`\\[`\"conjunction\"`\\]; \\}\n\nConditions over columns asked in earlier sections.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-conditions\"></a> `conditions` | (\\{ `column`: `DatabaseColumn`; `kind`: `\"condition\"`; `test`: `FormRuleTest`; \\} \\| \\{ `kind`: `\"group\"`; \\} & `FormRules`)[] |\n| <a id=\"property-conjunction\"></a> `conjunction` | `FilterGroup`\\[`\"conjunction\"`\\] |",
"FormSectionPlacement": "# Type Alias: FormSectionPlacement\n\n> **FormSectionPlacement** = \\{ `description?`: `string`; `section?`: `FormSection`; `title`: `string`; \\} & \\{ `kind`: `\"questions\"`; `questions`: `FormQuestionPlacement`[]; \\} \\| \\{ `kind`: `\"gate\"`; `message`: `string`; `rules`: `FormRules`; \\} \\| \\{ `kind`: `\"booking\"`; `target`: `BookingTarget`; \\}\n\nA section in a layout replacement. Omit section to mint a new stable section.\n\n## Type Declaration\n\n| Name | Type |\n| ------ | ------ |\n| `description?` | `string` |\n| `section?` | `FormSection` |\n| `title` | `string` |",
"FormSubmissionOutcome": "# Type Alias: FormSubmissionOutcome\n\n> **FormSubmissionOutcome** = \\{ `booking?`: `FormBookingStep`; `outcome`: `\"submitted\"`; `response`: `FormResponse`; `row`: `DatabaseRow`; \\} \\| \\{ `message`: `string`; `outcome`: `\"stopped\"`; `section`: `FormSection`; \\}\n\nThe result of submitting or editing a response. A stopped submission has no row.",
- "MyFormResponse": "# Type Alias: MyFormResponse\n\n> **MyFormResponse** = \\{ `answers`: `FormAnswer`[]; `booking?`: `FormBookingStep`; `response`: `FormResponse`; `row?`: `DatabaseRow`; `status`: `ResponseStatus`; `stoppedAtSection?`: `FormSection`; `submittedAt`: `string`; `updatedAt`: `string`; \\}\n\nThe caller's receipt and current answers, read without access to other responses.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-answers\"></a> `answers` | `FormAnswer`[] |\n| <a id=\"property-booking\"></a> `booking?` | `FormBookingStep` |\n| <a id=\"property-response\"></a> `response` | `FormResponse` |\n| <a id=\"property-row\"></a> `row?` | `DatabaseRow` |\n| <a id=\"property-status\"></a> `status` | `ResponseStatus` |\n| <a id=\"property-stoppedatsection\"></a> `stoppedAtSection?` | `FormSection` |\n| <a id=\"property-submittedat\"></a> `submittedAt` | `string` |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` |",
+ "MyFormResponse": "# Type Alias: MyFormResponse\n\n> **MyFormResponse** = `SavedFormResponse` \\| \\{ `kind`: `\"anonymous\"`; \\}\n\nThe caller's receipt and current answers, read without access to other\nresponses. On an anonymous form the caller only learns that they\nresponded: nothing links them to their response.",
+ "SavedFormResponse": "# Type Alias: SavedFormResponse\n\n> **SavedFormResponse** = \\{ `answers`: `FormAnswer`[]; `booking?`: `FormBookingStep`; `kind`: `\"saved\"`; `response`: `FormResponse`; `row?`: `DatabaseRow`; `status`: `ResponseStatus`; `stoppedAtSection?`: `FormSection`; `submittedAt`: `string`; `updatedAt`: `string`; \\}\n\nThe caller's saved response to a form that isn't anonymous.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-answers\"></a> `answers` | `FormAnswer`[] |\n| <a id=\"property-booking\"></a> `booking?` | `FormBookingStep` |\n| <a id=\"property-kind\"></a> `kind` | `\"saved\"` |\n| <a id=\"property-response\"></a> `response` | `FormResponse` |\n| <a id=\"property-row\"></a> `row?` | `DatabaseRow` |\n| <a id=\"property-status\"></a> `status` | `ResponseStatus` |\n| <a id=\"property-stoppedatsection\"></a> `stoppedAtSection?` | `FormSection` |\n| <a id=\"property-submittedat\"></a> `submittedAt` | `string` |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` |",
"FormNamespace": "# Class: FormNamespace\n\nForms collect answers into a database table without granting respondents table access.",
"FormNamespace.byId": "### byId()\n\n> **byId**(`id`): `Form`\n\nA form handle. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`Form`",
"FormNamespace.create": "### create()\n\n> **create**(`options`): `Promise`\\<`Form`\\>\n\nCreate a form over an existing table, or create its own Responses database.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `name`: `string`; `table?`: `DatabaseTable`; \\} |\n| `options.name` | `string` |\n| `options.table?` | `DatabaseTable` |\n\n#### Returns\n\n`Promise`\\<`Form`\\>",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 9262fc4b5c..bd2d27f0d4 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,5 +1,5 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class W${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*d($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),l1=Symbol.for("@ts-pattern/isVariadic");var m0=($)=>Boolean($&&typeof $=="object"),Wj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Wj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(m0($)){if(!m0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Wj(X)&&X[l1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Wj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return m0($)?Wj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?cO($,Z$):cO(Object.values($),Z$):[]},cO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function u7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function e($){return Object.assign($,{optional:()=>d0($),and:(O)=>l($,O),or:(O)=>r1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function u0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[l1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>u0(d0($)),select:(O)=>u0(O===void 0?dO($):dO(O,$))})}function d0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var c7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},d7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},l7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>cO($,Z$),matcherType:"and"})})}function r1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return cO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>cO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Z$(j))})})}function p1($){return!0}function q$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var a1=e(u(p1)),r7=e(u(p1)),p7=a1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),d1=s$(u(i$)),w$=($)=>Object.assign(e($),{between:(O,j)=>w$(l($,((x,S)=>u((K)=>q$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x<j))(O))),gt:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x>j))(O))),lte:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x<=j))(O))),gte:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x>=j))(O))),int:()=>w$(l($,u((O)=>q$(O)&&Number.isInteger(O)))),finite:()=>w$(l($,u((O)=>q$(O)&&Number.isFinite(O)))),positive:()=>w$(l($,u((O)=>q$(O)&&O>0))),negative:()=>w$(l($,u((O)=>q$(O)&&O<0)))}),a7=w$(u(q$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),i7=t$(u(n$)),n7=e(u(function($){return typeof $=="boolean"})),s7=e(u(function($){return typeof $=="symbol"})),t7=e(u(function($){return $==null})),e7=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:d0,array:function(...$){return u0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:c7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:d7(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[d1,$[0]]:$;return{matched:l7(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:r1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:dO,any:a1,unknown:r7,_:p7,string:d1,number:a7,bigint:i7,boolean:n7,symbol:s7,nullish:t7,nonNullable:e7,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(u7($)))}};class i1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var c0={matched:!1,value:void 0};function k($){return new Bj($,c0)}class Bj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?c0:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Bj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Bj(this.input,j?{matched:!0,value:O(this.input,this.input)}:c0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=o7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function o7($){throw new i1($)}class b extends Error{constructor($){super($);this.name="MacroError"}}var n1=500;function $5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>n1?`${O.slice(0,n1)}…`:O}class GO extends b{status;data;constructor($,O){let j=$5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends b{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new GO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class H$ extends A{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var O5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function e$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>O5[x]??x);return`<${$}>${j}</${$}>`}function j5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var x5={toMention:()=>({tag:e$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function S5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(j5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:Z5(x)}}function Z5($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class B$ extends A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends A{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:l0($)}))}}function l0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Lj($,O,j,x=[]){let{channelId:S,thread:K}=K5(O);if(await Y5($)){let{id:X}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Y)=>({entity_type:X5,entity_id:Y.id,width:Y.width??null,height:Y.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=G(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var X5="static/image";function K5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function Y5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Lj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Nj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:c.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new r0(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class r0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return c.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function f$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:C.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var G5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??G5;return d(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class QO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return C.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new QO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends K${async recordActivity($){return new QO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return f$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Nj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Lj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return d(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return d(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class C extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new C($,O)}static fromName($,O){return new C($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new C($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:e$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?C.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async submit($,O){return IO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:C.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>C.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function o$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new p0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class p0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}async function Uj($,O,j,x){G(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class lO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new lO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>Uj(this.client,this.parent,$,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class zj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new zj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class rO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new rO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class c extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return rO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:o$($)}))}static byId($,O){return new c($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new c($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=G(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>c.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?C.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=G(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){G(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return G(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return G(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>zj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>Uj(this.client,this,$)};codeExecutions={byId:($)=>lO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class a0{client;constructor($){this.client=$}byId($){return c.byId(this.client,$)}createManaged($){return c.createManaged(this.client,$)}chooseMode($){return c.chooseMode(this.client,$)}repositories(){return c.repositories(this.client)}repositoryBranches($){return c.repositoryBranches(this.client,$)}forPullRequest($){return c.forPullRequest(this.client,$)}defaultSandboxSize(){return c.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return c.setDefaultSandboxSize(this.client,$)}codingPreferences(){return c.codingPreferences(this.client)}autoArchivePreferences(){return c.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return c.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return c.setCodingPreferences(this.client,$)}}class i0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,G(await this.client.storage.createAgent({body:l0($)})))}}class n0{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class $O extends A{static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class s0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>$O.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:$O.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class pO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class aO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends A{async fetch(){throw new b(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:Q5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new aO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function Q5($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class t0{client;async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return d(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=V5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:s1(K.event,S),inbox:Z?.emailAddress,role:W5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:C.byId(this.client,j)})),members:O.members.map((j)=>({user:C.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:C.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new aO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:J5($)}));return S$.fromRecord(this.client,O)}}function J5($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function V5($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function s1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function W5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&s1($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return f$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>C.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class e0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class o0{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class $x{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new QO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new o0($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends K${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Y$ extends K${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Y$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Y$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Y$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Y$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Y$($,O.chat_id)});toMention(){return{tag:e$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Ox{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class _$ extends A{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:C.byId(this.client,O.user_id),role:O.role}))}}var B5=8;class A$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new A$($,O,j)}static from($,O,j){return new A$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Ij($,O){let j={parent_type:O.type,parent_id:O.id},x=d(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,B5,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>A$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class b$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return f$(this.client,{type:"crm_contact",entity:this},(O)=>A$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>k$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Ij(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return f$(this.client,{type:"crm_company",entity:this},(O)=>A$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>b$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return b$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Ij(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class OO extends A{tableDetail=new W$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>C.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:o$($)}))}async table(){return Hj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return d(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return d(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Hj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Hj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Tj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class JO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Tj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Tj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class jx{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>OO.from(this.client,$))}async create($){return OO.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class xx{client;pipelines;constructor($){this.client=$;this.pipelines=new jx($)}companyById($){return k$.byId(this.client,$)}contactById($){return b$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?b$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>b$.from(this.client,x))}async createCompany($){return k$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Sx,L5=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(L5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function t1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function N5($,O,j){let x;if($)x=e1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();U5(Zx,S,K),x=e1(K,Zx.msecs,Zx.seq,O,j)}return O??t1(x)}function U5($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function e1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=N5;class P${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new P$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>P$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:P$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?z5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function z5($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Yx extends GO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Cj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var I5={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function H5($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>I5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:c$(),label:O}))}function o1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!o1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class G$ extends A{access=new $$(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new G$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new G$($,j.id)}async duplicate($){let O=G(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new G$(this.client,O.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new G$($,j.database.id))}query($,O){return _j(this.client,G$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>C.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Yx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new b(`expected one reorder_tables result, got ${O.map(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),C.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Cj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Cj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${H5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Cj(O.to),options:Xx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!o1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return P$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new b(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Cj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return P$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Gx{client;constructor($){this.client=$}query($,O){return _j(this.client,G$.byId,$,O)}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}list(){return G$.list(this.client)}}class VO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class tO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new tO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var T5=8;class w extends K${async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return tO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return f$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return d(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>C.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new GO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=d(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,T5,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return l$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:e$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?C.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends A{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=G(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?o$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=G(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends A{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return G(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new BO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Jx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:eO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return eO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class eO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new eO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Jx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class LO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class jO extends A{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new jO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new jO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new jO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Vx{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return d(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return d(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return jO.byId(this.client,$)}labels(){return jO.list(this.client)}createLabel($){return jO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}function Bx($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return G(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class xO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class SO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new SO(O,$)}static from($,O){return new SO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class ZO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new ZO($,O,j)}static from($,O,j){return new ZO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:SO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>xO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return G(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>xO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*d(async(O)=>{let j=G(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return G(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=G(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return SO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return ZO.from(this.client,this,x)}async sends(){return G(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>ZO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return G(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>ZO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return G(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return G(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class XO extends H${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function $2({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async bySource($,O){return XO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map($2),assignees:j.map($2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return P$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class TO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new TO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Pj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Pj($,O)}}class y$ extends A{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>C.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>G$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(G$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new b(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:k(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new b("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:TO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Pj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Q=V$.byId(G$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new b(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:TO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class zx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class RO extends A{static byId($,O){return new RO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return RO.byId(this.client,$)}forEntity($){return RO.byId(this.client,$.id)}}class DO extends A{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class oO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new oO($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>c.byId(this.client,$.session_id))}pairing($){return DO.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:DO.byId(this.client,O.code),device:oO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=G(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(R5)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function R5($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var D5="00000001-0000-0000-0000-000000000001",O2="00000001-0000-0000-0000-000000000002",_5="00000001-0000-0000-0000-000000000004",M5="00000001-0000-0000-0000-000000000014",C5="00000001-0000-0000-0002-000000000001",A5="00000001-0000-0000-0002-000000000004";function P5($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class Q$ extends w{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await F5($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=G(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:C.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=G(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=P5(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===O2)?.value;return j?.type==="SelectOption"&&j.value.includes(A5)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function F5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await C.me($)],x=[{propertyId:O2,value:{type:"select_option",option_id:C5}}];if(j.length>0)x.push({propertyId:D5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:M5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:_5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>C.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>C.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Q$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?o$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends A{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return d(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?C.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Mx{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Cx{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class Ax{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class _O{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new _O($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class KO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new KO($,j.id,j)}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>_O.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return _O.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return _O.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Px{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return KO.fromRecord(this.client,x)})}create($){return KO.create(this.client,$)}definition($){return KO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function Fx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function E5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class v$ extends A{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>C.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(G($))}async shareAsTemplate($){return this.toTemplate(G(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,G(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...qj($),enabled:$.enabled??!0}})))}toTemplate($){return new j2(this,C.byId(this.client,$.author),$)}async stopSharingTemplate(){G(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:qj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>c.byId(this.client,O.id)).with({type:"chat"},(O)=>Y$.byId(this.client,O.id)).exhaustive();return $.chat_id?Y$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class j2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function qj($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:E5($.trigger),task:{...O}}}class qx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...qj($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return C.byId(this.client,$)}me(){return C.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(C.fromName(this.client,J))}}return K}}class YO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>C.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class MO extends A{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.whatsappAccount());return $?MO.from(this.client,$):void 0}async chats(){return G(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function x2($,O,j){let x=[];for(let S of vx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Y$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:XO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var S2="00000000-0000-0000-0000-000000000000",hx={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),Z2=($,O)=>$==null?O:{"&":[$,O]};function mx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){mx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)mx($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:S2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=Z2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(hx))if(!x.includes(S))O[K]={l:{[Z]:S2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=Z2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*d((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>x2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function X2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class W${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*d($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),l1=Symbol.for("@ts-pattern/isVariadic");var m0=($)=>Boolean($&&typeof $=="object"),Wj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Wj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(m0($)){if(!m0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Wj(X)&&X[l1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Wj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return m0($)?Wj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?cO($,Z$):cO(Object.values($),Z$):[]},cO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function u7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function e($){return Object.assign($,{optional:()=>d0($),and:(O)=>l($,O),or:(O)=>r1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function u0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[l1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>u0(d0($)),select:(O)=>u0(O===void 0?dO($):dO(O,$))})}function d0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var c7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},d7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},l7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>cO($,Z$),matcherType:"and"})})}function r1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return cO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>cO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Z$(j))})})}function p1($){return!0}function q$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var a1=e(u(p1)),r7=e(u(p1)),p7=a1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),d1=s$(u(i$)),w$=($)=>Object.assign(e($),{between:(O,j)=>w$(l($,((x,S)=>u((K)=>q$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x<j))(O))),gt:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x>j))(O))),lte:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x<=j))(O))),gte:(O)=>w$(l($,((j)=>u((x)=>q$(x)&&x>=j))(O))),int:()=>w$(l($,u((O)=>q$(O)&&Number.isInteger(O)))),finite:()=>w$(l($,u((O)=>q$(O)&&Number.isFinite(O)))),positive:()=>w$(l($,u((O)=>q$(O)&&O>0))),negative:()=>w$(l($,u((O)=>q$(O)&&O<0)))}),a7=w$(u(q$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),i7=t$(u(n$)),n7=e(u(function($){return typeof $=="boolean"})),s7=e(u(function($){return typeof $=="symbol"})),t7=e(u(function($){return $==null})),e7=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:d0,array:function(...$){return u0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:c7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:d7(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[d1,$[0]]:$;return{matched:l7(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:r1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:dO,any:a1,unknown:r7,_:p7,string:d1,number:a7,bigint:i7,boolean:n7,symbol:s7,nullish:t7,nonNullable:e7,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(u7($)))}};class i1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var c0={matched:!1,value:void 0};function k($){return new Bj($,c0)}class Bj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?c0:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Bj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Bj(this.input,j?{matched:!0,value:O(this.input,this.input)}:c0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=o7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function o7($){throw new i1($)}class b extends Error{constructor($){super($);this.name="MacroError"}}var n1=500;function $5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>n1?`${O.slice(0,n1)}…`:O}class GO extends b{status;data;constructor($,O){let j=$5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends b{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new GO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class H$ extends A{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var O5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function e$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>O5[x]??x);return`<${$}>${j}</${$}>`}function j5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var x5={toMention:()=>({tag:e$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function S5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(j5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:Z5(x)}}function Z5($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class B$ extends A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends A{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:l0($)}))}}function l0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Lj($,O,j,x=[]){let{channelId:S,thread:K}=K5(O);if(await Y5($)){let{id:X}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Y)=>({entity_type:X5,entity_id:Y.id,width:Y.width??null,height:Y.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=G(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var X5="static/image";function K5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function Y5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Lj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Nj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:c.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new r0(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class r0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return c.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function f$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:C.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var G5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??G5;return d(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class QO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return C.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new QO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends K${async recordActivity($){return new QO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return f$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Nj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Lj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return d(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return d(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class C extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new C($,O)}static fromName($,O){return new C($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new C($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:e$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?C.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async submit($,O){return IO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:C.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>C.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function o$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new p0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class p0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}async function Uj($,O,j,x){G(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class lO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new lO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>Uj(this.client,this.parent,$,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class zj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new zj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class rO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new rO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class c extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return rO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:o$($)}))}static byId($,O){return new c($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new c($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=G(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>c.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?C.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=G(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){G(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return G(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return G(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>zj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>Uj(this.client,this,$)};codeExecutions={byId:($)=>lO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class a0{client;constructor($){this.client=$}byId($){return c.byId(this.client,$)}createManaged($){return c.createManaged(this.client,$)}chooseMode($){return c.chooseMode(this.client,$)}repositories(){return c.repositories(this.client)}repositoryBranches($){return c.repositoryBranches(this.client,$)}forPullRequest($){return c.forPullRequest(this.client,$)}defaultSandboxSize(){return c.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return c.setDefaultSandboxSize(this.client,$)}codingPreferences(){return c.codingPreferences(this.client)}autoArchivePreferences(){return c.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return c.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return c.setCodingPreferences(this.client,$)}}class i0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,G(await this.client.storage.createAgent({body:l0($)})))}}class n0{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class $O extends A{static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class s0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>$O.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:$O.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class pO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class aO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends A{async fetch(){throw new b(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:Q5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new aO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function Q5($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class t0{client;async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return d(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=V5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:s1(K.event,S),inbox:Z?.emailAddress,role:W5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:C.byId(this.client,j)})),members:O.members.map((j)=>({user:C.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:C.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new aO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:J5($)}));return S$.fromRecord(this.client,O)}}function J5($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function V5($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function s1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function W5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&s1($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return f$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>C.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class e0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class o0{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class $x{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new QO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new o0($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends K${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Y$ extends K${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Y$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Y$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Y$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Y$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Y$($,O.chat_id)});toMention(){return{tag:e$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Ox{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class _$ extends A{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:C.byId(this.client,O.user_id),role:O.role}))}}var B5=8;class A$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new A$($,O,j)}static from($,O,j){return new A$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Ij($,O){let j={parent_type:O.type,parent_id:O.id},x=d(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,B5,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>A$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class b$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return f$(this.client,{type:"crm_contact",entity:this},(O)=>A$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>k$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Ij(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return f$(this.client,{type:"crm_company",entity:this},(O)=>A$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>b$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return b$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Ij(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class OO extends A{tableDetail=new W$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>C.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:o$($)}))}async table(){return Hj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return d(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return d(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Hj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Hj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Tj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class JO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Tj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Tj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class jx{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>OO.from(this.client,$))}async create($){return OO.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class xx{client;pipelines;constructor($){this.client=$;this.pipelines=new jx($)}companyById($){return k$.byId(this.client,$)}contactById($){return b$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?b$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>b$.from(this.client,x))}async createCompany($){return k$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Sx,L5=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(L5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function t1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function N5($,O,j){let x;if($)x=e1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();U5(Zx,S,K),x=e1(K,Zx.msecs,Zx.seq,O,j)}return O??t1(x)}function U5($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function e1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=N5;class P${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new P$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>P$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:P$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?z5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function z5($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Yx extends GO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Cj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var I5={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function H5($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>I5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:c$(),label:O}))}function o1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!o1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class G$ extends A{access=new $$(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new G$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new G$($,j.id)}async duplicate($){let O=G(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new G$(this.client,O.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new G$($,j.database.id))}query($,O){return _j(this.client,G$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>C.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Yx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new b(`expected one reorder_tables result, got ${O.map(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),C.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Cj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Cj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${H5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Cj(O.to),options:Xx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!o1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return P$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new b(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Cj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return P$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Gx{client;constructor($){this.client=$}query($,O){return _j(this.client,G$.byId,$,O)}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}list(){return G$.list(this.client)}}class VO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class tO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new tO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var T5=8;class w extends K${async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return tO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return f$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return d(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>C.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new GO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=d(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,T5,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return l$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:e$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?C.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends A{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=G(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?o$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=G(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends A{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return G(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new BO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Jx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:eO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return eO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class eO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new eO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Jx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class LO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class jO extends A{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new jO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new jO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new jO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Vx{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return d(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return d(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return jO.byId(this.client,$)}labels(){return jO.list(this.client)}createLabel($){return jO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}function Bx($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return G(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class xO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class SO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new SO(O,$)}static from($,O){return new SO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class ZO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new ZO($,O,j)}static from($,O,j){return new ZO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:SO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>xO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return G(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>xO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*d(async(O)=>{let j=G(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return G(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=G(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return SO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return ZO.from(this.client,this,x)}async sends(){return G(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>ZO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return G(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>ZO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return G(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return G(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class XO extends H${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function $2({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async bySource($,O){return XO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map($2),assignees:j.map($2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return P$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class TO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new TO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Pj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Pj($,O)}}class y$ extends A{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>C.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>G$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(G$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new b(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:k(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new b("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:TO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Pj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Q=V$.byId(G$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new b(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...S?{booking:S}:{},response:TO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class zx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class RO extends A{static byId($,O){return new RO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return RO.byId(this.client,$)}forEntity($){return RO.byId(this.client,$.id)}}class DO extends A{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class oO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new oO($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>c.byId(this.client,$.session_id))}pairing($){return DO.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:DO.byId(this.client,O.code),device:oO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=G(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(R5)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function R5($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var D5="00000001-0000-0000-0000-000000000001",O2="00000001-0000-0000-0000-000000000002",_5="00000001-0000-0000-0000-000000000004",M5="00000001-0000-0000-0000-000000000014",C5="00000001-0000-0000-0002-000000000001",A5="00000001-0000-0000-0002-000000000004";function P5($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class Q$ extends w{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await F5($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=G(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:C.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=G(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=P5(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===O2)?.value;return j?.type==="SelectOption"&&j.value.includes(A5)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function F5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await C.me($)],x=[{propertyId:O2,value:{type:"select_option",option_id:C5}}];if(j.length>0)x.push({propertyId:D5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:M5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:_5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>C.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>C.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Q$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?o$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends A{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return d(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?C.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Mx{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Cx{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class Ax{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class _O{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new _O($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class KO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new KO($,j.id,j)}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>_O.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return _O.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return _O.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Px{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return KO.fromRecord(this.client,x)})}create($){return KO.create(this.client,$)}definition($){return KO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function Fx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function E5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class v$ extends A{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>C.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(G($))}async shareAsTemplate($){return this.toTemplate(G(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,G(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...qj($),enabled:$.enabled??!0}})))}toTemplate($){return new j2(this,C.byId(this.client,$.author),$)}async stopSharingTemplate(){G(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:qj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>c.byId(this.client,O.id)).with({type:"chat"},(O)=>Y$.byId(this.client,O.id)).exhaustive();return $.chat_id?Y$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class j2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function qj($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:E5($.trigger),task:{...O}}}class qx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...qj($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return C.byId(this.client,$)}me(){return C.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(C.fromName(this.client,J))}}return K}}class YO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>C.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class MO extends A{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.whatsappAccount());return $?MO.from(this.client,$):void 0}async chats(){return G(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function x2($,O,j){let x=[];for(let S of vx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Y$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:XO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var S2="00000000-0000-0000-0000-000000000000",hx={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),Z2=($,O)=>$==null?O:{"&":[$,O]};function mx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){mx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)mx($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:S2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=Z2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(hx))if(!x.includes(S))O[K]={l:{[Z]:S2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=Z2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*d((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>x2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function X2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
diff --git a/crates/entity_access/AGENTS.md b/crates/entity_access/AGENTS.md
index c53a693b13..76b4447c4a 100644
--- a/crates/entity_access/AGENTS.md
+++ b/crates/entity_access/AGENTS.md
@@ -17,6 +17,8 @@ depended-on crates in the backend.
- `src/inbound/axum_extractors.rs`: Axum extractors that resolve a receipt
from the request (feature `inbound`).
- `src/outbound/pg_access_repo.rs`: the Postgres adapter (feature `outbound`).
+ Form Edit/Owner grants Edit on the backing database; form View grants
+ database View only when that form shares its responses.
- `src/bin/explain_access.rs`: CLI to explain why a user has (or lacks)
access to an entity (feature `explain_binary`).
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/database_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/database_access.rs
index 83ae6918ec..1591658b68 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/database_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/database_access.rs
@@ -16,8 +16,9 @@ use uuid::Uuid;
mod test;
/// The highest access level `source_ids` hold on a database: its own grants,
-/// and Edit through edit or owner on any live form over it, so form editors
-/// can read and change their responses. View on a form grants nothing here.
+/// Edit through edit or owner on any live form over it, so form editors
+/// can read and change their responses, and View through view on a live form
+/// that shares its responses. View on a form grants nothing here otherwise.
/// Databases have no share link, so there is no public-sharing arm; a team
/// share is a team-source grant like any other.
/// Both grant paths require an app entity; core storage alone is not shareable.
@@ -50,6 +51,18 @@ pub async fn get_database_access(
AND f.trashed_at IS NULL
AND ea.source_id = ANY($2)
AND ea.access_level IN ('edit', 'owner')
+
+ UNION ALL
+
+ SELECT 'view'
+ FROM forms f
+ JOIN database_entities d ON d.database_id = f.database_id
+ JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'
+ WHERE f.database_id = $1
+ AND f.trashed_at IS NULL
+ AND f.responses_visible
+ AND ea.source_id = ANY($2)
+ AND ea.access_level = 'view'
"#,
database_id,
&source_ids.0,
@@ -76,9 +89,9 @@ pub(super) fn highest_access_level(
}
/// The highest access level a user has on every database their source ids
-/// reach, directly or as Edit through a live form they edit, ordered by
-/// database id. Trash is the databases domain's concern: a trashed database's
-/// grants are still listed.
+/// reach, directly, as Edit through a live form they edit, or as View through
+/// a live form that shares its responses, ordered by database id. Trash is
+/// the databases domain's concern: a trashed database's grants are still listed.
#[tracing::instrument(err, skip(pool, source_ids))]
pub async fn list_database_access(
pool: &PgPool,
@@ -106,6 +119,18 @@ pub async fn list_database_access(
AND ea.source_id = ANY($1)
AND ea.access_level IN ('edit', 'owner')
AND f.trashed_at IS NULL
+
+ UNION ALL
+
+ SELECT f.database_id, 'view'::"AccessLevel"
+ FROM entity_access ea
+ JOIN forms f ON f.id = ea.entity_id
+ JOIN database_entities d ON d.database_id = f.database_id
+ WHERE ea.entity_type = 'form'
+ AND ea.source_id = ANY($1)
+ AND ea.access_level = 'view'
+ AND f.responses_visible
+ AND f.trashed_at IS NULL
"#,
&source_ids.0,
)
@@ -146,7 +171,10 @@ pub async fn explain_database_access(
WHERE f.database_id = $1
AND f.trashed_at IS NULL
AND ea.source_id = ANY($2)
- AND ea.access_level IN ('edit', 'owner')
+ AND (
+ ea.access_level IN ('edit', 'owner')
+ OR (ea.access_level = 'view' AND f.responses_visible)
+ )
ORDER BY f.id
"#,
database_id,
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/database_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/database_access/test.rs
index 5efca6a168..5b0c4b7921 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/database_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/database_access/test.rs
@@ -336,6 +336,39 @@ async fn owning_a_form_grants_only_edit_on_its_database(pool: PgPool) {
);
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn viewing_a_form_that_shares_responses_grants_view_on_its_database(pool: PgPool) {
+ let database_id = insert_database(&pool).await;
+ let form_id = insert_form_over(&pool, database_id, MEMBER, "user", "view").await;
+ sqlx::query!(
+ r#"UPDATE forms SET responses_visible = TRUE WHERE id = $1"#,
+ form_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let member = get_user_source_ids(
+ &pool,
+ Some(&MacroUserIdStr::try_from(MEMBER.to_string()).unwrap()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ get_database_access(&pool, &database_id, &member)
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ assert_eq!(
+ list_database_access(&pool, &member).await.unwrap(),
+ vec![(database_id, AccessLevel::View)]
+ );
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../../fixtures", scripts("user_team"))
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access.rs
index 49ed7b56ee..c3b838e05b 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access.rs
@@ -12,7 +12,8 @@ mod test;
/// The highest access level `source_ids` hold on a database row: a row has
/// no grants of its own, so this is its database's access, including Edit
-/// through a live form over that database.
+/// through a live form over that database and View through a live form that
+/// shares its responses.
#[tracing::instrument(err, skip(pool, source_ids))]
pub async fn get_database_row_access(
pool: &PgPool,
@@ -46,6 +47,20 @@ pub async fn get_database_row_access(
AND f.trashed_at IS NULL
AND ea.source_id = ANY($2)
AND ea.access_level IN ('edit', 'owner')
+
+ UNION ALL
+
+ SELECT 'view'
+ FROM database_rows r
+ JOIN database_tables t ON t.id = r.table_id
+ JOIN forms f ON f.database_id = t.database_id
+ JOIN database_entities d ON d.database_id = f.database_id
+ JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'
+ WHERE r.id = $1
+ AND f.trashed_at IS NULL
+ AND f.responses_visible
+ AND ea.source_id = ANY($2)
+ AND ea.access_level = 'view'
"#,
row_id,
&source_ids.0,
@@ -57,7 +72,8 @@ pub async fn get_database_row_access(
}
/// Highest database grant for each requested row, using the caller's shared
-/// sources, including Edit through a live form over the row's database.
+/// sources, including Edit through a live form over the row's database and
+/// View through a live form that shares its responses.
#[tracing::instrument(err, skip_all, fields(row_count = row_ids.len()))]
pub async fn get_database_rows_access(
pool: &PgPool,
@@ -91,6 +107,20 @@ pub async fn get_database_rows_access(
AND f.trashed_at IS NULL
AND ea.source_id = ANY($2)
AND ea.access_level IN ('edit', 'owner')
+
+ UNION ALL
+
+ SELECT r.id, 'view'::"AccessLevel"
+ FROM database_rows r
+ JOIN database_tables t ON t.id = r.table_id
+ JOIN forms f ON f.database_id = t.database_id
+ JOIN database_entities d ON d.database_id = f.database_id
+ JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'
+ WHERE r.id = ANY($1)
+ AND f.trashed_at IS NULL
+ AND f.responses_visible
+ AND ea.source_id = ANY($2)
+ AND ea.access_level = 'view'
"#,
row_ids,
&source_ids.0,
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access/test.rs
index 4fd7ec8a7e..54f6de2c04 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/database_row_access/test.rs
@@ -144,7 +144,7 @@ async fn a_row_belongs_to_the_database_of_its_table(pool: PgPool) {
}
/// A form over the table holding `row_id`, granting `MEMBER` `level` on it.
-async fn insert_form_over_row(pool: &PgPool, row_id: Uuid, level: &str, trashed: bool) {
+async fn insert_form_over_row(pool: &PgPool, row_id: Uuid, level: &str, trashed: bool) -> Uuid {
let form_id = Uuid::now_v7();
sqlx::query!(
r#"
@@ -174,6 +174,7 @@ async fn insert_form_over_row(pool: &PgPool, row_id: Uuid, level: &str, trashed:
.execute(pool)
.await
.unwrap();
+ form_id
}
#[sqlx::test(
@@ -248,3 +249,46 @@ async fn a_direct_database_grant_above_edit_wins_over_a_form_on_rows(pool: PgPoo
HashMap::from([(row_id, AccessLevel::Owner)])
);
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn viewing_a_form_that_shares_responses_views_the_rows_of_its_database(pool: PgPool) {
+ let (_, shared) = insert_row(&pool).await;
+ let (_, hidden) = insert_row(&pool).await;
+ let form_id = insert_form_over_row(&pool, shared, "view", false).await;
+ insert_form_over_row(&pool, hidden, "view", false).await;
+ sqlx::query!(
+ r#"UPDATE forms SET responses_visible = TRUE WHERE id = $1"#,
+ form_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let member = get_user_source_ids(
+ &pool,
+ Some(&MacroUserIdStr::try_from(MEMBER.to_string()).unwrap()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ get_database_row_access(&pool, &shared, &member)
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ assert_eq!(
+ get_database_row_access(&pool, &hidden, &member)
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(
+ get_database_rows_access(&pool, &[shared, hidden], &member)
+ .await
+ .unwrap(),
+ HashMap::from([(shared, AccessLevel::View)])
+ );
+}
diff --git a/crates/forms/AGENTS.md b/crates/forms/AGENTS.md
index fab0a013d3..a4f0e4d52c 100644
--- a/crates/forms/AGENTS.md
+++ b/crates/forms/AGENTS.md
@@ -48,6 +48,11 @@ service.
## Gotchas
+- An anonymous form (`forms.anonymous`) keeps who responded in
+ `form_submission_receipts` (no response, row or time) and writes ledger
+ entries with no respondent, a random v4 id and the day only. Nothing may
+ join the two: no span, log, event or row author names a voter next to a
+ response.
- A form is filed in a folder on its own (`forms.project_id`, `MoveEntity`,
owner only); its database stays where it is. The folder's inherited grants
on the form reach the database through form access, like any form grant.
diff --git a/crates/forms/Cargo.toml b/crates/forms/Cargo.toml
index 2fb631f2f0..78ff25c632 100644
--- a/crates/forms/Cargo.toml
+++ b/crates/forms/Cargo.toml
@@ -81,3 +81,4 @@ models_properties = { path = "../models_properties" }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync"] }
tower = { workspace = true }
+tracing-subscriber = { workspace = true }
diff --git a/crates/forms/src/domain/authoring/contracts.rs b/crates/forms/src/domain/authoring/contracts.rs
index 464434a672..2ffd73f1f0 100644
--- a/crates/forms/src/domain/authoring/contracts.rs
+++ b/crates/forms/src/domain/authoring/contracts.rs
@@ -49,7 +49,7 @@ pub struct List {
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum GrantAccess {
- /// May respond; no database read grant.
+ /// May respond. When the form shares responses, also grants database View.
View,
/// May edit the form and its entire backing database.
Edit,
@@ -88,6 +88,13 @@ pub struct AccessDraft {
pub closes_at: Option<DateTime<Utc>>,
/// Whether respondents can see aggregate choice tallies.
pub tally_visible: bool,
+ /// Whether people with View may read individual response rows.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub responses_visible: Option<bool>,
+ /// Whether nobody, the owner included, can see who gave which response;
+ /// refused once anyone has responded.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub anonymous: Option<bool>,
/// Direct channel changes only; this does not post messages or send invitations.
#[serde(default)]
pub channel_grants: Vec<GrantChange>,
diff --git a/crates/forms/src/domain/authoring/workflow/access.rs b/crates/forms/src/domain/authoring/workflow/access.rs
index e2dc72c800..ada8d801a2 100644
--- a/crates/forms/src/domain/authoring/workflow/access.rs
+++ b/crates/forms/src/domain/authoring/workflow/access.rs
@@ -36,6 +36,8 @@ impl<
status: Some(intent.draft.status),
closes_at: Some(intent.draft.closes_at),
tally_visible: Some(intent.draft.tally_visible),
+ responses_visible: intent.draft.responses_visible,
+ anonymous: intent.draft.anonymous,
..Default::default()
},
)
diff --git a/crates/forms/src/domain/authoring/workflow/create.rs b/crates/forms/src/domain/authoring/workflow/create.rs
index acec7c04fb..a55f9b529f 100644
--- a/crates/forms/src/domain/authoring/workflow/create.rs
+++ b/crates/forms/src/domain/authoring/workflow/create.rs
@@ -24,9 +24,13 @@ impl<
));
}
let source = match intent.source {
- FormSource::New { is_hidden_in_drive } => {
- CreateSource::NewDatabase { is_hidden_in_drive }
- }
+ FormSource::New {
+ is_hidden_in_drive,
+ anonymous,
+ } => CreateSource::NewDatabase {
+ is_hidden_in_drive,
+ anonymous,
+ },
FormSource::Table {
database_id,
table_id,
diff --git a/crates/forms/src/domain/entity_mutation.rs b/crates/forms/src/domain/entity_mutation.rs
index 03c09dc230..38b961afdc 100644
--- a/crates/forms/src/domain/entity_mutation.rs
+++ b/crates/forms/src/domain/entity_mutation.rs
@@ -27,6 +27,7 @@ impl From<FormError> for EntityMutationErrorCode {
error @ (FormError::Conflict
| FormError::TableAlreadyHasForm
| FormError::AlreadyResponded
+ | FormError::AnonymousResponseFinal
| FormError::Closed
| FormError::TableGone) => Self::conflict(rootcause::report!(error)),
error @ (FormError::SignInRequired
diff --git a/crates/forms/src/domain/events.rs b/crates/forms/src/domain/events.rs
index 1bd2baddca..4119674899 100644
--- a/crates/forms/src/domain/events.rs
+++ b/crates/forms/src/domain/events.rs
@@ -95,7 +95,8 @@ pub struct FormResponseSubmittedMetadata {
pub form_id: FormId,
/// The ledger entry.
pub response_id: FormResponseId,
- /// The signed-in respondent; `None` for an anonymous one.
+ /// The signed-in respondent; `None` for an anonymous visitor or when
+ /// the form hides respondents. The ledger still records them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub respondent: Option<MacroUserIdStr<'static>>,
/// The row holding the answers.
diff --git a/crates/forms/src/domain/models.rs b/crates/forms/src/domain/models.rs
index 6d041ef978..53e7c98724 100644
--- a/crates/forms/src/domain/models.rs
+++ b/crates/forms/src/domain/models.rs
@@ -103,6 +103,9 @@ pub enum FormUpdate {
/// The change forbade a widget one of the form's questions uses when it
/// committed; nothing was written.
WidgetInUse,
+ /// The change would make the form anonymous, or stop it being, after
+ /// someone responded; nothing was written.
+ AnonymityLocked,
}
/// A form's ledger counts.
@@ -133,6 +136,11 @@ pub enum SharingRefusal {
/// or names no level.
#[error("a channel grant is invalid")]
InvalidChannelGrant,
+ /// Someone has responded, so whether the form is anonymous is fixed:
+ /// earlier responses name their respondents, or were given on the
+ /// promise that nobody would see who gave them.
+ #[error("whether a form is anonymous can't change once anyone has responded")]
+ AnonymityLocked,
}
/// Errors of the forms domain.
@@ -165,6 +173,10 @@ pub enum FormError {
/// The respondent has no saved response.
#[error("you have no response to this form")]
NoResponse,
+ /// Nothing links a response to an anonymous form to its respondent, so
+ /// it can't be found to change.
+ #[error("a response to an anonymous form can't be changed")]
+ AnonymousResponseFinal,
/// An answer names a question the form does not ask.
#[error("the form has no question {question}")]
UnknownQuestion {
diff --git a/crates/forms/src/domain/ports.rs b/crates/forms/src/domain/ports.rs
index c6fb9dfafe..0e43dca965 100644
--- a/crates/forms/src/domain/ports.rs
+++ b/crates/forms/src/domain/ports.rs
@@ -24,6 +24,8 @@ pub enum CreateSource {
NewDatabase {
/// Keep the form, and the database made for it, out of Drive.
is_hidden_in_drive: bool,
+ /// Make the form anonymous, with no Respondent column.
+ anonymous: bool,
},
/// An existing table of the database the receipt names. Attaching a
/// form to an existing table takes the database's Owner: the form's
@@ -157,7 +159,8 @@ pub trait FormsRepo: Send + Sync + 'static {
/// what it leaves out stays. With `forbidden_widget`, the change goes
/// through only if no question of the form asks one of its columns with
/// its widget when it commits; concurrent writes of the form's facts and
- /// layout serialize, so the check holds.
+ /// layout serialize, so the check holds. A change of whether the form is
+ /// anonymous goes through only while it has no accepted response.
fn update_form(
&self,
id: FormId,
@@ -236,6 +239,27 @@ pub trait FormsRepo: Send + Sync + 'static {
at: DateTime<Utc>,
) -> impl Future<Output = Result<RecordedResponse, Self::Error>> + Send;
+ /// Record a response to an anonymous form whose row is written, in one
+ /// transaction: a signed-in voter's receipt, which names no response,
+ /// and a ledger entry that names nobody, with a random id and stamped
+ /// `day`. A voter who already holds a receipt answers
+ /// [`RecordedResponse::AlreadySubmitted`] and nothing is written.
+ fn record_anonymous_submission(
+ &self,
+ form: FormId,
+ voter: Option<&MacroUserIdStr<'_>>,
+ row: RowId,
+ day: DateTime<Utc>,
+ ) -> impl Future<Output = Result<RecordedResponse, Self::Error>> + Send;
+
+ /// Whether a signed-in person holds a receipt for responding to an
+ /// anonymous form.
+ fn holds_receipt(
+ &self,
+ form: FormId,
+ voter: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+
/// Point an entry at a new row, for a response whose row was deleted
/// and written again.
fn repoint_response(
@@ -257,6 +281,13 @@ pub trait FormsRepo: Send + Sync + 'static {
&self,
form: FormId,
) -> impl Future<Output = Result<ResponseCounts, Self::Error>> + Send;
+
+ /// Who submitted each row: the signed-in respondents of accepted
+ /// responses that still point at a row, in submission order.
+ fn respondents_by_row(
+ &self,
+ form: FormId,
+ ) -> impl Future<Output = Result<Vec<(RowId, MacroUserIdStr<'static>)>, Self::Error>> + Send;
}
/// The forms domain service.
diff --git a/crates/forms/src/domain/service/authoring.rs b/crates/forms/src/domain/service/authoring.rs
index db503ffab5..d816cf5d2f 100644
--- a/crates/forms/src/domain/service/authoring.rs
+++ b/crates/forms/src/domain/service/authoring.rs
@@ -22,25 +22,27 @@ where
&self,
source: &CreateSource,
) -> Result<(Vec<Column>, Vec<models_databases::ColumnId>), FormError> {
- let new_columns = || {
- vec![
- Column {
- id: models_databases::ColumnId::new(),
- name: create::SUBMITTED_COLUMN.into(),
- kind: managed::submitted_kind(),
- options: vec![],
- },
- Column {
+ // An anonymous form's new table gets no Respondent column.
+ let new_columns = |anonymous: bool| {
+ let mut columns = vec![Column {
+ id: models_databases::ColumnId::new(),
+ name: create::SUBMITTED_COLUMN.into(),
+ kind: managed::submitted_kind(),
+ options: vec![],
+ }];
+ if !anonymous {
+ columns.push(Column {
id: models_databases::ColumnId::new(),
name: create::RESPONDENT_COLUMN.into(),
kind: managed::respondent_kind(),
options: vec![],
- },
- ]
+ });
+ }
+ columns
};
match source {
- CreateSource::NewDatabase { .. } => {
- let columns = new_columns();
+ CreateSource::NewDatabase { anonymous, .. } => {
+ let columns = new_columns(*anonymous);
let managed = columns.iter().map(|c| c.id).collect();
Ok((columns, managed))
}
@@ -79,7 +81,7 @@ where
})
.collect();
let mut managed_ids = vec![];
- for column in new_columns() {
+ for column in new_columns(false) {
match create::managed_column(table, &column.name, column.kind) {
create::ManagedColumn::Existing(id) => managed_ids.push(id),
create::ManagedColumn::New { id, name } => {
diff --git a/crates/forms/src/domain/service/create.rs b/crates/forms/src/domain/service/create.rs
index 3b931c6acd..6c71aedd46 100644
--- a/crates/forms/src/domain/service/create.rs
+++ b/crates/forms/src/domain/service/create.rs
@@ -38,9 +38,13 @@ pub(super) const RESPONDENT_COLUMN: &str = "Respondent";
/// Where a new form's table came from.
#[derive(Clone, Copy)]
enum Provenance {
- /// A database made for the form, which goes by its name and may stay
- /// out of Drive with it.
- OwnDatabase { is_hidden_in_drive: bool },
+ /// A database made for the form, which goes by its name, may stay out
+ /// of Drive with it, and has no Respondent column when the form starts
+ /// anonymous.
+ OwnDatabase {
+ is_hidden_in_drive: bool,
+ anonymous: bool,
+ },
/// A table of a database the creator already had.
ExistingTable,
}
@@ -159,8 +163,15 @@ where
};
let name = validated_name(&command.name)?;
match command.source {
- CreateSource::NewDatabase { is_hidden_in_drive } => {
- self.create_over_new_database(creator, name, is_hidden_in_drive, id, status, policy)
+ CreateSource::NewDatabase {
+ is_hidden_in_drive,
+ anonymous,
+ } => {
+ let provenance = Provenance::OwnDatabase {
+ is_hidden_in_drive,
+ anonymous,
+ };
+ self.create_over_new_database(creator, name, provenance, id, status, policy)
.await
}
CreateSource::Table { receipt, table_id } => {
@@ -177,7 +188,7 @@ where
&self,
creator: Viewer,
name: String,
- is_hidden_in_drive: bool,
+ provenance: Provenance,
id: FormId,
status: FormStatus,
policy: CreationPolicy,
@@ -196,7 +207,7 @@ where
&creator,
database.name,
database.id,
- is_hidden_in_drive,
+ provenance,
id,
status,
policy,
@@ -219,14 +230,14 @@ where
#[expect(
clippy::too_many_arguments,
- reason = "Attaching carries the new form's identity, status and Drive visibility"
+ reason = "Attaching carries the new form's identity, status and provenance"
)]
async fn attach_to_new_database(
&self,
creator: &Viewer,
name: String,
database_id: DatabaseId,
- is_hidden_in_drive: bool,
+ provenance: Provenance,
id: FormId,
status: FormStatus,
policy: CreationPolicy,
@@ -263,9 +274,16 @@ where
id: ColumnId::new(),
name: SUBMITTED_COLUMN.to_string(),
};
- let respondent = ManagedColumn::New {
- id: ColumnId::new(),
- name: RESPONDENT_COLUMN.to_string(),
+ let respondent = match provenance {
+ Provenance::OwnDatabase {
+ anonymous: true, ..
+ } => None,
+ Provenance::OwnDatabase { .. } | Provenance::ExistingTable => {
+ Some(ManagedColumn::New {
+ id: ColumnId::new(),
+ name: RESPONDENT_COLUMN.to_string(),
+ })
+ }
};
let mut ops = vec![DatabaseOp::Table {
table: table.table.id,
@@ -277,7 +295,9 @@ where
ops.extend(
[
create_op(&table, &submitted, submitted_kind()),
- create_op(&table, &respondent, respondent_kind()),
+ respondent
+ .as_ref()
+ .and_then(|respondent| create_op(&table, respondent, respondent_kind())),
]
.into_iter()
.flatten(),
@@ -315,10 +335,10 @@ where
self.store_new_form(
creator,
name,
- (submitted.id(), respondent.id()),
+ (submitted.id(), respondent.as_ref().map(ManagedColumn::id)),
layout,
&table,
- Provenance::OwnDatabase { is_hidden_in_drive },
+ provenance,
id,
status,
)
@@ -421,7 +441,7 @@ where
self.store_new_form(
&creator,
name,
- (submitted.id(), respondent.id()),
+ (submitted.id(), Some(respondent.id())),
layout,
&table,
Provenance::ExistingTable,
@@ -442,7 +462,7 @@ where
&self,
creator: &Viewer,
name: String,
- (submitted, respondent): (ColumnId, ColumnId),
+ (submitted, respondent): (ColumnId, Option<ColumnId>),
layout: FormLayout,
table: &TableDetail,
provenance: Provenance,
@@ -459,7 +479,7 @@ where
database_id,
table_id: table.table.id,
submitted_column_id: Some(submitted),
- respondent_column_id: Some(respondent),
+ respondent_column_id: respondent,
audience: Audience::Members,
tally_visible: false,
status,
@@ -472,7 +492,16 @@ where
is_hidden_in_drive: matches!(
provenance,
Provenance::OwnDatabase {
- is_hidden_in_drive: true
+ is_hidden_in_drive: true,
+ ..
+ }
+ ),
+ responses_visible: false,
+ anonymous: matches!(
+ provenance,
+ Provenance::OwnDatabase {
+ anonymous: true,
+ ..
}
),
};
diff --git a/crates/forms/src/domain/service/lifecycle.rs b/crates/forms/src/domain/service/lifecycle.rs
index 52aaa8fca6..d4373fa542 100644
--- a/crates/forms/src/domain/service/lifecycle.rs
+++ b/crates/forms/src/domain/service/lifecycle.rs
@@ -26,7 +26,7 @@ use crate::domain::events::{
};
use crate::domain::models::{
Audience, ForbiddenWidget, Form, FormAccess, FormError, FormId, FormUpdate, ListedForm,
- UpdateForm, Widget,
+ SharingRefusal, UpdateForm, Widget,
};
use crate::domain::ports::{
Clock, FormAccessDirectory, FormEventPublisher, FormImageFiles, FormsRepo,
@@ -129,6 +129,7 @@ where
}
FormUpdate::FormGone => Err(FormError::NotFound),
FormUpdate::WidgetInUse => Err(FormError::FileUploadNeedsSignIn),
+ FormUpdate::AnonymityLocked => Err(SharingRefusal::AnonymityLocked.into()),
}
}
diff --git a/crates/forms/src/domain/service/responses.rs b/crates/forms/src/domain/service/responses.rs
index 758b0b1576..aeab035ab0 100644
--- a/crates/forms/src/domain/service/responses.rs
+++ b/crates/forms/src/domain/service/responses.rs
@@ -1,5 +1,6 @@
//! What editors and poll voters read of the responses: the ledger's counts
-//! and, for choice questions, how the table's rows answer them.
+//! and, for choice questions, how the table's rows answer them and, where
+//! the responses are shared and name their respondents, who chose what.
use crate::domain::drafts::{FormDraftRepository, FormDraftStore};
@@ -9,6 +10,7 @@ use databases::domain::models::DatabaseError;
use databases::domain::ports::{DatabaseMetadataReads, DatabaseRowReads, DatabasesService};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
use macro_event_broker::MacroEventBroker;
+use macro_user_id::user_id::MacroUserIdStr;
use models_databases::{CellValue, ColumnKind, OptionRef, RowId};
use super::layout::question_columns;
@@ -24,11 +26,13 @@ use crate::domain::ports::{
Clock, FormAccessDirectory, FormEventPublisher, FormImageFiles, FormsRepo,
};
-/// One column's tally from its cells.
+/// One column's tally from its cells, naming each bucket's voters when
+/// `voters` (who submitted each row, in submission order) is given.
fn tally_of(
kind: ColumnKind,
options: &[QuestionOption],
cells: &HashMap<RowId, CellValue>,
+ voters: Option<&[(RowId, MacroUserIdStr<'static>)]>,
) -> (u64, Vec<TallyBucket>) {
// A count of in-memory cells is a usize, at most 64 bits on every
// target the service builds for, so it always fits a u64.
@@ -40,21 +44,35 @@ fn tally_of(
CellValue::Clear => false,
_ => true,
});
+ let named = |holds: &dyn Fn(&CellValue) -> bool| -> Option<Vec<String>> {
+ voters.map(|voters| {
+ voters
+ .iter()
+ .filter(|(row, _)| cells.get(row).is_some_and(holds))
+ .map(|(_, voter)| voter.to_string())
+ .collect()
+ })
+ };
+ let bucket = |value: TallyValue, holds: &dyn Fn(&CellValue) -> bool| TallyBucket {
+ value,
+ count: count(holds),
+ voters: named(holds),
+ };
let buckets = match kind {
ColumnKind::Boolean => [true, false]
.into_iter()
- .map(|checked| TallyBucket {
- value: TallyValue::Checkbox { checked },
- count: count(&|value| *value == CellValue::Boolean(checked)),
+ .map(|checked| {
+ bucket(TallyValue::Checkbox { checked }, &|value| {
+ *value == CellValue::Boolean(checked)
+ })
})
.collect(),
_ => options
.iter()
- .map(|option| TallyBucket {
- value: TallyValue::Option { option: option.id },
- count: count(&|value| {
+ .map(|option| {
+ bucket(TallyValue::Option { option: option.id }, &|value| {
matches!(value, CellValue::Options(held) if held.contains(&OptionRef::Id(option.id)))
- }),
+ })
})
.collect(),
};
@@ -145,9 +163,22 @@ where
receipt: &EntityAccessReceipt<ViewAccessLevel>,
) -> Result<FormTally, FormError> {
let form = self.live_form(receipt_form_id(receipt)?).await?;
- if receipt_access(receipt) < FormAccess::Edit && !form.tally_visible {
+ let editor = receipt_access(receipt) >= FormAccess::Edit;
+ if !editor && !form.tally_visible {
return Err(FormError::TallyHidden);
}
+ // Voters show to whoever may read the responses, and never on a form
+ // that hides its respondents.
+ let voters = if !form.anonymous && (editor || form.responses_visible) {
+ Some(
+ self.repository
+ .respondents_by_row(form.id)
+ .await
+ .map_err(repository_error)?,
+ )
+ } else {
+ None
+ };
let table = self.live_table_of(&form).await?;
let columns = question_columns(&table);
let layout = self.refresh_layout(&form, Some(&table)).await?.layout;
@@ -177,7 +208,8 @@ where
Err(DatabaseError::NotFound) => continue,
Err(other) => return Err(database_error(other)),
};
- let (responses, buckets) = tally_of(column.kind, &column.options, &cells);
+ let (responses, buckets) =
+ tally_of(column.kind, &column.options, &cells, voters.as_deref());
questions.push(QuestionTally {
question: question.id,
responses,
diff --git a/crates/forms/src/domain/service/submit.rs b/crates/forms/src/domain/service/submit.rs
index aa605001f8..006a441261 100644
--- a/crates/forms/src/domain/service/submit.rs
+++ b/crates/forms/src/domain/service/submit.rs
@@ -6,7 +6,7 @@ use crate::domain::drafts::{FormDraftRepository, FormDraftStore};
use std::collections::HashMap;
-use chrono::{DateTime, Utc};
+use chrono::{DateTime, DurationRound, TimeDelta, Utc};
use databases::domain::models::{DatabaseError, OpBatch, TableDetail, Viewer};
use databases::domain::ports::{DatabaseMetadataReads, DatabaseRowReads, DatabasesService};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
@@ -34,6 +34,16 @@ use crate::domain::ports::{
Clock, FormAccessDirectory, FormEventPublisher, FormImageFiles, FormsRepo,
};
+/// Who a response's row is written as: the respondent, or the form's owner
+/// for an anonymous visitor or on an anonymous form, so the row's author and
+/// its history name nobody.
+fn row_author(form: &Form, respondent: &Respondent) -> Result<MacroUserIdStr<'static>, FormError> {
+ match respondent {
+ Respondent::Member(user) if !form.anonymous => Ok(user.clone()),
+ Respondent::Member(_) | Respondent::Anonymous => owner_of(form),
+ }
+}
+
/// The cells of a new row: every answer, then the managed columns the table
/// still has.
fn insert_cells(
@@ -58,10 +68,12 @@ fn insert_cells(
value: CellValue::Date(submitted_at),
});
}
- if let (Some(column), Respondent::Member(user)) = (
- writable(columns, form.respondent_column_id, respondent_kind()),
- respondent,
- ) {
+ if !form.anonymous
+ && let (Some(column), Respondent::Member(user)) = (
+ writable(columns, form.respondent_column_id, respondent_kind()),
+ respondent,
+ )
+ {
cells.push(CellWrite {
column,
value: CellValue::Entities(vec![EntityRef {
@@ -227,12 +239,19 @@ where
let now = self.now();
let (form, respondent, table, layout) = self.open_for(receipt, now).await?;
if let Respondent::Member(user) = &respondent {
- let existing = self
- .repository
- .response_of(form.id, user)
- .await
- .map_err(repository_error)?;
- if existing.is_some_and(|entry| entry.status == ResponseStatus::Submitted) {
+ let responded = if form.anonymous {
+ self.repository
+ .holds_receipt(form.id, user)
+ .await
+ .map_err(repository_error)?
+ } else {
+ self.repository
+ .response_of(form.id, user)
+ .await
+ .map_err(repository_error)?
+ .is_some_and(|entry| entry.status == ResponseStatus::Submitted)
+ };
+ if responded {
return Err(FormError::AlreadyResponded);
}
}
@@ -242,8 +261,11 @@ where
Evaluation::Passed(answered) => answered,
Evaluation::Stopped { section, message } => {
// Only a signed-in respondent has an entry to stop; an
- // anonymous one leaves no trace.
- if let Respondent::Member(user) = &respondent {
+ // anonymous one, or anyone on an anonymous form, leaves no
+ // trace.
+ if let Respondent::Member(user) = &respondent
+ && !form.anonymous
+ {
self.repository
.record_stop(form.id, user, section, now)
.await
@@ -253,30 +275,45 @@ where
return Ok(SubmissionOutcome::Stopped { section, message });
}
};
+ // An anonymous form's responses carry only their day, so their
+ // times can't be matched against who was active when.
+ let stamped = if form.anonymous {
+ now.duration_trunc(TimeDelta::days(1))
+ .map_err(|_| FormError::DatabaseContract("a submission time has no day"))?
+ } else {
+ now
+ };
let insert = vec![DatabaseOp::Rows {
table: form.table_id,
change: RowsChange::Insert {
- rows: vec![insert_cells(&form, &columns, &answered, &respondent, now)],
+ rows: vec![insert_cells(
+ &form,
+ &columns,
+ &answered,
+ &respondent,
+ stamped,
+ )],
},
}];
- // The row first, under the form's receipt, as the respondent or, for
- // an anonymous one, the form's owner; then the ledger, in its own
- // transaction.
- let viewer = match &respondent {
- Respondent::Member(user) => user.clone(),
- Respondent::Anonymous => owner_of(&form)?,
- };
+ // The row first, under the form's receipt, then the ledger, in its
+ // own transaction.
+ let viewer = row_author(&form, &respondent)?;
let results = self.write(&form, viewer, insert, &answered).await?;
let row = inserted_row(&results)?;
let member = match &respondent {
Respondent::Member(user) => Some(user),
Respondent::Anonymous => None,
};
- let recorded = self
- .repository
- .record_submission(form.id, member, row, now)
- .await
- .map_err(|error| {
+ let recorded = if form.anonymous {
+ self.repository
+ .record_anonymous_submission(form.id, member, row, stamped)
+ .await
+ } else {
+ self.repository
+ .record_submission(form.id, member, row, now)
+ .await
+ }
+ .map_err(|error| {
tracing::error!(error = ?error, form_id = %form.id, row_id = %row, "a response's row was written but its ledger entry was not");
repository_error(error)
})?;
@@ -294,12 +331,14 @@ where
FormResponseSubmittedMetadata {
form_id: form.id,
response_id: response,
+ // An anonymous form's event names nobody; activity would
+ // say who responded.
respondent: match respondent {
- Respondent::Member(user) => Some(user),
- Respondent::Anonymous => None,
+ Respondent::Member(user) if !form.anonymous => Some(user),
+ Respondent::Member(_) | Respondent::Anonymous => None,
},
row_id: Some(row),
- submitted_at: now,
+ submitted_at: stamped,
},
));
Ok(SubmissionOutcome::Submitted {
@@ -319,6 +358,9 @@ where
return Err(FormError::SignInRequired);
};
let (form, _, table, layout) = self.open_for(receipt, now).await?;
+ if form.anonymous {
+ return Err(FormError::AnonymousResponseFinal);
+ }
let entry = self
.repository
.response_of(form.id, &user)
@@ -394,7 +436,7 @@ where
.collect();
self.write(
form,
- user.clone(),
+ row_author(form, &Respondent::Member(user.clone()))?,
vec![DatabaseOp::Rows {
table: form.table_id,
change: RowsChange::Update {
@@ -432,7 +474,8 @@ where
)],
},
}];
- let results = self.write(form, user.clone(), insert, answered).await?;
+ let viewer = row_author(form, &Respondent::Member(user.clone()))?;
+ let results = self.write(form, viewer, insert, answered).await?;
let row = inserted_row(&results)?;
self.repository
.repoint_response(entry.id, row, now)
@@ -452,14 +495,27 @@ where
return Err(FormError::SignInRequired);
};
let form = self.live_form(receipt_form_id(receipt)?).await?;
- let response = self
- .repository
- .response_of(form.id, &user)
- .await
- .map_err(repository_error)?
- .ok_or(FormError::NoResponse)?;
+ if form.anonymous {
+ return if self
+ .repository
+ .holds_receipt(form.id, &user)
+ .await
+ .map_err(repository_error)?
+ {
+ Ok(MyResponse::Anonymous)
+ } else {
+ Err(FormError::NoResponse)
+ };
+ }
+ let response = Box::new(
+ self.repository
+ .response_of(form.id, &user)
+ .await
+ .map_err(repository_error)?
+ .ok_or(FormError::NoResponse)?,
+ );
let Some(row) = response.row else {
- return Ok(MyResponse {
+ return Ok(MyResponse::Saved {
response,
answers: vec![],
booking: None,
@@ -478,7 +534,7 @@ where
{
Ok(cells) => cells,
Err(DatabaseError::NotFound) => {
- return Ok(MyResponse {
+ return Ok(MyResponse::Saved {
response,
answers: vec![],
booking: None,
@@ -489,7 +545,7 @@ where
let table = self.table_of(&form).await?;
let layout = self.refresh_layout(&form, table.as_ref()).await?.layout;
let Some(cells) = cells.remove(&row) else {
- return Ok(MyResponse {
+ return Ok(MyResponse::Saved {
response,
answers: vec![],
booking: None,
@@ -501,7 +557,7 @@ where
Some(table) => still_passes(&layout, &question_columns(&table), &answers),
None => false,
};
- Ok(MyResponse {
+ Ok(MyResponse::Saved {
response,
answers,
booking: passes.then(|| unlocked_booking(&layout)).flatten(),
diff --git a/crates/forms/src/domain/service/test.rs b/crates/forms/src/domain/service/test.rs
index 41217e8b60..4efe2f9a58 100644
--- a/crates/forms/src/domain/service/test.rs
+++ b/crates/forms/src/domain/service/test.rs
@@ -24,6 +24,7 @@ use crate::domain::models::{
FormSectionId, FormStatus, QuestionLayout, StoredForm, Widget,
};
+mod anonymous;
mod authoring_workflow;
mod booking;
mod catalog;
@@ -300,6 +301,8 @@ fn seed_rsvp(world: &Shared, audience: Audience) {
updated_at: now,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
trashed_at: None,
name_follows_database: false,
diff --git a/crates/forms/src/domain/service/test/anonymous.rs b/crates/forms/src/domain/service/test/anonymous.rs
new file mode 100644
index 0000000000..4a054f9421
--- /dev/null
+++ b/crates/forms/src/domain/service/test/anonymous.rs
@@ -0,0 +1,316 @@
+//! Anonymous forms: who responded is kept apart from what they answered, at
+//! every level of access, and still nobody responds twice.
+
+use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
+use models_databases::{CellValue, CellWrite, DatabaseOp, OptionRef, RowsChange};
+
+use super::*;
+use crate::domain::models::{
+ Answer, FormError, MyResponse, SharingRefusal, Submission, SubmissionOutcome, UpdateForm,
+};
+use crate::domain::ports::{CreateFormCommand, CreateSource, FormsService};
+
+fn employee_answers() -> Vec<Answer> {
+ vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(EMPLOYEE)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ ]
+}
+
+async fn submit_as(
+ forms: &Service,
+ user: &'static str,
+ answers: Vec<Answer>,
+) -> Result<SubmissionOutcome, FormError> {
+ forms
+ .submit_response(
+ form_receipt::<ViewAccessLevel>(RSVP_FORM, user, AccessLevel::View),
+ Submission { answers },
+ )
+ .await
+}
+
+fn seed_anonymous(world: &Shared) {
+ seed_rsvp(world, Audience::Members);
+ world.lock().unwrap().forms[0].form.anonymous = true;
+}
+
+#[tokio::test]
+async fn an_anonymous_response_leaves_a_receipt_and_a_dated_ledger_entry_naming_nobody() {
+ let world = world();
+ seed_anonymous(&world);
+ let outcome = submit_as(&service(&world), VIEWER, employee_answers())
+ .await
+ .unwrap();
+ let SubmissionOutcome::Submitted { response, row, .. } = outcome else {
+ panic!("saved, not {outcome:?}");
+ };
+ let day = Utc.with_ymd_and_hms(2026, 9, 1, 0, 0, 0).unwrap();
+ let world = world.lock().unwrap();
+ assert_eq!(world.receipts, vec![(RSVP_FORM, VIEWER.to_string())]);
+ assert_eq!(world.ledger.len(), 1);
+ assert_eq!(world.ledger[0].respondent, None);
+ assert_eq!(world.ledger[0].response.id, response);
+ assert_eq!(world.ledger[0].response.row, Some(row));
+ assert_eq!(world.ledger[0].response.submitted_at, day);
+ assert_eq!(world.ledger[0].response.updated_at, day);
+ // Written as the owner, with no Respondent cell and only the day.
+ assert_eq!(
+ world.batches,
+ vec![RecordedBatch {
+ database: RSVP_DATABASE,
+ internal: true,
+ viewer: OWNER.into(),
+ ops: vec![DatabaseOp::Rows {
+ table: RSVP_TABLE,
+ change: RowsChange::Insert {
+ rows: vec![vec![
+ CellWrite {
+ column: TEAM,
+ value: CellValue::Options(vec![OptionRef::Id(EMPLOYEE)]),
+ },
+ CellWrite {
+ column: START_DATE,
+ value: CellValue::Date(
+ Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()
+ ),
+ },
+ CellWrite {
+ column: SUBMITTED,
+ value: CellValue::Date(day),
+ },
+ ]],
+ },
+ }],
+ }]
+ );
+}
+
+#[tokio::test]
+async fn an_anonymous_response_event_names_nobody_and_carries_only_the_day() {
+ let world = world();
+ seed_anonymous(&world);
+ submit_as(&service(&world), VIEWER, employee_answers())
+ .await
+ .unwrap();
+ let world = world.lock().unwrap();
+ assert_eq!(world.event_types(), vec!["form.response_submitted"]);
+ let metadata = &world.events[0]["metadata"];
+ assert!(metadata.get("respondent").is_none());
+ assert_eq!(metadata["submitted_at"], "2026-09-01T00:00:00Z");
+ assert!(!world.events[0].to_string().contains(VIEWER));
+}
+
+#[tokio::test]
+async fn a_second_anonymous_response_is_refused_and_writes_nothing() {
+ let world = world();
+ seed_anonymous(&world);
+ let forms = service(&world);
+ submit_as(&forms, VIEWER, employee_answers()).await.unwrap();
+ let again = submit_as(&forms, VIEWER, employee_answers()).await;
+ assert!(matches!(again, Err(FormError::AlreadyResponded)));
+ let world = world.lock().unwrap();
+ assert_eq!(world.batches.len(), 1);
+ assert_eq!(world.ledger.len(), 1);
+ assert_eq!(world.receipts.len(), 1);
+}
+
+#[tokio::test]
+async fn an_anonymous_response_racing_another_by_the_same_person_is_refused_by_the_receipt() {
+ let world = world();
+ seed_anonymous(&world);
+ world.lock().unwrap().competing_submission = Some((RSVP_FORM, VIEWER.to_string()));
+ let raced = submit_as(&service(&world), VIEWER, employee_answers()).await;
+ assert!(matches!(raced, Err(FormError::AlreadyResponded)));
+ let world = world.lock().unwrap();
+ assert_eq!(world.receipts, vec![(RSVP_FORM, VIEWER.to_string())]);
+ assert_eq!(world.ledger.len(), 1);
+}
+
+#[tokio::test]
+async fn a_respondent_reads_back_only_that_they_responded_to_an_anonymous_form() {
+ let world = world();
+ seed_anonymous(&world);
+ let forms = service(&world);
+ submit_as(&forms, VIEWER, employee_answers()).await.unwrap();
+ let mine = forms
+ .my_response(form_receipt::<ViewAccessLevel>(
+ RSVP_FORM,
+ VIEWER,
+ AccessLevel::View,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(mine, MyResponse::Anonymous);
+ let stranger = forms
+ .my_response(form_receipt::<ViewAccessLevel>(
+ RSVP_FORM,
+ STRANGER,
+ AccessLevel::View,
+ ))
+ .await;
+ assert!(matches!(stranger, Err(FormError::NoResponse)));
+}
+
+#[tokio::test]
+async fn an_anonymous_response_cannot_be_changed() {
+ let world = world();
+ seed_anonymous(&world);
+ let forms = service(&world);
+ submit_as(&forms, VIEWER, employee_answers()).await.unwrap();
+ let refused = forms
+ .edit_my_response(
+ form_receipt::<ViewAccessLevel>(RSVP_FORM, VIEWER, AccessLevel::View),
+ Submission {
+ answers: employee_answers(),
+ },
+ )
+ .await;
+ assert!(matches!(refused, Err(FormError::AnonymousResponseFinal)));
+ assert_eq!(world.lock().unwrap().batches.len(), 1);
+}
+
+#[tokio::test]
+async fn a_gate_stop_on_an_anonymous_form_leaves_no_trace() {
+ let world = world();
+ seed_anonymous(&world);
+ let outcome = submit_as(
+ &service(&world),
+ VIEWER,
+ vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(CONTRACTOR)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ ],
+ )
+ .await
+ .unwrap();
+ assert!(matches!(outcome, SubmissionOutcome::Stopped { .. }));
+ let world = world.lock().unwrap();
+ assert!(world.ledger.is_empty());
+ assert!(world.receipts.is_empty());
+}
+
+#[tokio::test]
+async fn whether_a_form_is_anonymous_is_fixed_once_anyone_responds() {
+ for (starts_anonymous, change) in [(false, true), (true, false)] {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ world.lock().unwrap().forms[0].form.anonymous = starts_anonymous;
+ let forms = service(&world);
+ submit_as(&forms, VIEWER, employee_answers()).await.unwrap();
+ let refused = forms
+ .update_form(
+ form_receipt::<EditAccessLevel>(RSVP_FORM, OWNER, AccessLevel::Owner),
+ UpdateForm {
+ anonymous: Some(change),
+ ..UpdateForm::default()
+ },
+ )
+ .await;
+ assert!(matches!(
+ refused,
+ Err(FormError::InvalidSharing(SharingRefusal::AnonymityLocked))
+ ));
+ assert_eq!(
+ world.lock().unwrap().forms[0].form.anonymous,
+ starts_anonymous
+ );
+ }
+}
+
+#[tokio::test]
+async fn a_form_turns_anonymous_while_nobody_has_responded() {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ let form = service(&world)
+ .update_form(
+ form_receipt::<EditAccessLevel>(RSVP_FORM, OWNER, AccessLevel::Owner),
+ UpdateForm {
+ anonymous: Some(true),
+ ..UpdateForm::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(form.anonymous);
+}
+
+#[tokio::test]
+async fn a_form_created_anonymous_has_no_respondent_column() {
+ let world = world();
+ let detail = service(&world)
+ .create_form(
+ viewer(OWNER),
+ CreateFormCommand {
+ name: "Lunch poll".into(),
+ source: CreateSource::NewDatabase {
+ is_hidden_in_drive: true,
+ anonymous: true,
+ },
+ },
+ )
+ .await
+ .unwrap();
+ assert!(detail.form.anonymous);
+ assert_eq!(detail.form.respondent_column_id, None);
+ let world = world.lock().unwrap();
+ let names: Vec<&str> = world.databases[0].tables[0]
+ .columns
+ .iter()
+ .map(|column| column.name.as_str())
+ .collect();
+ assert_eq!(names, vec!["Submitted"]);
+}
+
+/// Everything a fmt subscriber writes, spans opening and closing included.
+#[derive(Clone, Default)]
+struct Captured(Arc<Mutex<Vec<u8>>>);
+
+impl std::io::Write for Captured {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn no_span_or_log_of_an_anonymous_response_names_its_respondent() {
+ let captured = Captured::default();
+ let writer = captured.clone();
+ let subscriber = tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::TRACE)
+ .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL)
+ .with_ansi(false)
+ .with_writer(move || writer.clone())
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+ tracing::callsite::rebuild_interest_cache();
+
+ let world = world();
+ seed_anonymous(&world);
+ let forms = service(&world);
+ submit_as(&forms, VIEWER, employee_answers()).await.unwrap();
+ // A refused second vote logs its error.
+ let again = submit_as(&forms, VIEWER, employee_answers()).await;
+ assert!(matches!(again, Err(FormError::AlreadyResponded)));
+
+ let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
+ assert!(output.contains("submit_response"), "spans were captured");
+ assert!(!output.contains(VIEWER), "{output}");
+}
diff --git a/crates/forms/src/domain/service/test/authoring_workflow.rs b/crates/forms/src/domain/service/test/authoring_workflow.rs
index d650359281..87f637a030 100644
--- a/crates/forms/src/domain/service/test/authoring_workflow.rs
+++ b/crates/forms/src/domain/service/test/authoring_workflow.rs
@@ -190,6 +190,8 @@ async fn authoring_preserves_human_edits_then_opens_directly_without_response_le
status: FormStatus::Open,
closes_at: None,
tally_visible: false,
+ responses_visible: None,
+ anonymous: None,
channel_grants: vec![],
},
};
@@ -491,6 +493,8 @@ async fn owners_can_close_an_open_form_with_an_invalid_newer_draft() {
status: FormStatus::Closed,
closes_at: None,
tally_visible: false,
+ responses_visible: None,
+ anonymous: None,
channel_grants: vec![],
},
},
@@ -876,6 +880,8 @@ async fn review_regression_sharing_preserves_human_reference_questions_and_empty
status: FormStatus::Open,
closes_at: None,
tally_visible: false,
+ responses_visible: None,
+ anonymous: None,
channel_grants: vec![],
},
},
@@ -998,6 +1004,8 @@ async fn review_regression_equivalent_revision_bytes_remain_projected_and_editab
status: FormStatus::Closed,
closes_at: None,
tally_visible: false,
+ responses_visible: None,
+ anonymous: None,
channel_grants: vec![],
},
},
@@ -1412,6 +1420,8 @@ async fn direct_access_changes_use_existing_channel_sharing_and_report_partial_f
status: FormStatus::Open,
closes_at: None,
tally_visible: false,
+ responses_visible: None,
+ anonymous: None,
channel_grants: vec![GrantChange::Upsert {
channel_id: channel,
access: GrantAccess::View,
diff --git a/crates/forms/src/domain/service/test/booking.rs b/crates/forms/src/domain/service/test/booking.rs
index 4ccfc73bd1..4ff3f187e7 100644
--- a/crates/forms/src/domain/service/test/booking.rs
+++ b/crates/forms/src/domain/service/test/booking.rs
@@ -9,7 +9,7 @@ use serde_json::json;
use super::*;
use crate::domain::models::{
- Answer, FormError, MyResponse, ResponseStatus, Submission, SubmissionOutcome,
+ Answer, FormError, FormResponse, MyResponse, ResponseStatus, Submission, SubmissionOutcome,
};
use crate::domain::ports::FormsService;
@@ -96,7 +96,7 @@ async fn edit_as(
.await
}
-async fn mine(forms: &Service, user: &'static str) -> MyResponse {
+async fn my_response(forms: &Service, user: &'static str) -> MyResponse {
forms
.my_response(form_receipt::<ViewAccessLevel>(
RSVP_FORM,
@@ -107,6 +107,28 @@ async fn mine(forms: &Service, user: &'static str) -> MyResponse {
.unwrap()
}
+/// A saved response as `my_response` reads it.
+struct Saved {
+ response: Box<FormResponse>,
+ answers: Vec<Answer>,
+ booking: Option<UnlockedBooking>,
+}
+
+async fn mine(forms: &Service, user: &'static str) -> Saved {
+ match my_response(forms, user).await {
+ MyResponse::Saved {
+ response,
+ answers,
+ booking,
+ } => Saved {
+ response,
+ answers,
+ booking,
+ },
+ MyResponse::Anonymous => panic!("a saved response, not an anonymous one"),
+ }
+}
+
/// Whether the booking destination appears anywhere in `text`.
fn reveals_target(text: &str) -> bool {
text.contains(&PROFILE.to_string()) || text.contains(&EVENT_TYPE.to_string())
@@ -404,10 +426,16 @@ async fn a_stopped_response_reads_back_no_booking_step() {
submit_as(&forms, VIEWER, answers(CONTRACTOR))
.await
.unwrap();
- let mine = mine(&forms, VIEWER).await;
- assert_eq!(mine.response.status, ResponseStatus::Stopped);
- assert_eq!(mine.booking, None);
- assert!(!reveals_target(&serde_json::to_string(&mine).unwrap()));
+ let wire = my_response(&forms, VIEWER).await;
+ let MyResponse::Saved {
+ response, booking, ..
+ } = &wire
+ else {
+ panic!("a saved response");
+ };
+ assert_eq!(response.status, ResponseStatus::Stopped);
+ assert_eq!(*booking, None);
+ assert!(!reveals_target(&serde_json::to_string(&wire).unwrap()));
}
#[tokio::test]
@@ -494,10 +522,10 @@ async fn my_response_without_a_booking_step_serializes_no_booking_field() {
submit_as(&forms, VIEWER, answers(CONTRACTOR))
.await
.unwrap();
- let wire = serde_json::to_value(mine(&forms, VIEWER).await).unwrap();
+ let wire = serde_json::to_value(my_response(&forms, VIEWER).await).unwrap();
assert!(wire.get("booking").is_none());
- assert_eq!(
- serde_json::from_value::<MyResponse>(wire).unwrap().booking,
- None
- );
+ assert!(matches!(
+ serde_json::from_value::<MyResponse>(wire).unwrap(),
+ MyResponse::Saved { booking: None, .. }
+ ));
}
diff --git a/crates/forms/src/domain/service/test/create.rs b/crates/forms/src/domain/service/test/create.rs
index 704907c3ab..ae76fdfec2 100644
--- a/crates/forms/src/domain/service/test/create.rs
+++ b/crates/forms/src/domain/service/test/create.rs
@@ -101,6 +101,8 @@ async fn a_form_over_a_table_asks_every_column_and_adds_the_managed_ones() {
updated_at: start_of_tests(),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
access: FormAccess::Owner,
table_gone: false,
@@ -298,6 +300,7 @@ async fn a_form_needs_a_name() {
name: " ".into(),
source: CreateSource::NewDatabase {
is_hidden_in_drive: false,
+ anonymous: false,
},
},
)
@@ -310,6 +313,7 @@ async fn a_form_needs_a_name() {
name: "x".repeat(201),
source: CreateSource::NewDatabase {
is_hidden_in_drive: false,
+ anonymous: false,
},
},
)
@@ -328,6 +332,7 @@ async fn a_form_over_a_new_database_can_stay_out_of_drive() {
name: "Lunch?".into(),
source: CreateSource::NewDatabase {
is_hidden_in_drive: true,
+ anonymous: false,
},
},
)
@@ -348,6 +353,7 @@ async fn a_new_database_whose_setup_fails_is_removed_and_no_form_is_left() {
name: "Q4 offsite RSVP".into(),
source: CreateSource::NewDatabase {
is_hidden_in_drive: false,
+ anonymous: false,
},
},
)
diff --git a/crates/forms/src/domain/service/test/end_to_end.rs b/crates/forms/src/domain/service/test/end_to_end.rs
index d8c0e1e6ff..a43332d8cd 100644
--- a/crates/forms/src/domain/service/test/end_to_end.rs
+++ b/crates/forms/src/domain/service/test/end_to_end.rs
@@ -51,6 +51,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
name: "Q4 offsite RSVP".into(),
source: CreateSource::NewDatabase {
is_hidden_in_drive: false,
+ anonymous: false,
},
},
)
@@ -84,6 +85,8 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
updated_at: Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap(),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
access: FormAccess::Owner,
table_gone: false,
diff --git a/crates/forms/src/domain/service/test/fakes.rs b/crates/forms/src/domain/service/test/fakes.rs
index db6b93cfad..cb7963006a 100644
--- a/crates/forms/src/domain/service/test/fakes.rs
+++ b/crates/forms/src/domain/service/test/fakes.rs
@@ -56,6 +56,8 @@ pub(crate) struct World {
/// Owner grants the repository wrote with each new form.
pub(crate) owner_grants: Vec<(FormId, String)>,
pub(crate) ledger: Vec<LedgerEntry>,
+ /// Who has responded to each anonymous form.
+ pub(crate) receipts: Vec<(FormId, String)>,
pub(crate) channel_grants: HashMap<FormId, Vec<ChannelSharePermission>>,
/// Every form a liveness ping named, oldest first.
pub(crate) form_pings: Vec<FormId>,
@@ -115,6 +117,7 @@ impl World {
draft_update_before_next_write: None,
owner_grants: vec![],
ledger: vec![],
+ receipts: vec![],
channel_grants: HashMap::new(),
form_grants: HashMap::new(),
form_pings: vec![],
@@ -457,6 +460,15 @@ impl FormsRepo for FakeRepo {
{
return Ok(FormUpdate::WidgetInUse);
}
+ if changes
+ .anonymous
+ .is_some_and(|anonymous| anonymous != world.forms[position].form.anonymous)
+ && world.ledger.iter().any(|entry| {
+ entry.response.form_id == id && entry.response.status == ResponseStatus::Submitted
+ })
+ {
+ return Ok(FormUpdate::AnonymityLocked);
+ }
let form = &mut world.forms[position].form;
if let Some(description) = &changes.description {
form.description = description.clone();
@@ -476,6 +488,12 @@ impl FormsRepo for FakeRepo {
if let Some(tally_visible) = changes.tally_visible {
form.tally_visible = tally_visible;
}
+ if let Some(responses_visible) = changes.responses_visible {
+ form.responses_visible = responses_visible;
+ }
+ if let Some(anonymous) = changes.anonymous {
+ form.anonymous = anonymous;
+ }
if let Some(logo_file_id) = changes.logo_file_id {
form.branding.logo_file_id = logo_file_id;
}
@@ -567,6 +585,7 @@ impl FormsRepo for FakeRepo {
world.forms.retain(|stored| stored.form.id != id);
world.layouts.remove(&id);
world.ledger.retain(|entry| entry.response.form_id != id);
+ world.receipts.retain(|(form, _)| *form != id);
world.owner_grants.retain(|(form, _)| *form != id);
world.channel_grants.remove(&id);
Ok(())
@@ -670,6 +689,47 @@ impl FormsRepo for FakeRepo {
Ok(RecordedResponse::Recorded(response))
}
+ async fn record_anonymous_submission(
+ &self,
+ form: FormId,
+ voter: Option<&MacroUserIdStr<'_>>,
+ row: RowId,
+ day: DateTime<Utc>,
+ ) -> Result<RecordedResponse, FakeError> {
+ let mut world = self.0.lock().unwrap();
+ ledger_write(&mut world)?;
+ if let Some(voter) = voter {
+ let receipt = (form, voter.to_string());
+ if world.receipts.contains(&receipt) {
+ return Ok(RecordedResponse::AlreadySubmitted);
+ }
+ world.receipts.push(receipt);
+ }
+ let response = FormResponse {
+ id: FormResponseId::from_uuid(uuid::Uuid::new_v4()),
+ form_id: form,
+ status: ResponseStatus::Submitted,
+ stopped_at_section: None,
+ row: Some(row),
+ submitted_at: day,
+ updated_at: day,
+ };
+ world.ledger.push(LedgerEntry {
+ response: response.clone(),
+ respondent: None,
+ });
+ Ok(RecordedResponse::Recorded(response))
+ }
+
+ async fn holds_receipt(
+ &self,
+ form: FormId,
+ voter: &MacroUserIdStr<'_>,
+ ) -> Result<bool, FakeError> {
+ let world = self.0.lock().unwrap();
+ Ok(world.receipts.contains(&(form, voter.to_string())))
+ }
+
async fn repoint_response(
&self,
response: FormResponseId,
@@ -724,6 +784,29 @@ impl FormsRepo for FakeRepo {
counts.stopped_by_section = stopped.into_iter().collect();
Ok(counts)
}
+
+ async fn respondents_by_row(
+ &self,
+ form: FormId,
+ ) -> Result<Vec<(RowId, MacroUserIdStr<'static>)>, FakeError> {
+ let world = self.0.lock().unwrap();
+ let mut entries: Vec<&LedgerEntry> = world
+ .ledger
+ .iter()
+ .filter(|entry| {
+ entry.response.form_id == form && entry.response.status == ResponseStatus::Submitted
+ })
+ .collect();
+ entries.sort_by_key(|entry| (entry.response.submitted_at, entry.response.id));
+ Ok(entries
+ .into_iter()
+ .filter_map(|entry| {
+ let row = entry.response.row?;
+ let respondent = MacroUserIdStr::try_from(entry.respondent.clone()?).ok()?;
+ Some((row, respondent))
+ })
+ .collect())
+ }
}
impl FormSharingRepo for FakeRepo {
diff --git a/crates/forms/src/domain/service/test/fakes/databases.rs b/crates/forms/src/domain/service/test/fakes/databases.rs
index 7a2cd224ae..9ff98ece5b 100644
--- a/crates/forms/src/domain/service/test/fakes/databases.rs
+++ b/crates/forms/src/domain/service/test/fakes/databases.rs
@@ -700,6 +700,13 @@ impl DatabasesService for FakeDatabases {
}
if let Some((form, respondent)) = world.competing_submission.take() {
let at = world.now;
+ let anonymous = world
+ .forms
+ .iter()
+ .any(|stored| stored.form.id == form && stored.form.anonymous);
+ if anonymous {
+ world.receipts.push((form, respondent.clone()));
+ }
world.ledger.push(super::LedgerEntry {
response: crate::domain::models::FormResponse {
id: crate::domain::models::FormResponseId::new(),
@@ -710,7 +717,7 @@ impl DatabasesService for FakeDatabases {
submitted_at: at,
updated_at: at,
},
- respondent: Some(respondent),
+ respondent: (!anonymous).then_some(respondent),
});
}
let position = world
diff --git a/crates/forms/src/domain/service/test/layout.rs b/crates/forms/src/domain/service/test/layout.rs
index 8735ccae1c..78444715da 100644
--- a/crates/forms/src/domain/service/test/layout.rs
+++ b/crates/forms/src/domain/service/test/layout.rs
@@ -29,6 +29,8 @@ fn respondent_details_withhold_the_booking_destination() {
updated_at: start_of_tests(),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
};
let layout = FormLayout {
sections: vec![FormSection::Booking {
diff --git a/crates/forms/src/domain/service/test/lifecycle.rs b/crates/forms/src/domain/service/test/lifecycle.rs
index 233fe68062..e896a3f3dd 100644
--- a/crates/forms/src/domain/service/test/lifecycle.rs
+++ b/crates/forms/src/domain/service/test/lifecycle.rs
@@ -48,6 +48,14 @@ async fn an_editor_changes_the_wording_but_only_the_owner_changes_who_responds_a
tally_visible: Some(true),
..UpdateForm::default()
},
+ UpdateForm {
+ responses_visible: Some(true),
+ ..UpdateForm::default()
+ },
+ UpdateForm {
+ anonymous: Some(true),
+ ..UpdateForm::default()
+ },
] {
let refused = forms
.update_form(
@@ -67,6 +75,8 @@ async fn an_editor_changes_the_wording_but_only_the_owner_changes_who_responds_a
status: Some(FormStatus::Closed),
closes_at: Some(Some(closing)),
tally_visible: Some(true),
+ responses_visible: Some(true),
+ anonymous: Some(true),
..UpdateForm::default()
},
)
@@ -76,6 +86,8 @@ async fn an_editor_changes_the_wording_but_only_the_owner_changes_who_responds_a
assert_eq!(owned.status, FormStatus::Closed);
assert_eq!(owned.closes_at, Some(closing));
assert!(owned.tally_visible);
+ assert!(owned.responses_visible);
+ assert!(owned.anonymous);
let reopened = forms
.update_form(
diff --git a/crates/forms/src/domain/service/test/names.rs b/crates/forms/src/domain/service/test/names.rs
index aab2f8ea19..4e3c83cfdc 100644
--- a/crates/forms/src/domain/service/test/names.rs
+++ b/crates/forms/src/domain/service/test/names.rs
@@ -26,6 +26,7 @@ async fn create_standalone(world: &Shared) -> (FormId, DatabaseId) {
name: "Offsite RSVP".into(),
source: CreateSource::NewDatabase {
is_hidden_in_drive: false,
+ anonymous: false,
},
},
)
@@ -133,6 +134,8 @@ async fn which_name_a_new_form_goes_by_is_recorded_from_where_it_was_created() {
updated_at: start_of_tests(),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
trashed_at: None,
name_follows_database: true,
diff --git a/crates/forms/src/domain/service/test/responses.rs b/crates/forms/src/domain/service/test/responses.rs
index 3fd8d88e62..907459ff28 100644
--- a/crates/forms/src/domain/service/test/responses.rs
+++ b/crates/forms/src/domain/service/test/responses.rs
@@ -76,8 +76,8 @@ async fn a_respondent_reads_their_response_back_from_the_row_as_it_is_now() {
.unwrap();
assert_eq!(
mine,
- MyResponse {
- response: FormResponse {
+ MyResponse::Saved {
+ response: Box::new(FormResponse {
id: response,
form_id: RSVP_FORM,
status: ResponseStatus::Submitted,
@@ -85,7 +85,7 @@ async fn a_respondent_reads_their_response_back_from_the_row_as_it_is_now() {
row: Some(row),
submitted_at: start_of_tests(),
updated_at: start_of_tests(),
- },
+ }),
answers: vec![
Answer {
question: TEAM_QUESTION,
@@ -145,7 +145,10 @@ async fn a_response_whose_row_was_deleted_reads_with_no_answers() {
))
.await
.unwrap();
- assert_eq!(mine.answers, vec![]);
+ let MyResponse::Saved { answers, .. } = mine else {
+ panic!("a saved response");
+ };
+ assert_eq!(answers, vec![]);
}
#[tokio::test]
@@ -437,6 +440,8 @@ async fn the_tally_counts_every_option_and_checkbox_in_layout_order() {
seed_rsvp(&world, Audience::Members);
let forms = service(&world);
respond(&forms, VIEWER, answers(EMPLOYEE, None)).await;
+ // Voters list in submission order, so the second response lands later.
+ world.lock().unwrap().now = Utc.with_ymd_and_hms(2026, 9, 3, 8, 0, 0).unwrap();
let mut with_plus_one = answers(EMPLOYEE, None);
with_plus_one.push(Answer {
question: PLUS_ONE_QUESTION,
@@ -463,10 +468,12 @@ async fn the_tally_counts_every_option_and_checkbox_in_layout_order() {
TallyBucket {
value: TallyValue::Option { option: EMPLOYEE },
count: 2,
+ voters: Some(vec![VIEWER.to_string(), EDITOR.to_string()]),
},
TallyBucket {
value: TallyValue::Option { option: CONTRACTOR },
count: 0,
+ voters: Some(Vec::new()),
},
],
},
@@ -477,10 +484,12 @@ async fn the_tally_counts_every_option_and_checkbox_in_layout_order() {
TallyBucket {
value: TallyValue::Checkbox { checked: true },
count: 1,
+ voters: Some(vec![EDITOR.to_string()]),
},
TallyBucket {
value: TallyValue::Checkbox { checked: false },
count: 0,
+ voters: Some(Vec::new()),
},
],
},
@@ -526,6 +535,61 @@ async fn respondents_read_the_tally_only_when_the_owner_shows_it() {
.unwrap();
}
+#[tokio::test]
+async fn respondents_see_who_voted_only_when_the_responses_are_shared() {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ world.lock().unwrap().forms[0].form.tally_visible = true;
+ let forms = service(&world);
+ respond(&forms, VIEWER, answers(EMPLOYEE, None)).await;
+ let voters_seen_by_viewer = || async {
+ forms
+ .tally(form_receipt::<ViewAccessLevel>(
+ RSVP_FORM,
+ VIEWER,
+ AccessLevel::View,
+ ))
+ .await
+ .unwrap()
+ .questions[0]
+ .buckets[0]
+ .voters
+ .clone()
+ };
+
+ assert_eq!(voters_seen_by_viewer().await, None);
+
+ world.lock().unwrap().forms[0].form.responses_visible = true;
+ assert_eq!(
+ voters_seen_by_viewer().await,
+ Some(vec![VIEWER.to_string()])
+ );
+}
+
+#[tokio::test]
+async fn nobody_sees_who_voted_on_an_anonymous_form_not_even_its_owner() {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ {
+ let mut world = world.lock().unwrap();
+ world.forms[0].form.anonymous = true;
+ world.forms[0].form.responses_visible = true;
+ }
+ let forms = service(&world);
+ respond(&forms, VIEWER, answers(EMPLOYEE, None)).await;
+
+ let tally = forms
+ .tally(form_receipt::<ViewAccessLevel>(
+ RSVP_FORM,
+ OWNER,
+ AccessLevel::Owner,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(tally.questions[0].buckets[0].count, 1);
+ assert_eq!(tally.questions[0].buckets[0].voters, None);
+}
+
#[tokio::test]
async fn rewriting_a_lost_row_skips_managed_columns_retyped_in_the_grid() {
let world = world();
@@ -597,9 +661,17 @@ async fn a_database_trashed_while_reading_ones_response_reads_as_the_receipt_wit
.await
.unwrap();
- assert_eq!(mine.response.id, response);
- assert_eq!(mine.response.row, Some(row));
- assert_eq!(mine.answers, vec![]);
+ let MyResponse::Saved {
+ response: entry,
+ answers,
+ ..
+ } = mine
+ else {
+ panic!("a saved response");
+ };
+ assert_eq!(entry.id, response);
+ assert_eq!(entry.row, Some(row));
+ assert_eq!(answers, vec![]);
}
#[tokio::test]
diff --git a/crates/forms/src/inbound/axum_router/error.rs b/crates/forms/src/inbound/axum_router/error.rs
index 6d8fbb9cc5..886ed60af2 100644
--- a/crates/forms/src/inbound/axum_router/error.rs
+++ b/crates/forms/src/inbound/axum_router/error.rs
@@ -128,6 +128,10 @@ impl IntoResponse for FormsApiError {
StatusCode::NOT_FOUND,
body(FormErrorCode::NoResponse, message),
),
+ FormError::AnonymousResponseFinal => (
+ StatusCode::CONFLICT,
+ body(FormErrorCode::AnonymousResponseFinal, message),
+ ),
FormError::UnknownQuestion { question } => (
StatusCode::BAD_REQUEST,
FormErrorResponse {
diff --git a/crates/forms/src/inbound/axum_router/forms.rs b/crates/forms/src/inbound/axum_router/forms.rs
index b04c4e56ad..99239062d3 100644
--- a/crates/forms/src/inbound/axum_router/forms.rs
+++ b/crates/forms/src/inbound/axum_router/forms.rs
@@ -65,7 +65,13 @@ where
..creator.clone()
};
let source = match request.source {
- FormSource::New { is_hidden_in_drive } => CreateSource::NewDatabase { is_hidden_in_drive },
+ FormSource::New {
+ is_hidden_in_drive,
+ anonymous,
+ } => CreateSource::NewDatabase {
+ is_hidden_in_drive,
+ anonymous,
+ },
FormSource::Table {
database_id,
table_id,
diff --git a/crates/forms/src/inbound/axum_router/test/fakes.rs b/crates/forms/src/inbound/axum_router/test/fakes.rs
index 01c79f12da..6b6d9fcf93 100644
--- a/crates/forms/src/inbound/axum_router/test/fakes.rs
+++ b/crates/forms/src/inbound/axum_router/test/fakes.rs
@@ -260,6 +260,8 @@ pub(super) fn form() -> Form {
updated_at: at,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
}
}
diff --git a/crates/forms/src/inbound/toolset/set_form_access.rs b/crates/forms/src/inbound/toolset/set_form_access.rs
index fbd93cdf0b..9ee3899860 100644
--- a/crates/forms/src/inbound/toolset/set_form_access.rs
+++ b/crates/forms/src/inbound/toolset/set_form_access.rs
@@ -11,7 +11,7 @@ use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[schemars(
title = "SetFormAccess",
- description = "Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Public allows anonymous responses. View allows responding without database access; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open."
+ description = "Open, close or share a saved form immediately. Requires Form Owner. Supply complete audience/status/deadline/tally settings and explicit channel grant deltas; empty deltas change no grants. Optional responsesVisible lets View holders read response rows; optional anonymous makes the form anonymous to everyone, its owner included (who responded is kept apart from the responses), and is refused once anyone has responded. Public allows anonymous responses. View allows responding without database access unless responses are shared; channel Edit grants editing of the entire backing database. Uses the existing Forms settings and sharing services without a review step. This never posts a message or sends invitations. Settings and channel grants are separate writes; inspect partial results before retrying. Returns actual access, canonical links and acceptingResponses; a URL alone does not mean the form is open."
)]
pub struct SetFormAccess {
/// Flat workflow arguments shared with the domain service.
diff --git a/crates/forms/src/outbound/pg_forms_repo.rs b/crates/forms/src/outbound/pg_forms_repo.rs
index 63e7c94d7d..3e70f6143c 100644
--- a/crates/forms/src/outbound/pg_forms_repo.rs
+++ b/crates/forms/src/outbound/pg_forms_repo.rs
@@ -102,6 +102,8 @@ struct FormRow {
trashed_at: Option<DateTime<Utc>>,
name_follows_database: bool,
is_hidden_in_drive: bool,
+ responses_visible: bool,
+ anonymous: bool,
project_id: Option<String>,
}
@@ -143,6 +145,8 @@ impl TryFrom<FormRow> for StoredForm {
updated_at: row.updated_at,
project_id: row.project_id,
is_hidden_in_drive: row.is_hidden_in_drive,
+ responses_visible: row.responses_visible,
+ anonymous: row.anonymous,
},
trashed_at: row.trashed_at,
name_follows_database: row.name_follows_database,
@@ -189,11 +193,11 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
id, name, description, owner_id, database_id, table_id,
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id,
- accent_color, created_at, updated_at, name_follows_database, is_hidden_in_drive
+ accent_color, created_at, updated_at, name_follows_database, is_hidden_in_drive, responses_visible, anonymous
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,
- $19, $20
+ $19, $20, $21, $22
)
ON CONFLICT (table_id) DO NOTHING
"#,
@@ -217,6 +221,8 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
form.updated_at,
name_follows_database,
form.is_hidden_in_drive,
+ form.responses_visible,
+ form.anonymous,
)
.execute(&mut *transaction)
.await;
@@ -264,7 +270,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
FROM forms WHERE id = $1
"#,
id.into_uuid(),
@@ -285,7 +291,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
FROM forms WHERE id = ANY($1) AND trashed_at IS NULL
ORDER BY id
"#,
@@ -319,7 +325,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
FROM forms WHERE database_id = $1 AND trashed_at IS NULL
ORDER BY created_at, id
"#,
@@ -391,6 +397,27 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
return Ok(FormUpdate::WidgetInUse);
}
}
+ // The form's row lock also waits out a response being recorded, so
+ // no response lands between this check and the change.
+ if let Some(anonymous) = changes.anonymous {
+ let locked = sqlx::query_scalar!(
+ r#"
+ SELECT f.anonymous <> $2 AND EXISTS (
+ SELECT 1 FROM form_responses
+ WHERE form_id = f.id AND status = 'submitted'
+ ) AS "locked!"
+ FROM forms f WHERE f.id = $1
+ "#,
+ id.into_uuid(),
+ anonymous,
+ )
+ .fetch_one(&mut *transaction)
+ .await?;
+ if locked {
+ transaction.rollback().await?;
+ return Ok(FormUpdate::AnonymityLocked);
+ }
+ }
let updated = sqlx::query_as!(
FormRow,
r#"
@@ -404,13 +431,15 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
logo_file_id = CASE WHEN $10 THEN $11 ELSE logo_file_id END,
cover_file_id = CASE WHEN $12 THEN $13 ELSE cover_file_id END,
accent_color = CASE WHEN $14 THEN $15 ELSE accent_color END,
+ responses_visible = COALESCE($16, responses_visible),
+ anonymous = COALESCE($17, anonymous),
updated_at = $9
WHERE id = $1
RETURNING id, name, description, owner_id, database_id, table_id,
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
"#,
id.into_uuid(),
changes.description.as_deref(),
@@ -430,6 +459,8 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
.accent_color
.as_ref()
.and_then(|color| color.as_ref().map(AccentColor::as_str)),
+ changes.responses_visible,
+ changes.anonymous,
)
.fetch_one(&mut *transaction)
.await?;
@@ -454,7 +485,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
"#,
id.into_uuid(),
name,
@@ -481,7 +512,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive, project_id
+ name_follows_database, is_hidden_in_drive, project_id, responses_visible, anonymous
"#,
id.into_uuid(),
updated_at,
@@ -567,6 +598,24 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
ledger::record_submission(&self.pool, form, respondent, row, at).await
}
+ async fn record_anonymous_submission(
+ &self,
+ form: FormId,
+ voter: Option<&MacroUserIdStr<'_>>,
+ row: RowId,
+ day: DateTime<Utc>,
+ ) -> Result<RecordedResponse, Self::Error> {
+ ledger::record_anonymous_submission(&self.pool, form, voter, row, day).await
+ }
+
+ async fn holds_receipt(
+ &self,
+ form: FormId,
+ voter: &MacroUserIdStr<'_>,
+ ) -> Result<bool, Self::Error> {
+ ledger::holds_receipt(&self.pool, form, voter).await
+ }
+
async fn repoint_response(
&self,
response: FormResponseId,
@@ -587,4 +636,11 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
async fn response_counts(&self, form: FormId) -> Result<ResponseCounts, Self::Error> {
ledger::response_counts(&self.pool, form).await
}
+
+ async fn respondents_by_row(
+ &self,
+ form: FormId,
+ ) -> Result<Vec<(RowId, MacroUserIdStr<'static>)>, Self::Error> {
+ ledger::respondents_by_row(&self.pool, form).await
+ }
}
diff --git a/crates/forms/src/outbound/pg_forms_repo/ledger.rs b/crates/forms/src/outbound/pg_forms_repo/ledger.rs
index 98fdba59ef..1dff8522b4 100644
--- a/crates/forms/src/outbound/pg_forms_repo/ledger.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/ledger.rs
@@ -1,5 +1,7 @@
//! The submission ledger, `form_responses`. Its partial unique index on
-//! `(form_id, respondent_id)` is what keeps a signed-in person to one entry.
+//! `(form_id, respondent_id)` is what keeps a signed-in person to one entry;
+//! on an anonymous form, whose entries name nobody, the key of
+//! `form_submission_receipts` does.
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -129,6 +131,74 @@ pub(super) async fn record_submission(
})
}
+// The voter stays out of the span: it would pair them with the row.
+#[tracing::instrument(err, skip(pool, voter, row))]
+pub(super) async fn record_anonymous_submission(
+ pool: &PgPool,
+ form: FormId,
+ voter: Option<&MacroUserIdStr<'_>>,
+ row: RowId,
+ day: DateTime<Utc>,
+) -> Result<RecordedResponse, PgFormsRepoError> {
+ let mut transaction = pool.begin().await?;
+ if let Some(voter) = voter {
+ let receipt = sqlx::query_scalar!(
+ r#"
+ INSERT INTO form_submission_receipts (form_id, user_id) VALUES ($1, $2)
+ ON CONFLICT DO NOTHING
+ RETURNING 1 AS "one!"
+ "#,
+ form.into_uuid(),
+ voter.as_ref(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await?;
+ if receipt.is_none() {
+ transaction.rollback().await?;
+ return Ok(RecordedResponse::AlreadySubmitted);
+ }
+ }
+ // A random id, unlike a time-ordered one, says nothing of when or in
+ // what order people responded.
+ let recorded = sqlx::query_as!(
+ ResponseRow,
+ r#"
+ INSERT INTO form_responses (id, form_id, row_id, status, submitted_at, updated_at)
+ VALUES ($1, $2, $3, 'submitted', $4, $4)
+ RETURNING id, form_id, status, stopped_at_section, row_id, submitted_at, updated_at
+ "#,
+ Uuid::new_v4(),
+ form.into_uuid(),
+ row.into_uuid(),
+ day,
+ )
+ .fetch_one(&mut *transaction)
+ .await?;
+ transaction.commit().await?;
+ Ok(RecordedResponse::Recorded(FormResponse::try_from(
+ recorded,
+ )?))
+}
+
+#[tracing::instrument(err, skip(pool, voter))]
+pub(super) async fn holds_receipt(
+ pool: &PgPool,
+ form: FormId,
+ voter: &MacroUserIdStr<'_>,
+) -> Result<bool, PgFormsRepoError> {
+ Ok(sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM form_submission_receipts WHERE form_id = $1 AND user_id = $2
+ ) AS "held!"
+ "#,
+ form.into_uuid(),
+ voter.as_ref(),
+ )
+ .fetch_one(pool)
+ .await?)
+}
+
#[tracing::instrument(err, skip(pool))]
pub(super) async fn repoint_response(
pool: &PgPool,
@@ -202,3 +272,33 @@ pub(super) async fn response_counts(
}
Ok(counts)
}
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn respondents_by_row(
+ pool: &PgPool,
+ form: FormId,
+) -> Result<Vec<(RowId, MacroUserIdStr<'static>)>, PgFormsRepoError> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT row_id AS "row_id!", respondent_id AS "respondent_id!"
+ FROM form_responses
+ WHERE form_id = $1 AND status = 'submitted'
+ AND row_id IS NOT NULL AND respondent_id IS NOT NULL
+ ORDER BY submitted_at, id
+ "#,
+ form.into_uuid(),
+ )
+ .fetch_all(pool)
+ .await?;
+ rows.into_iter()
+ .map(|row| {
+ let respondent = MacroUserIdStr::try_from(row.respondent_id.clone()).map_err(|_| {
+ PgFormsRepoError::Corrupt {
+ kind: "respondent",
+ value: row.respondent_id,
+ }
+ })?;
+ Ok((RowId::from_uuid(row.row_id), respondent))
+ })
+ .collect()
+}
diff --git a/crates/forms/src/outbound/pg_forms_repo/test.rs b/crates/forms/src/outbound/pg_forms_repo/test.rs
index 379f3de053..468bc8fa4a 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test.rs
@@ -11,6 +11,7 @@ use models_permissions::share_permission::channel_share_permission::{
use super::*;
+mod anonymous;
mod booking;
mod drafts;
mod folders;
@@ -176,6 +177,8 @@ fn form_over(table: &Table) -> Form {
updated_at: at(9),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
}
}
@@ -261,6 +264,8 @@ async fn a_form_hidden_in_drive_stays_hidden_through_a_rename(pool: PgPool) {
let repo = PgFormsRepo::new(pool.clone());
let form = Form {
is_hidden_in_drive: true,
+ responses_visible: false,
+ anonymous: false,
..form_over(&table)
};
repo.create_form(&form, &layout_over(&table), true)
@@ -359,6 +364,8 @@ async fn facts_change_only_where_given_and_a_closing_time_can_be_cleared(pool: P
status: Some(FormStatus::Closed),
closes_at: Some(Some(at(17))),
tally_visible: Some(true),
+ responses_visible: None,
+ anonymous: None,
logo_file_id: Some(Some(Uuid::from_u128(0x1060))),
cover_file_id: None,
accent_color: Some(Some(AccentColor::try_from("#1f6feb".to_string()).unwrap())),
@@ -530,6 +537,33 @@ async fn anonymous_responses_are_unbounded_and_counted(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn respondents_by_row_name_signed_in_responses_in_submission_order(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = form_over(&table);
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+ let later = insert_row(&pool, table.table, "a0").await;
+ let earlier = insert_row(&pool, table.table, "a1").await;
+ let anonymous = insert_row(&pool, table.table, "a2").await;
+ repo.record_submission(form.id, Some(&user(OWNER)), later, at(11))
+ .await
+ .unwrap();
+ repo.record_submission(form.id, Some(&user(RESPONDENT)), earlier, at(10))
+ .await
+ .unwrap();
+ repo.record_submission(form.id, None, anonymous, at(9))
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.respondents_by_row(form.id).await.unwrap(),
+ vec![(earlier, user(RESPONDENT)), (later, user(OWNER))]
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn concurrent_responses_by_one_person_record_exactly_one(pool: PgPool) {
let table = insert_table(&pool).await;
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/anonymous.rs b/crates/forms/src/outbound/pg_forms_repo/test/anonymous.rs
new file mode 100644
index 0000000000..cccb7ab476
--- /dev/null
+++ b/crates/forms/src/outbound/pg_forms_repo/test/anonymous.rs
@@ -0,0 +1,135 @@
+//! An anonymous form's ledger: receipts say who responded, entries say what,
+//! and nothing joins the two.
+
+use super::*;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_anonymous_response_is_a_receipt_and_an_entry_that_name_nothing_of_each_other(
+ pool: PgPool,
+) {
+ let table = insert_table(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = Form {
+ anonymous: true,
+ ..form_over(&table)
+ };
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+ let voter = user(RESPONDENT);
+ let row = insert_row(&pool, table.table, "a0").await;
+ let day = Utc.with_ymd_and_hms(2026, 9, 1, 0, 0, 0).unwrap();
+ assert!(!repo.holds_receipt(form.id, &voter).await.unwrap());
+
+ let RecordedResponse::Recorded(entry) = repo
+ .record_anonymous_submission(form.id, Some(&voter), row, day)
+ .await
+ .unwrap()
+ else {
+ panic!("recorded");
+ };
+
+ assert!(repo.holds_receipt(form.id, &voter).await.unwrap());
+ assert_eq!(entry.id.into_uuid().get_version_num(), 4);
+ let stored = sqlx::query!(
+ "SELECT respondent_id, row_id, submitted_at, updated_at FROM form_responses WHERE form_id = $1",
+ form.id.into_uuid(),
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1);
+ assert_eq!(stored[0].respondent_id, None);
+ assert_eq!(stored[0].row_id, Some(row.into_uuid()));
+ assert_eq!(stored[0].submitted_at, day);
+ assert_eq!(stored[0].updated_at, day);
+ let receipts = sqlx::query!("SELECT form_id, user_id FROM form_submission_receipts",)
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(receipts.len(), 1);
+ assert_eq!(receipts[0].form_id, form.id.into_uuid());
+ assert_eq!(receipts[0].user_id, RESPONDENT);
+ assert_eq!(repo.respondents_by_row(form.id).await.unwrap(), vec![]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_anonymous_responses_by_one_person_record_exactly_one(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = Form {
+ anonymous: true,
+ ..form_over(&table)
+ };
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+ let voter = user(RESPONDENT);
+ let first_row = insert_row(&pool, table.table, "a0").await;
+ let second_row = insert_row(&pool, table.table, "a1").await;
+ // Each runs on its own pooled connection; the receipt's key serializes
+ // them, and the loser's entry rolls back with its receipt.
+ let (first, second) = tokio::join!(
+ repo.record_anonymous_submission(form.id, Some(&voter), first_row, at(0)),
+ repo.record_anonymous_submission(form.id, Some(&voter), second_row, at(0)),
+ );
+ let outcomes = [first.unwrap(), second.unwrap()];
+ assert_eq!(
+ outcomes
+ .iter()
+ .filter(|outcome| **outcome == RecordedResponse::AlreadySubmitted)
+ .count(),
+ 1
+ );
+ let entries = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) AS "count!" FROM form_responses WHERE form_id = $1"#,
+ form.id.into_uuid(),
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(entries, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn whether_a_form_is_anonymous_cannot_change_once_a_response_is_recorded(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = form_over(&table);
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+ let anonymous = UpdateForm {
+ anonymous: Some(true),
+ ..UpdateForm::default()
+ };
+ let FormUpdate::Updated(updated) = repo
+ .update_form(form.id, &anonymous, at(10), None)
+ .await
+ .unwrap()
+ else {
+ panic!("updated");
+ };
+ assert!(updated.anonymous);
+ let row = insert_row(&pool, table.table, "a0").await;
+ repo.record_anonymous_submission(form.id, Some(&user(RESPONDENT)), row, at(0))
+ .await
+ .unwrap();
+ let named = UpdateForm {
+ anonymous: Some(false),
+ ..UpdateForm::default()
+ };
+ assert_eq!(
+ repo.update_form(form.id, &named, at(11), None)
+ .await
+ .unwrap(),
+ FormUpdate::AnonymityLocked
+ );
+ // Asking for what it already is changes nothing and is not refused.
+ assert!(matches!(
+ repo.update_form(form.id, &anonymous, at(12), None)
+ .await
+ .unwrap(),
+ FormUpdate::Updated(_)
+ ));
+}
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
index bf30e36b4c..a90f5982e6 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
@@ -24,6 +24,8 @@ async fn a_projection_commits_its_layout_and_revision_together(pool: PgPool) {
updated_at: at(9),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
};
let layout = FormLayout {
sections: vec![FormSection::Questions {
diff --git a/crates/macro_db_client/migrations/20261022144330_forms_response_visibility.sql b/crates/macro_db_client/migrations/20261022144330_forms_response_visibility.sql
new file mode 100644
index 0000000000..5b1811834e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261022144330_forms_response_visibility.sql
@@ -0,0 +1,5 @@
+-- Channel polls can share individual responses with everyone who can vote,
+-- and can hide who voted while still recording them so nobody votes twice.
+ALTER TABLE forms
+ ADD COLUMN responses_visible BOOLEAN NOT NULL DEFAULT FALSE,
+ ADD COLUMN respondent_hidden BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/crates/macro_db_client/migrations/20261103004547_forms_anonymous_receipts.sql b/crates/macro_db_client/migrations/20261103004547_forms_anonymous_receipts.sql
new file mode 100644
index 0000000000..f252abcc6f
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261103004547_forms_anonymous_receipts.sql
@@ -0,0 +1,28 @@
+-- An anonymous form keeps who voted apart from what they answered:
+-- `form_submission_receipts` says who has responded, with no response, row
+-- or time, and its key keeps them to one response. The form's ledger
+-- entries name nobody.
+ALTER TABLE forms RENAME COLUMN respondent_hidden TO anonymous;
+
+CREATE TABLE form_submission_receipts (
+ form_id UUID NOT NULL REFERENCES forms(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ PRIMARY KEY (form_id, user_id)
+);
+
+CREATE INDEX idx_form_submission_receipts_user ON form_submission_receipts(user_id);
+
+-- Forms already hiding respondents move them off their ledger entries.
+INSERT INTO form_submission_receipts (form_id, user_id)
+SELECT r.form_id, r.respondent_id
+FROM form_responses r JOIN forms f ON f.id = r.form_id
+WHERE f.anonymous AND r.respondent_id IS NOT NULL AND r.status = 'submitted';
+
+DELETE FROM form_responses r USING forms f
+WHERE f.id = r.form_id AND f.anonymous AND r.status = 'stopped';
+
+UPDATE form_responses r SET respondent_id = NULL,
+ submitted_at = date_trunc('day', r.submitted_at, 'UTC'),
+ updated_at = date_trunc('day', r.submitted_at, 'UTC')
+FROM forms f
+WHERE f.id = r.form_id AND f.anonymous;
diff --git a/crates/models_forms/src/error.rs b/crates/models_forms/src/error.rs
index f25a90d307..aaf482e4b7 100644
--- a/crates/models_forms/src/error.rs
+++ b/crates/models_forms/src/error.rs
@@ -49,6 +49,8 @@ pub enum FormErrorCode {
AlreadyResponded,
/// The caller has no saved response to read or edit.
NoResponse,
+ /// A response to an anonymous form can't be changed.
+ AnonymousResponseFinal,
/// An answer names a question the form does not ask.
UnknownQuestion,
/// A question is answered twice.
diff --git a/crates/models_forms/src/form.rs b/crates/models_forms/src/form.rs
index 8ce96958cc..15b4398d78 100644
--- a/crates/models_forms/src/form.rs
+++ b/crates/models_forms/src/form.rs
@@ -60,8 +60,9 @@ pub enum FormStatus {
Closed,
}
-/// The caller's level on a form: view responds, edit changes questions and
-/// reads responses, owner also sets the audience, closes and trashes it.
+/// The caller's level on a form: view responds (and reads responses when
+/// they are shared), edit changes questions and reads responses, owner
+/// also sets the audience, closes and trashes it.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(
Debug,
@@ -78,7 +79,7 @@ pub enum FormStatus {
)]
#[serde(rename_all = "camelCase")]
pub enum FormAccess {
- /// May respond.
+ /// May respond, and read response rows when they are shared.
View,
/// May change the questions and read the responses.
Edit,
@@ -111,13 +112,20 @@ pub struct Form {
#[schema(value_type = Option<Uuid>, required = true)]
pub submitted_column_id: Option<ColumnId>,
/// The person column each signed-in submission names its respondent in;
- /// `null` once deleted.
+ /// `null` once deleted, and on a form created anonymous. An anonymous
+ /// form never writes it.
#[schema(value_type = Option<Uuid>, required = true)]
pub respondent_column_id: Option<ColumnId>,
/// Who may respond.
pub audience: Audience,
/// Whether respondents may read option tallies.
pub tally_visible: bool,
+ /// Whether people with View may read individual response rows.
+ pub responses_visible: bool,
+ /// Whether nobody, the owner included, can see who gave which response.
+ /// Who responded is kept apart from the responses, only so nobody
+ /// responds twice. Fixed once anyone has responded.
+ pub anonymous: bool,
/// Whether its owner closed it.
pub status: FormStatus,
/// When it stops taking responses, if it does.
@@ -175,6 +183,10 @@ pub enum FormSource {
/// for a channel poll.
#[serde(default, rename = "isHiddenInDrive")]
is_hidden_in_drive: bool,
+ /// Make the form anonymous from the start: its table gets no
+ /// Respondent column.
+ #[serde(default)]
+ anonymous: bool,
},
/// An existing table in a database the caller owns. The form starts with a
/// question per column.
@@ -233,6 +245,17 @@ pub struct UpdateForm {
#[schema(nullable = false)]
#[specta(optional)]
pub tally_visible: Option<bool>,
+ /// Whether people with View may read individual response rows.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schema(nullable = false)]
+ #[specta(optional)]
+ pub responses_visible: Option<bool>,
+ /// Whether nobody can see who gave which response; refused once anyone
+ /// has responded.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schema(nullable = false)]
+ #[specta(optional)]
+ pub anonymous: Option<bool>,
/// A new logo, or `null` to remove it.
#[serde(
default,
@@ -274,6 +297,8 @@ impl UpdateForm {
|| self.status.is_some()
|| self.closes_at.is_some()
|| self.tally_visible.is_some()
+ || self.responses_visible.is_some()
+ || self.anonymous.is_some()
}
}
diff --git a/crates/models_forms/src/response.rs b/crates/models_forms/src/response.rs
index 58f50aa431..a98a4c37c0 100644
--- a/crates/models_forms/src/response.rs
+++ b/crates/models_forms/src/response.rs
@@ -110,22 +110,32 @@ pub struct FormResponse {
pub updated_at: DateTime<Utc>,
}
-/// A signed-in respondent's own response, with its answers as the row
-/// holds them now.
+/// A signed-in respondent's own response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, utoipa::ToSchema, specta::Type)]
-#[serde(rename_all = "camelCase")]
-pub struct MyResponse {
- /// The ledger entry.
- pub response: FormResponse,
- /// The row's cells for the form's current questions, the empty ones
- /// left out; none when the row is gone.
- pub answers: Vec<Answer>,
- /// The form's booking step, while the saved row still passes the form's
- /// current required questions and gates.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- #[schema(nullable = false)]
- #[specta(optional)]
- pub booking: Option<UnlockedBooking>,
+#[serde(
+ tag = "kind",
+ rename_all = "camelCase",
+ rename_all_fields = "camelCase"
+)]
+pub enum MyResponse {
+ /// Their ledger entry, with its answers as the row holds them now.
+ Saved {
+ /// The ledger entry.
+ // Boxed to keep the variants a similar size.
+ response: Box<FormResponse>,
+ /// The row's cells for the form's current questions, the empty ones
+ /// left out; none when the row is gone.
+ answers: Vec<Answer>,
+ /// The form's booking step, while the saved row still passes the
+ /// form's current required questions and gates.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schema(nullable = false)]
+ #[specta(optional)]
+ booking: Option<UnlockedBooking>,
+ },
+ /// They responded to an anonymous form. Nothing links them to their
+ /// response, so there is nothing more to show.
+ Anonymous,
}
/// A booking step a passing response has unlocked, with its destination.
@@ -201,6 +211,12 @@ pub struct TallyBucket {
pub value: TallyValue,
/// How many rows hold it.
pub count: u64,
+ /// Who chose it, as Macro user ids in submission order: present only
+ /// for the form's editors, or its viewers when it shares its responses,
+ /// and never when it hides respondents. Rows no signed-in respondent
+ /// submitted count without a voter.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub voters: Option<Vec<String>>,
}
/// A value a tally counts.
diff --git a/crates/models_forms/src/test.rs b/crates/models_forms/src/test.rs
index 1dc949c9e8..a425bdd11c 100644
--- a/crates/models_forms/src/test.rs
+++ b/crates/models_forms/src/test.rs
@@ -62,6 +62,8 @@ fn a_form_detail_reads_as_the_web_client_expects() {
updated_at: Utc.with_ymd_and_hms(2026, 9, 2, 9, 0, 0).unwrap(),
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
access: FormAccess::Edit,
table_gone: false,
@@ -118,6 +120,8 @@ fn a_form_detail_reads_as_the_web_client_expects() {
"respondentColumnId": null,
"audience": "members",
"tallyVisible": false,
+ "responsesVisible": false,
+ "anonymous": false,
"status": "open",
"closesAt": "2026-10-03T17:00:00Z",
"confirmationMessage": "",
@@ -245,7 +249,8 @@ fn a_create_request_names_its_source_by_kind() {
assert_eq!(
new.source,
FormSource::New {
- is_hidden_in_drive: false
+ is_hidden_in_drive: false,
+ anonymous: false,
}
);
@@ -256,7 +261,8 @@ fn a_create_request_names_its_source_by_kind() {
assert_eq!(
hidden.source,
FormSource::New {
- is_hidden_in_drive: true
+ is_hidden_in_drive: true,
+ anonymous: false,
}
);
@@ -351,10 +357,12 @@ fn a_tally_names_options_and_checkbox_states() {
TallyBucket {
value: TallyValue::Option { option: CONTRACTOR },
count: 2,
+ voters: Some(vec!["macro|[email protected]".to_string()]),
},
TallyBucket {
value: TallyValue::Checkbox { checked: true },
count: 1,
+ voters: None,
},
],
}],
@@ -366,7 +374,7 @@ fn a_tally_names_options_and_checkbox_states() {
"question": "00000000-0000-0000-0000-000000000091",
"responses": 3,
"buckets": [
- {"value": {"kind": "option", "option": "00000000-0000-0000-0000-0000000000c0"}, "count": 2},
+ {"value": {"kind": "option", "option": "00000000-0000-0000-0000-0000000000c0"}, "count": 2, "voters": ["macro|[email protected]"]},
{"value": {"kind": "checkbox", "checked": true}, "count": 1},
],
}],
@@ -418,6 +426,8 @@ fn a_form_takes_responses_while_open_and_before_it_closes() {
updated_at: now,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
};
assert!(form(FormStatus::Open, None).accepts_responses_at(now));
assert!(
@@ -450,6 +460,8 @@ fn a_listed_form_names_the_callers_access_beside_the_form() {
updated_at: now,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
},
access: FormAccess::View,
};
@@ -467,6 +479,8 @@ fn a_listed_form_names_the_callers_access_beside_the_form() {
"respondentColumnId": null,
"audience": "public",
"tallyVisible": true,
+ "responsesVisible": false,
+ "anonymous": false,
"status": "closed",
"closesAt": null,
"confirmationMessage": "Thanks",
@@ -543,6 +557,8 @@ fn form_and_response_schemas_require_every_field_they_always_serialize() {
updated_at: now,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
};
let response = FormResponse {
id: FormResponseId::from_uuid(Uuid::from_u128(0xe1)),
@@ -601,6 +617,8 @@ fn a_form_sends_its_branding_with_its_facts() {
updated_at: now,
project_id: None,
is_hidden_in_drive: false,
+ responses_visible: false,
+ anonymous: false,
};
assert_eq!(
serde_json::to_value(&form).unwrap()["branding"],
diff --git a/crates/soup/src/outbound/pg_soup_repo/database_row/by_ids.sql b/crates/soup/src/outbound/pg_soup_repo/database_row/by_ids.sql
index 62bf2d3fcb..532de4a48f 100644
--- a/crates/soup/src/outbound/pg_soup_repo/database_row/by_ids.sql
+++ b/crates/soup/src/outbound/pg_soup_repo/database_row/by_ids.sql
@@ -15,11 +15,13 @@ WHERE r.id = ANY($2)
EXISTS (SELECT 1 FROM entity_access ea
WHERE ea.entity_id = row_database.database_id AND ea.entity_type = 'database'
AND ea.source_id IN (SELECT source_id FROM user_source_ids))
- -- Editors of a live form over the database edit its rows.
+ -- Editors of a live form over the database edit its rows; viewers
+ -- read them when the form shares its responses.
OR EXISTS (SELECT 1 FROM forms f
JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'
WHERE f.database_id = row_database.database_id AND f.trashed_at IS NULL
- AND ea.access_level IN ('edit', 'owner')
+ AND (ea.access_level IN ('edit', 'owner')
+ OR (ea.access_level = 'view' AND f.responses_visible))
AND ea.source_id IN (SELECT source_id FROM user_source_ids))
)
ORDER BY r.created_at DESC, r.id DESC
diff --git a/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs b/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs
index 9fe15b3201..01a270a531 100644
--- a/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs
@@ -456,18 +456,24 @@ async fn core_rows_stay_out_of_soup_even_with_a_stray_database_grant(pool: PgPoo
}
/// A form over the CRM's Deals table, granting the stranger `level`.
-async fn grant_the_stranger_a_crm_form(pool: &PgPool, level: &str, trashed: bool) {
+async fn grant_the_stranger_a_crm_form(
+ pool: &PgPool,
+ level: &str,
+ trashed: bool,
+ responses_visible: bool,
+) {
let form_id = Uuid::now_v7();
let stranger = stranger();
sqlx::query!(
r#"
- INSERT INTO forms (id, name, owner_id, database_id, table_id, trashed_at)
- VALUES ($1, 'Deal intake', 'macro|[email protected]', $2, $3, CASE WHEN $4 THEN now() END)
+ INSERT INTO forms (id, name, owner_id, database_id, table_id, trashed_at, responses_visible)
+ VALUES ($1, 'Deal intake', 'macro|[email protected]', $2, $3, CASE WHEN $4 THEN now() END, $5)
"#,
form_id,
CRM,
DEALS,
trashed,
+ responses_visible,
)
.execute(pool)
.await
@@ -515,7 +521,7 @@ async fn stranger_reads(pool: &PgPool) -> (Vec<Uuid>, Vec<Uuid>) {
#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]
async fn a_form_editor_reads_the_rows_of_the_forms_database(pool: PgPool) {
- grant_the_stranger_a_crm_form(&pool, "edit", false).await;
+ grant_the_stranger_a_crm_form(&pool, "edit", false, false).await;
assert_eq!(
stranger_reads(&pool).await,
@@ -525,14 +531,24 @@ async fn a_form_editor_reads_the_rows_of_the_forms_database(pool: PgPool) {
#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]
async fn a_form_respondent_reads_no_rows(pool: PgPool) {
- grant_the_stranger_a_crm_form(&pool, "view", false).await;
+ grant_the_stranger_a_crm_form(&pool, "view", false, false).await;
assert_eq!(stranger_reads(&pool).await, (Vec::new(), Vec::new()));
}
+#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_respondent_of_a_form_that_shares_responses_reads_its_rows(pool: PgPool) {
+ grant_the_stranger_a_crm_form(&pool, "view", false, true).await;
+
+ assert_eq!(
+ stranger_reads(&pool).await,
+ (vec![DEAL_3, DEAL_2, DEAL_1], vec![DEAL_2, DEAL_1])
+ );
+}
+
#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]
async fn a_trashed_form_owner_reads_no_rows(pool: PgPool) {
- grant_the_stranger_a_crm_form(&pool, "owner", true).await;
+ grant_the_stranger_a_crm_form(&pool, "owner", true, false).await;
assert_eq!(stranger_reads(&pool).await, (Vec::new(), Vec::new()));
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs
index 2655575466..d3bf8df239 100644
--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs
@@ -1,6 +1,6 @@
//! Database row clauses for the flat and grouped Soup queries: a row is visible
-//! when its database is untrashed and the viewer holds a grant on it, or edits
-//! a live form over it.
+//! when its database is untrashed and the viewer holds a grant on it, edits a
+//! live form over it, or views a live form over it that shares its responses.
use filter_ast::Expr;
use item_filters::ast::database_row::DatabaseRowLiteral;
@@ -28,14 +28,18 @@ pub(in crate::outbound::pg_soup_repo) fn build_database_row_filter(
.unwrap_or_default()
}
-/// Databases the viewer reaches as an editor of a live form over them.
-const FORM_EDITOR_SEMI_JOIN: &str = r#"row_database.database_id IN (
+/// Databases the viewer reaches through a live form over them: as its editor,
+/// or as its viewer when it shares its responses.
+const FORM_SEMI_JOIN: &str = r#"row_database.database_id IN (
SELECT f.database_id
FROM forms f
JOIN entity_access ea ON ea.entity_id = f.id AND ea.entity_type = 'form'
JOIN user_source_ids us ON us.source_id = ea.source_id
WHERE f.trashed_at IS NULL
- AND ea.access_level IN ('edit', 'owner')
+ AND (
+ ea.access_level IN ('edit', 'owner')
+ OR (ea.access_level = 'view' AND f.responses_visible)
+ )
)"#;
/// Rows are never viewed on their own: `ViewedAt` sorts them last and `ViewedUpdated`
@@ -65,6 +69,6 @@ pub(super) fn database_row_top_clause(
JOIN database_entities row_database ON row_database.database_id = row_table.database_id
WHERE row_database.trashed_at IS NULL AND ({} OR {})"#,
access_semi_join("row_database.database_id::text", "database"),
- FORM_EDITOR_SEMI_JOIN,
+ FORM_SEMI_JOIN,
)
}
diff --git a/deny.toml b/deny.toml
index acc1c7d569..e10761eb79 100644
--- a/deny.toml
+++ b/deny.toml
@@ -232,6 +232,7 @@ deny = [
"documents", # Dev logging only
"email", # Dev logging only
"email_db_client", # Purge phase span tests only
+ "forms", # Anonymous-response span and log leak tests only (dev-dependency)
"genai_telemetry", # GenAI span tests
"graphql_email", # Unavailable-thread warning field and span tests only
"graphql_entity_mutation", # Batch failure span field tests only
diff --git a/docs/agent-guide/forms.md b/docs/agent-guide/forms.md
index adde405f6f..2aa4f48310 100644
--- a/docs/agent-guide/forms.md
+++ b/docs/agent-guide/forms.md
@@ -26,10 +26,16 @@ decides who may respond.
- In a channel composer, `/form` creates a form and opens the builder beside
the channel; its card joins the draft once the builder saves a question.
`/poll` opens the poll dialog (question, at least two options, **Multiple
- answers**, **Show results to respondents**); **Post poll** puts the poll's
- card in the message and sends it. Closing the dialog while it posts sends
- nothing and trashes the poll. With results hidden, respondents answer
- without counts and editors review votes in the Responses tab.
+ answers**, **Show results to respondents**, **Share responses with team**,
+ **Anonymous**); **Post poll** puts the poll's card in the message and sends
+ it. Closing the dialog while it posts sends nothing and trashes the poll.
+ With results hidden, respondents answer without counts and editors review
+ votes in the Responses tab. **Share responses with team** lets everyone who
+ can vote open that table. **Anonymous** makes votes anonymous to everyone
+ in Macro, the poll's owner included: the server keeps who voted apart from
+ what they chose, so each person still votes once, but no vote can be
+ traced to them. An anonymous poll's table has no Respondent column, its
+ vote times keep only the day, and a vote can't be changed.
- Asked for a poll, or for a form for a channel, the Macro agent makes a poll
and posts it as its card in one message (its channel reply), the same card
`/poll` posts.
@@ -138,7 +144,8 @@ submitting are not recorded; answers stay in the browser until Submit.
**Who can respond**: Invited people (sign in, one response each, editable
while open) or Anyone with the link (anonymous; no file questions). The
respond link with Copy, Accepting responses, Close automatically, Show results
-to respondents, Confirmation message, **Branding**, and **Manage access** (the
+to respondents, Share responses with team, Anonymous (locked, with a tooltip
+saying why, once anyone has responded), Confirmation message, **Branding**, and **Manage access** (the
share dialog, which also shows the audience panel). Branding (editors) sets a
logo (**Upload**/**Replace**/**Remove**, shown above the title), a cover image
(a banner across the top of the respond page) and an accent color (color
@@ -146,7 +153,7 @@ swatch or `#rrggbb` field, **Reset** for Macro's accent) that colors the
respond page's buttons and selected answers. Images must be PNG, JPEG,
WebP or GIF uploaded by the person setting them; nothing set keeps Macro's
look, and inline form cards in channels never show branding. Anyone with the link: visitors who aren't signed in respond anonymously;
-people signed in to Macro respond as themselves. Roles: View can respond; Edit can change
+people signed in to Macro respond as themselves. Roles: View can respond; when responses are shared it also reads the linked database (view only). Edit can change
questions and also edits the linked database (its response rows and columns)
through derived access; Owner can also change the audience, close and trash.
Posting a form in a channel grants that channel View, which means it can
@@ -211,10 +218,16 @@ waits for server acceptance. Preview can show real slots, but its booking button
is disabled.
In a message or document, a form card fills in place; a poll card shows one
-bar per option, your vote marked, and "N votes · one vote each". Click an
-option to vote; click another to change it. **Responses** opens the Responses
-tab for editors; respondents get **Results**, the counts as a table in the
-card. In a draft, the card menu's **Convert to Inline Mention** minimizes it;
+bar per option, your vote marked, and "N votes · one vote each". An anonymous
+poll says "Anonymous poll: votes aren't linked to people"; once you vote it
+says "You voted", marks no option, and the vote can't be changed. Its respond
+page shows that you responded without your answers. Click an
+option to vote; click another to change it. Editors, and everyone who can vote
+when responses are shared, get **Results**: each option with the people who
+chose it (avatar and name, yours marked "(you)") and a **Responses table** link
+to the Responses tab. An anonymous poll never names voters, so its editors (and
+its voters, when shared) get **Responses** instead; other respondents get
+neither, since the bars already show the counts. In a draft, the card menu's **Convert to Inline Mention** minimizes it;
in a sent message, **Collapse / Expand** hides the body for you only. Arrow
keys move between poll options; Space or Enter votes. Polls can also be voted
on directly in mobile channels. In New poll, Add option focuses the new
@@ -234,7 +247,9 @@ an empty card.
Use the Responses tab grid, or open the database (`/app/database/<uuid>`) linked
in the form's banner. Each submission is a row; the `Submitted` and
-`Respondent` columns are written by the form. They can be renamed and moved,
+`Respondent` columns are written by the form. An anonymous form never writes
+Respondent (a poll created anonymous has none), stamps Submitted with the day
+only, and writes rows as its owner. They can be renamed and moved,
but their types cannot change and they cannot be deleted while the form exists
(including while it is in the trash). Permanently deleting the form releases
those protections and preserves its database, columns, and answer rows.
@@ -277,8 +292,11 @@ response summaries and hidden booking destinations. Authoring summaries contain
counts, never response rows.
The owner calls `SetFormAccess` with complete audience, open/closed, deadline and
-tally settings. It executes directly without a sharing review card. Channel View
-allows responding. Channel Edit also permits reading and editing the entire
+tally settings. Optional `responsesVisible` lets View holders read response rows;
+optional `anonymous` makes the form anonymous to everyone, its owner included,
+and is refused once anyone has responded. It executes directly without a sharing review card. Channel View
+allows responding. When responses are shared it also grants database View.
+Channel Edit also permits reading and editing the entire
backing database, including columns the form does not ask. Explicit grant deltas
leave other grants unchanged and do not post messages or send invitations.
A passed deadline keeps an otherwise open form closed to responses. Settings and
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
index dcc3e6afe9..89ebcb8de8 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
@@ -1,6 +1,6 @@
# Type Alias: Form
-> **Form** = \{ `audience`: [`Audience`](Audience.md); `branding`: [`FormBranding`](FormBranding.md); `closesAt`: `string` \| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \| `null`; `respondentColumnId`: `string` \| `null`; `status`: [`FormStatus`](FormStatus.md); `submittedColumnId`: `string` \| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \}
+> **Form** = \{ `anonymous`: `boolean`; `audience`: [`Audience`](Audience.md); `branding`: [`FormBranding`](FormBranding.md); `closesAt`: `string` \| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \| `null`; `respondentColumnId`: `string` \| `null`; `responsesVisible`: `boolean`; `status`: [`FormStatus`](FormStatus.md); `submittedColumnId`: `string` \| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \}
A form: a view of one database table whose rows are its responses.
@@ -8,6 +8,7 @@ A form: a view of one database table whose rows are its responses.
| Property | Type | Description |
| ------ | ------ | ------ |
+| <a id="property-anonymous"></a> `anonymous` | `boolean` | Whether nobody, the owner included, can see who gave which response. Who responded is kept apart from the responses, only so nobody responds twice. Fixed once anyone has responded. |
| <a id="property-audience"></a> `audience` | [`Audience`](Audience.md) | Who may respond. |
| <a id="property-branding"></a> `branding` | [`FormBranding`](FormBranding.md) | Its logo, cover image and accent color. |
| <a id="property-closesat"></a> `closesAt` | `string` \| `null` | When it stops taking responses, if it does. |
@@ -20,7 +21,8 @@ A form: a view of one database table whose rows are its responses.
| <a id="property-name"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |
| <a id="property-ownerid"></a> `ownerId` | `string` | Its owner. |
| <a id="property-projectid"></a> `projectId` | `string` \| `null` | The folder it is filed in; `null` at the root. |
-| <a id="property-respondentcolumnid"></a> `respondentColumnId` | `string` \| `null` | The person column each signed-in submission names its respondent in; `null` once deleted. |
+| <a id="property-respondentcolumnid"></a> `respondentColumnId` | `string` \| `null` | The person column each signed-in submission names its respondent in; `null` once deleted, and on a form created anonymous. An anonymous form never writes it. |
+| <a id="property-responsesvisible"></a> `responsesVisible` | `boolean` | Whether people with View may read individual response rows. |
| <a id="property-status"></a> `status` | [`FormStatus`](FormStatus.md) | Whether its owner closed it. |
| <a id="property-submittedcolumnid"></a> `submittedColumnId` | `string` \| `null` | The date column each submission stamps; `null` once deleted. |
| <a id="property-tableid"></a> `tableId` | `string` | The table whose rows are its responses. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormAccess.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormAccess.md
index 5dfd8c1a40..25d91c4e8a 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormAccess.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormAccess.md
@@ -2,5 +2,6 @@
> **FormAccess** = `"view"` \| `"edit"` \| `"owner"`
-The caller's level on a form: view responds, edit changes questions and
-reads responses, owner also sets the audience, closes and trashes it.
+The caller's level on a form: view responds (and reads responses when
+they are shared), edit changes questions and reads responses, owner
+also sets the audience, closes and trashes it.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormErrorCode.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormErrorCode.md
index 11c0055412..ce81a7a207 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormErrorCode.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormErrorCode.md
@@ -1,5 +1,5 @@
# Type Alias: FormErrorCode
-> **FormErrorCode** = `"tableAlreadyHasForm"` \| `"notFound"` \| `"forbidden"` \| `"ownerOnly"` \| `"signInRequired"` \| `"closed"` \| `"tableGone"` \| `"alreadyResponded"` \| `"noResponse"` \| `"unknownQuestion"` \| `"repeatedAnswer"` \| `"missingAnswer"` \| `"invalidAnswer"` \| `"widgetMismatch"` \| `"fileUploadNeedsSignIn"` \| `"invalidLayout"` \| `"invalidName"` \| `"invalidSharing"` \| `"tallyHidden"` \| `"invalidBranding"` \| `"conflict"` \| `"internal"`
+> **FormErrorCode** = `"tableAlreadyHasForm"` \| `"notFound"` \| `"forbidden"` \| `"ownerOnly"` \| `"signInRequired"` \| `"closed"` \| `"tableGone"` \| `"alreadyResponded"` \| `"noResponse"` \| `"anonymousResponseFinal"` \| `"unknownQuestion"` \| `"repeatedAnswer"` \| `"missingAnswer"` \| `"invalidAnswer"` \| `"widgetMismatch"` \| `"fileUploadNeedsSignIn"` \| `"invalidLayout"` \| `"invalidName"` \| `"invalidSharing"` \| `"tallyHidden"` \| `"invalidBranding"` \| `"conflict"` \| `"internal"`
What went wrong with a forms request.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormSource.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormSource.md
index be5a0f77d1..44e840cfe8 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormSource.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/FormSource.md
@@ -1,6 +1,6 @@
# Type Alias: FormSource
-> **FormSource** = \{ `isHiddenInDrive?`: `boolean`; `kind`: `"new"`; \} \| \{ `databaseId`: `string`; `kind`: `"table"`; `tableId`: `string`; \}
+> **FormSource** = \{ `anonymous?`: `boolean`; `isHiddenInDrive?`: `boolean`; `kind`: `"new"`; \} \| \{ `databaseId`: `string`; `kind`: `"table"`; `tableId`: `string`; \}
Where a new form's responses go.
@@ -8,10 +8,11 @@ Where a new form's responses go.
### Type Literal
-\{ `isHiddenInDrive?`: `boolean`; `kind`: `"new"`; \}
+\{ `anonymous?`: `boolean`; `isHiddenInDrive?`: `boolean`; `kind`: `"new"`; \}
| Name | Type | Description |
| ------ | ------ | ------ |
+| `anonymous?` | `boolean` | Make the form anonymous from the start: its table gets no Respondent column. |
| `isHiddenInDrive?` | `boolean` | Keep the form, and the database made for it, out of Drive, as for a channel poll. |
| `kind` | `"new"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MyResponse.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MyResponse.md
index 24a05c8036..ea9c8441c7 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MyResponse.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MyResponse.md
@@ -1,14 +1,24 @@
# Type Alias: MyResponse
-> **MyResponse** = \{ `answers`: [`Answer`](Answer.md)[]; `booking?`: [`UnlockedBooking`](UnlockedBooking.md); `response`: [`FormResponse`](FormResponse.md); \}
+> **MyResponse** = \{ `answers`: [`Answer`](Answer.md)[]; `booking?`: [`UnlockedBooking`](UnlockedBooking.md); `kind`: `"saved"`; `response`: [`FormResponse`](FormResponse.md); \} \| \{ `kind`: `"anonymous"`; \}
-A signed-in respondent's own response, with its answers as the row
-holds them now.
+A signed-in respondent's own response.
-## Properties
+## Union Members
-| Property | Type | Description |
+### Type Literal
+
+\{ `answers`: [`Answer`](Answer.md)[]; `booking?`: [`UnlockedBooking`](UnlockedBooking.md); `kind`: `"saved"`; `response`: [`FormResponse`](FormResponse.md); \}
+
+| Name | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-answers"></a> `answers` | [`Answer`](Answer.md)[] | The row's cells for the form's current questions, the empty ones left out; none when the row is gone. |
-| <a id="property-booking"></a> `booking?` | [`UnlockedBooking`](UnlockedBooking.md) | The form's booking step, while the saved row still passes the form's current required questions and gates. |
-| <a id="property-response"></a> `response` | [`FormResponse`](FormResponse.md) | The ledger entry. |
+| `answers` | [`Answer`](Answer.md)[] | The row's cells for the form's current questions, the empty ones left out; none when the row is gone. |
+| `booking?` | [`UnlockedBooking`](UnlockedBooking.md) | The form's booking step, while the saved row still passes the form's current required questions and gates. |
+| `kind` | `"saved"` | - |
+| `response` | [`FormResponse`](FormResponse.md) | The ledger entry. |
+
+***
+
+### Type Literal
+
+\{ `kind`: `"anonymous"`; \}
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/TallyBucket.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/TallyBucket.md
index 4da35fac8c..4f5d2ce484 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/TallyBucket.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/TallyBucket.md
@@ -1,6 +1,6 @@
# Type Alias: TallyBucket
-> **TallyBucket** = \{ `count`: `number`; `value`: [`TallyValue`](TallyValue.md); \}
+> **TallyBucket** = \{ `count`: `number`; `value`: [`TallyValue`](TallyValue.md); `voters?`: `string`[] \| `null`; \}
How many rows hold one value.
@@ -10,3 +10,4 @@ How many rows hold one value.
| ------ | ------ | ------ |
| <a id="property-count"></a> `count` | `number` | How many rows hold it. |
| <a id="property-value"></a> `value` | [`TallyValue`](TallyValue.md) | The value. |
+| <a id="property-voters"></a> `voters?` | `string`[] \| `null` | Who chose it, as Macro user ids in submission order: present only for the form's editors, or its viewers when it shares its responses, and never when it hides respondents. Rows no signed-in respondent submitted count without a voter. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/UpdateForm.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/UpdateForm.md
index d403392d9a..51308b73a3 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/UpdateForm.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/UpdateForm.md
@@ -1,6 +1,6 @@
# Type Alias: UpdateForm
-> **UpdateForm** = \{ `accentColor?`: `string` \| `null`; `audience?`: [`Audience`](Audience.md); `closesAt?`: `string` \| `null`; `confirmationMessage?`: `string`; `coverFileId?`: `string` \| `null`; `description?`: `string`; `logoFileId?`: `string` \| `null`; `status?`: [`FormStatus`](FormStatus.md); `tallyVisible?`: `boolean`; \}
+> **UpdateForm** = \{ `accentColor?`: `string` \| `null`; `anonymous?`: `boolean`; `audience?`: [`Audience`](Audience.md); `closesAt?`: `string` \| `null`; `confirmationMessage?`: `string`; `coverFileId?`: `string` \| `null`; `description?`: `string`; `logoFileId?`: `string` \| `null`; `responsesVisible?`: `boolean`; `status?`: [`FormStatus`](FormStatus.md); `tallyVisible?`: `boolean`; \}
A change to a form's facts; what is left out stays. The description,
confirmation message and branding take edit, the rest owner. A form is renamed
@@ -11,11 +11,13 @@ through the entity mutation router.
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-accentcolor"></a> `accentColor?` | `string` \| `null` | A new accent color, or `null` for the default. |
+| <a id="property-anonymous"></a> `anonymous?` | `boolean` | Whether nobody can see who gave which response; refused once anyone has responded. |
| <a id="property-audience"></a> `audience?` | [`Audience`](Audience.md) | Who may respond from now on. |
| <a id="property-closesat"></a> `closesAt?` | `string` \| `null` | When it stops taking responses, or `null` for never. |
| <a id="property-confirmationmessage"></a> `confirmationMessage?` | `string` | Its new confirmation message. |
| <a id="property-coverfileid"></a> `coverFileId?` | `string` \| `null` | A new cover image, or `null` to remove it. |
| <a id="property-description"></a> `description?` | `string` | Its new description. |
| <a id="property-logofileid"></a> `logoFileId?` | `string` \| `null` | A new logo, or `null` to remove it. |
+| <a id="property-responsesvisible"></a> `responsesVisible?` | `boolean` | Whether people with View may read individual response rows. |
| <a id="property-status"></a> `status?` | [`FormStatus`](FormStatus.md) | Open or close it. |
| <a id="property-tallyvisible"></a> `tallyVisible?` | `boolean` | Whether respondents may read option tallies. |
diff --git a/packages/sdk-docs/reference/src/entities/forms/form/README.md b/packages/sdk-docs/reference/src/entities/forms/form/README.md
index 038c460eb9..f34aefaf34 100644
--- a/packages/sdk-docs/reference/src/entities/forms/form/README.md
+++ b/packages/sdk-docs/reference/src/entities/forms/form/README.md
@@ -24,3 +24,4 @@
- [FormSectionPlacement](type-aliases/FormSectionPlacement.md)
- [FormSubmissionOutcome](type-aliases/FormSubmissionOutcome.md)
- [MyFormResponse](type-aliases/MyFormResponse.md)
+- [SavedFormResponse](type-aliases/SavedFormResponse.md)
diff --git a/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/MyFormResponse.md b/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/MyFormResponse.md
index 92f810fc2a..61893e793b 100644
--- a/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/MyFormResponse.md
+++ b/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/MyFormResponse.md
@@ -1,18 +1,7 @@
# Type Alias: MyFormResponse
-> **MyFormResponse** = \{ `answers`: [`FormAnswer`](FormAnswer.md)[]; `booking?`: [`FormBookingStep`](FormBookingStep.md); `response`: [`FormResponse`](../../response/classes/FormResponse.md); `row?`: [`DatabaseRow`](../../../databases/row/classes/DatabaseRow.md); `status`: [`ResponseStatus`](../../../../../generated/storage/types.gen/type-aliases/ResponseStatus.md); `stoppedAtSection?`: [`FormSection`](../../section/classes/FormSection.md); `submittedAt`: `string`; `updatedAt`: `string`; \}
+> **MyFormResponse** = [`SavedFormResponse`](SavedFormResponse.md) \| \{ `kind`: `"anonymous"`; \}
-The caller's receipt and current answers, read without access to other responses.
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-answers"></a> `answers` | [`FormAnswer`](FormAnswer.md)[] |
-| <a id="property-booking"></a> `booking?` | [`FormBookingStep`](FormBookingStep.md) |
-| <a id="property-response"></a> `response` | [`FormResponse`](../../response/classes/FormResponse.md) |
-| <a id="property-row"></a> `row?` | [`DatabaseRow`](../../../databases/row/classes/DatabaseRow.md) |
-| <a id="property-status"></a> `status` | [`ResponseStatus`](../../../../../generated/storage/types.gen/type-aliases/ResponseStatus.md) |
-| <a id="property-stoppedatsection"></a> `stoppedAtSection?` | [`FormSection`](../../section/classes/FormSection.md) |
-| <a id="property-submittedat"></a> `submittedAt` | `string` |
-| <a id="property-updatedat"></a> `updatedAt` | `string` |
+The caller's receipt and current answers, read without access to other
+responses. On an anonymous form the caller only learns that they
+responded: nothing links them to their response.
diff --git a/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/SavedFormResponse.md b/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/SavedFormResponse.md
new file mode 100644
index 0000000000..00d6e7b890
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/forms/form/type-aliases/SavedFormResponse.md
@@ -0,0 +1,19 @@
+# Type Alias: SavedFormResponse
+
+> **SavedFormResponse** = \{ `answers`: [`FormAnswer`](FormAnswer.md)[]; `booking?`: [`FormBookingStep`](FormBookingStep.md); `kind`: `"saved"`; `response`: [`FormResponse`](../../response/classes/FormResponse.md); `row?`: [`DatabaseRow`](../../../databases/row/classes/DatabaseRow.md); `status`: [`ResponseStatus`](../../../../../generated/storage/types.gen/type-aliases/ResponseStatus.md); `stoppedAtSection?`: [`FormSection`](../../section/classes/FormSection.md); `submittedAt`: `string`; `updatedAt`: `string`; \}
+
+The caller's saved response to a form that isn't anonymous.
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-answers"></a> `answers` | [`FormAnswer`](FormAnswer.md)[] |
+| <a id="property-booking"></a> `booking?` | [`FormBookingStep`](FormBookingStep.md) |
+| <a id="property-kind"></a> `kind` | `"saved"` |
+| <a id="property-response"></a> `response` | [`FormResponse`](../../response/classes/FormResponse.md) |
+| <a id="property-row"></a> `row?` | [`DatabaseRow`](../../../databases/row/classes/DatabaseRow.md) |
+| <a id="property-status"></a> `status` | [`ResponseStatus`](../../../../../generated/storage/types.gen/type-aliases/ResponseStatus.md) |
+| <a id="property-stoppedatsection"></a> `stoppedAtSection?` | [`FormSection`](../../section/classes/FormSection.md) |
+| <a id="property-submittedat"></a> `submittedAt` | `string` |
+| <a id="property-updatedat"></a> `updatedAt` | `string` |
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index d42b9b9ae5..35bb7f1d5e 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -622,6 +622,12 @@ Re-exports [RoutineTriggerOptions](../entities/routines/routine/type-aliases/Rou
***
+### SavedFormResponse
+
+Re-exports [SavedFormResponse](../entities/forms/form/type-aliases/SavedFormResponse.md)
+
+***
+
### SessionAutoArchive
Re-exports [SessionAutoArchive](../entities/agent-sessions/agent-session/type-aliases/SessionAutoArchive.md)
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 9125c17d3c..babaa9004d 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -7770,6 +7770,12 @@ export type ForeignEntityFilters = {
* A form: a view of one database table whose rows are its responses.
*/
export type Form = {
+ /**
+ * Whether nobody, the owner included, can see who gave which response.
+ * Who responded is kept apart from the responses, only so nobody
+ * responds twice. Fixed once anyone has responded.
+ */
+ anonymous: boolean;
/**
* Who may respond.
*/
@@ -7823,9 +7829,14 @@ export type Form = {
projectId: string | null;
/**
* The person column each signed-in submission names its respondent in;
- * `null` once deleted.
+ * `null` once deleted, and on a form created anonymous. An anonymous
+ * form never writes it.
*/
respondentColumnId: string | null;
+ /**
+ * Whether people with View may read individual response rows.
+ */
+ responsesVisible: boolean;
/**
* Whether its owner closed it.
*/
@@ -7849,8 +7860,9 @@ export type Form = {
};
/**
- * The caller's level on a form: view responds, edit changes questions and
- * reads responses, owner also sets the audience, closes and trashes it.
+ * The caller's level on a form: view responds (and reads responses when
+ * they are shared), edit changes questions and reads responses, owner
+ * also sets the audience, closes and trashes it.
*/
export type FormAccess = 'view' | 'edit' | 'owner';
@@ -7910,7 +7922,7 @@ export type FormDetail = {
/**
* What went wrong with a forms request.
*/
-export type FormErrorCode = 'tableAlreadyHasForm' | 'notFound' | 'forbidden' | 'ownerOnly' | 'signInRequired' | 'closed' | 'tableGone' | 'alreadyResponded' | 'noResponse' | 'unknownQuestion' | 'repeatedAnswer' | 'missingAnswer' | 'invalidAnswer' | 'widgetMismatch' | 'fileUploadNeedsSignIn' | 'invalidLayout' | 'invalidName' | 'invalidSharing' | 'tallyHidden' | 'invalidBranding' | 'conflict' | 'internal';
+export type FormErrorCode = 'tableAlreadyHasForm' | 'notFound' | 'forbidden' | 'ownerOnly' | 'signInRequired' | 'closed' | 'tableGone' | 'alreadyResponded' | 'noResponse' | 'anonymousResponseFinal' | 'unknownQuestion' | 'repeatedAnswer' | 'missingAnswer' | 'invalidAnswer' | 'widgetMismatch' | 'fileUploadNeedsSignIn' | 'invalidLayout' | 'invalidName' | 'invalidSharing' | 'tallyHidden' | 'invalidBranding' | 'conflict' | 'internal';
/**
* Why a forms request was refused or failed.
@@ -8166,6 +8178,11 @@ export type FormSectionDetail = {
* Where a new form's responses go.
*/
export type FormSource = {
+ /**
+ * Make the form anonymous from the start: its table gets no
+ * Respondent column.
+ */
+ anonymous?: boolean;
/**
* Keep the form, and the database made for it, out of Drive, as
* for a channel poll.
@@ -10761,8 +10778,7 @@ export type MessageTopicEvent = {
};
/**
- * A signed-in respondent's own response, with its answers as the row
- * holds them now.
+ * A signed-in respondent's own response.
*/
export type MyResponse = {
/**
@@ -10771,14 +10787,17 @@ export type MyResponse = {
*/
answers: Array<Answer>;
/**
- * The form's booking step, while the saved row still passes the form's
- * current required questions and gates.
+ * The form's booking step, while the saved row still passes the
+ * form's current required questions and gates.
*/
booking?: UnlockedBooking;
+ kind: 'saved';
/**
* The ledger entry.
*/
response: FormResponse;
+} | {
+ kind: 'anonymous';
};
/**
@@ -15099,6 +15118,13 @@ export type TallyBucket = {
* The value.
*/
value: TallyValue;
+ /**
+ * Who chose it, as Macro user ids in submission order: present only
+ * for the form's editors, or its viewers when it shares its responses,
+ * and never when it hides respondents. Rows no signed-in respondent
+ * submitted count without a voter.
+ */
+ voters?: Array<string> | null;
};
/**
@@ -15929,6 +15955,11 @@ export type UpdateForm = {
* A new accent color, or `null` for the default.
*/
accentColor?: string | null;
+ /**
+ * Whether nobody can see who gave which response; refused once anyone
+ * has responded.
+ */
+ anonymous?: boolean;
/**
* Who may respond from now on.
*/
@@ -15953,6 +15984,10 @@ export type UpdateForm = {
* A new logo, or `null` to remove it.
*/
logoFileId?: string | null;
+ /**
+ * Whether people with View may read individual response rows.
+ */
+ responsesVisible?: boolean;
/**
* Open or close it.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 28106aba22..4f3747ac76 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -31851,6 +31851,8 @@
"respondentColumnId",
"audience",
"tallyVisible",
+ "responsesVisible",
+ "anonymous",
"status",
"closesAt",
"confirmationMessage",
@@ -31861,6 +31863,10 @@
"isHiddenInDrive"
],
"properties": {
+ "anonymous": {
+ "type": "boolean",
+ "description": "Whether nobody, the owner included, can see who gave which response.\nWho responded is kept apart from the responses, only so nobody\nresponds twice. Fixed once anyone has responded."
+ },
"audience": {
"$ref": "#/components/schemas/Audience",
"description": "Who may respond."
@@ -31916,7 +31922,11 @@
"respondentColumnId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The person column each signed-in submission names its respondent in;\n`null` once deleted."
+ "description": "The person column each signed-in submission names its respondent in;\n`null` once deleted, and on a form created anonymous. An anonymous\nform never writes it."
+ },
+ "responsesVisible": {
+ "type": "boolean",
+ "description": "Whether people with View may read individual response rows."
},
"status": {
"$ref": "#/components/schemas/FormStatus",
@@ -31945,7 +31955,7 @@
},
"FormAccess": {
"type": "string",
- "description": "The caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it.",
+ "description": "The caller's level on a form: view responds (and reads responses when\nthey are shared), edit changes questions and reads responses, owner\nalso sets the audience, closes and trashes it.",
"enum": ["view", "edit", "owner"]
},
"FormBranding": {
@@ -32030,6 +32040,7 @@
"tableGone",
"alreadyResponded",
"noResponse",
+ "anonymousResponseFinal",
"unknownQuestion",
"repeatedAnswer",
"missingAnswer",
@@ -32481,6 +32492,10 @@
"description": "A new database named like the form, whose one table, \"Responses\",\nstarts with only the form's own columns.",
"required": ["kind"],
"properties": {
+ "anonymous": {
+ "type": "boolean",
+ "description": "Make the form anonymous from the start: its table gets no\nRespondent column."
+ },
"isHiddenInDrive": {
"type": "boolean",
"description": "Keep the form, and the database made for it, out of Drive, as\nfor a channel poll."
@@ -36414,26 +36429,46 @@
"description": "Lifecycle events for the common message service, one per committed fact.\nReactions and typing never reach the topic."
},
"MyResponse": {
- "type": "object",
- "description": "A signed-in respondent's own response, with its answers as the row\nholds them now.",
- "required": ["response", "answers"],
- "properties": {
- "answers": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Answer"
- },
- "description": "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
- },
- "booking": {
- "$ref": "#/components/schemas/UnlockedBooking",
- "description": "The form's booking step, while the saved row still passes the form's\ncurrent required questions and gates."
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Their ledger entry, with its answers as the row holds them now.",
+ "required": ["response", "answers", "kind"],
+ "properties": {
+ "answers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Answer"
+ },
+ "description": "The row's cells for the form's current questions, the empty ones\nleft out; none when the row is gone."
+ },
+ "booking": {
+ "$ref": "#/components/schemas/UnlockedBooking",
+ "description": "The form's booking step, while the saved row still passes the\nform's current required questions and gates."
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["saved"]
+ },
+ "response": {
+ "$ref": "#/components/schemas/FormResponse",
+ "description": "The ledger entry."
+ }
+ }
},
- "response": {
- "$ref": "#/components/schemas/FormResponse",
- "description": "The ledger entry."
+ {
+ "type": "object",
+ "description": "They responded to an anonymous form. Nothing links them to their\nresponse, so there is nothing more to show.",
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["anonymous"]
+ }
+ }
}
- }
+ ],
+ "description": "A signed-in respondent's own response."
},
"NewAttachment": {
"type": "object",
@@ -43584,6 +43619,13 @@
"value": {
"$ref": "#/components/schemas/TallyValue",
"description": "The value."
+ },
+ "voters": {
+ "type": ["array", "null"],
+ "items": {
+ "type": "string"
+ },
+ "description": "Who chose it, as Macro user ids in submission order: present only\nfor the form's editors, or its viewers when it shares its responses,\nand never when it hides respondents. Rows no signed-in respondent\nsubmitted count without a voter."
}
}
},
@@ -44748,6 +44790,10 @@
"description": "A new accent color, or `null` for the default.",
"pattern": "^#[0-9a-fA-F]{6}$"
},
+ "anonymous": {
+ "type": "boolean",
+ "description": "Whether nobody can see who gave which response; refused once anyone\nhas responded."
+ },
"audience": {
"$ref": "#/components/schemas/Audience",
"description": "Who may respond from now on."
@@ -44775,6 +44821,10 @@
"format": "uuid",
"description": "A new logo, or `null` to remove it."
},
+ "responsesVisible": {
+ "type": "boolean",
+ "description": "Whether people with View may read individual response rows."
+ },
"status": {
"$ref": "#/components/schemas/FormStatus",
"description": "Open or close it."
diff --git a/packages/sdk/src/entities/forms/form.ts b/packages/sdk/src/entities/forms/form.ts
index a8c3a94f4a..72efe41710 100644
--- a/packages/sdk/src/entities/forms/form.ts
+++ b/packages/sdk/src/entities/forms/form.ts
@@ -132,8 +132,16 @@ export type FormSubmissionOutcome =
}
| { outcome: 'stopped'; section: FormSection; message: string };
-/** The caller's receipt and current answers, read without access to other responses. */
-export type MyFormResponse = {
+/**
+ * The caller's receipt and current answers, read without access to other
+ * responses. On an anonymous form the caller only learns that they
+ * responded: nothing links them to their response.
+ */
+export type MyFormResponse = SavedFormResponse | { kind: 'anonymous' };
+
+/** The caller's saved response to a form that isn't anonymous. */
+export type SavedFormResponse = {
+ kind: 'saved';
booking?: FormBookingStep;
response: FormResponse;
status: ResponseStatus;
@@ -502,6 +510,7 @@ export class Form extends MacroEntity<FormDetail> {
const mine = unwrap(
await this.client.storage.getMyFormResponse({ path: { id: this.id } }),
);
+ if (mine.kind === 'anonymous') return { kind: 'anonymous' };
const table = await this.table();
const answers = await Promise.all(
mine.answers.map(async (answer): Promise<FormAnswer> => {
@@ -564,6 +573,7 @@ export class Form extends MacroEntity<FormDetail> {
: undefined;
const booking = this.unlockedBooking(mine.booking);
return {
+ kind: 'saved',
...(booking ? { booking } : {}),
response: FormResponse.byId(this, mine.response.id, {
status: mine.response.status,
diff --git a/packages/sdk/src/entities/forms/response.ts b/packages/sdk/src/entities/forms/response.ts
index 6ffd9f0c88..194e294a29 100644
--- a/packages/sdk/src/entities/forms/response.ts
+++ b/packages/sdk/src/entities/forms/response.ts
@@ -26,7 +26,7 @@ export class FormResponse {
private async load(): Promise<ResponseSnapshot> {
const current = await this.form.myResponse();
- if (current.response.id !== this.id)
+ if (current.kind === 'anonymous' || current.response.id !== this.id)
throw new MacroNotFoundError(
`response ${this.id} is not your current response`,
);
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index e8fb689d03..ea2b437b47 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -73,6 +73,7 @@ export {
type FormSectionPlacement,
type FormSubmissionOutcome,
type MyFormResponse,
+ type SavedFormResponse,
} from './entities/forms/form';
export { FormOption, FormQuestion } from './entities/forms/question';
export { FormResponse } from './entities/forms/response';
diff --git a/packages/sdk/tests/forms.test.ts b/packages/sdk/tests/forms.test.ts
index 29763a4323..d2e4d4077a 100644
--- a/packages/sdk/tests/forms.test.ts
+++ b/packages/sdk/tests/forms.test.ts
@@ -25,6 +25,8 @@ const registration = {
respondentColumnId: null,
audience: 'members',
tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
status: 'open',
closesAt: null,
confirmationMessage: 'See you there!',
@@ -311,6 +313,7 @@ describe('Forms', () => {
paths.push(path);
if (path.endsWith('/responses/mine'))
return Response.json({
+ kind: 'saved',
response: {
id: responseId,
formId,
@@ -332,6 +335,7 @@ describe('Forms', () => {
const macro = new Macro({ token: 'user-token', hosts: { storage: host } });
const form = macro.forms.byId(formId);
const mine = await form.myResponse();
+ if (mine.kind !== 'saved') throw new Error('a saved response');
expect(mine.response.form).toBe(form);
expect(mine.response.id).toBe(responseId);
expect(mine.row?.id).toBe(rowId);
@@ -361,6 +365,22 @@ describe('Forms', () => {
]);
});
+ test('reads an anonymous form response as only having responded', async () => {
+ const paths: string[] = [];
+ globalThis.fetch = (async (input) => {
+ const request = input instanceof Request ? input : new Request(input);
+ const path = new URL(request.url).pathname;
+ paths.push(path);
+ if (path.endsWith('/responses/mine'))
+ return Response.json({ kind: 'anonymous' });
+ return Response.json(registration);
+ }) as typeof fetch;
+ const macro = new Macro({ token: 'user-token', hosts: { storage: host } });
+ const form = macro.forms.byId(formId);
+ expect(await form.myResponse()).toEqual({ kind: 'anonymous' });
+ expect(paths).toEqual([`/forms/${formId}/responses/mine`]);
+ });
+
test('edits responses with PUT and returns a stopped section without reading rows', async () => {
const writes: { method: string; path: string; body: unknown }[] = [];
globalThis.fetch = (async (input) => {