@ai-matrx/records 0.96.13 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/{client-D7bvxEZW.d.ts → client-MVuEbxKl.d.ts} +6 -0
  3. package/dist/{client-DKgbZUNt.d.cts → client-pFV_8AhM.d.cts} +6 -0
  4. package/dist/core/index.cjs +637 -3
  5. package/dist/core/index.cjs.map +1 -1
  6. package/dist/core/index.d.cts +3 -2
  7. package/dist/core/index.d.ts +3 -2
  8. package/dist/core/index.js +637 -3
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/data/index.cjs +634 -0
  11. package/dist/data/index.cjs.map +1 -1
  12. package/dist/data/index.d.cts +2 -1
  13. package/dist/data/index.d.ts +2 -1
  14. package/dist/data/index.js +634 -0
  15. package/dist/data/index.js.map +1 -1
  16. package/dist/{declareTable-VoNRi_j_.d.cts → declareTable-Bekj6UwK.d.cts} +1 -1
  17. package/dist/{declareTable-D_CiMnXM.d.ts → declareTable-C7zVyyLA.d.ts} +1 -1
  18. package/dist/doors-C43_5HjC.d.ts +487 -0
  19. package/dist/doors-CJPHsohF.d.cts +487 -0
  20. package/dist/questions/index.d.cts +2 -1
  21. package/dist/questions/index.d.ts +2 -1
  22. package/dist/react/index.cjs +637 -3
  23. package/dist/react/index.cjs.map +1 -1
  24. package/dist/react/index.d.cts +338 -5
  25. package/dist/react/index.d.ts +338 -5
  26. package/dist/react/index.js +637 -3
  27. package/dist/react/index.js.map +1 -1
  28. package/dist/scopes/index.cjs +729 -0
  29. package/dist/scopes/index.cjs.map +1 -0
  30. package/dist/scopes/index.d.cts +33 -0
  31. package/dist/scopes/index.d.ts +33 -0
  32. package/dist/scopes/index.js +706 -0
  33. package/dist/scopes/index.js.map +1 -0
  34. package/dist/setup/index.cjs +634 -0
  35. package/dist/setup/index.cjs.map +1 -1
  36. package/dist/setup/index.d.cts +2 -1
  37. package/dist/setup/index.d.ts +2 -1
  38. package/dist/setup/index.js +634 -0
  39. package/dist/setup/index.js.map +1 -1
  40. package/dist/typed-table/index.cjs +634 -0
  41. package/dist/typed-table/index.cjs.map +1 -1
  42. package/dist/typed-table/index.d.cts +3 -2
  43. package/dist/typed-table/index.d.ts +3 -2
  44. package/dist/typed-table/index.js +634 -0
  45. package/dist/typed-table/index.js.map +1 -1
  46. package/dist/views/index.d.cts +2 -1
  47. package/dist/views/index.d.ts +2 -1
  48. package/package.json +14 -4
@@ -5483,6 +5483,639 @@ function onTableStructureChanged(listener) {
5483
5483
  return () => tableListeners.delete(listener);
5484
5484
  }
5485
5485
 
5486
+ // src/scopes/codec.ts
5487
+ var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
5488
+ var strOrNull = (v) => typeof v === "string" ? v : null;
5489
+ var num = (v, fallback = 0) => {
5490
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
5491
+ return Number.isFinite(n) ? n : fallback;
5492
+ };
5493
+ function scopeTypeFromStore(row) {
5494
+ const singular = row.label_singular ?? row.name ?? "";
5495
+ return {
5496
+ id: row.id,
5497
+ organization_id: row.organization_id,
5498
+ label_singular: singular,
5499
+ label_plural: row.label_plural ?? singular,
5500
+ icon: row.icon ?? "folder",
5501
+ color: row.color ?? "",
5502
+ slug: row.slug ?? null,
5503
+ description: row.description ?? "",
5504
+ sort_order: num(row.sort_order),
5505
+ max_assignments_per_entity: row.max_assignments_per_entity ?? null,
5506
+ default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],
5507
+ created_by: row.created_by ?? null,
5508
+ created_at: row.created_at ?? "",
5509
+ updated_at: row.updated_at ?? ""
5510
+ };
5511
+ }
5512
+ function scopeTypeLabelFromStore(t) {
5513
+ const singular = t.label_singular ?? t.name ?? "";
5514
+ return { id: t.id, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };
5515
+ }
5516
+ function settingFromStore(value) {
5517
+ if (!Array.isArray(value)) return value;
5518
+ return value.map((el) => {
5519
+ if (typeof el !== "string") return el;
5520
+ const t = el.trim();
5521
+ if (!(t.startsWith("{") && t.endsWith("}")) && !(t.startsWith("[") && t.endsWith("]"))) return el;
5522
+ try {
5523
+ return JSON.parse(t);
5524
+ } catch {
5525
+ return el;
5526
+ }
5527
+ });
5528
+ }
5529
+ function scopeFromStore(row) {
5530
+ const settings = {};
5531
+ for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);
5532
+ return {
5533
+ id: row.id,
5534
+ scope_type_id: row.scope_type_id,
5535
+ organization_id: row.organization_id,
5536
+ name: row.name ?? "",
5537
+ description: row.description ?? "",
5538
+ slug: row.slug ?? null,
5539
+ sort_order: num(row.sort_order),
5540
+ parent_scope_id: row.parent_scope_id ?? null,
5541
+ settings,
5542
+ created_by: row.created_by ?? null,
5543
+ created_at: row.created_at ?? "",
5544
+ updated_at: row.updated_at ?? ""
5545
+ };
5546
+ }
5547
+ function scopeWithTypeFromStore(row) {
5548
+ return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };
5549
+ }
5550
+ function archivedScopeTypeFromStore(row) {
5551
+ const singular = row.label_singular ?? "";
5552
+ return {
5553
+ id: row.id,
5554
+ organization_id: row.organization_id,
5555
+ label_singular: singular,
5556
+ label_plural: row.label_plural ?? singular,
5557
+ icon: row.icon ?? "folder",
5558
+ color: row.color ?? "",
5559
+ archived_at: row.deleted_at ?? "",
5560
+ created_by: row.created_by ?? null,
5561
+ archived_scope_count: row.archived_scope_count ?? 0
5562
+ };
5563
+ }
5564
+ var FILE_KERNEL_ID = "11111111-0000-4000-8000-000000000006";
5565
+ var KINDS = /* @__PURE__ */ new Set([
5566
+ "string",
5567
+ "markdown",
5568
+ "email",
5569
+ "url",
5570
+ "phone",
5571
+ "color",
5572
+ "number",
5573
+ "percent",
5574
+ "currency",
5575
+ "boolean",
5576
+ "date",
5577
+ "datetime",
5578
+ "time",
5579
+ "object",
5580
+ "array",
5581
+ "reference",
5582
+ "document"
5583
+ ]);
5584
+ function contextFieldKind(doc, carried) {
5585
+ if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type;
5586
+ const behavior = String(doc.type ?? "text");
5587
+ const fmt = doc.format ? String(doc.format) : "";
5588
+ const shown = doc.display_format && typeof doc.display_format === "object" ? String(doc.display_format.id ?? "") : "";
5589
+ const kind = String(doc.config?.kind ?? "");
5590
+ const multi = Boolean(doc.multi);
5591
+ if (behavior === "boolean") return "boolean";
5592
+ if (behavior === "relation") return doc.relation_target === FILE_KERNEL_ID && !multi ? "document" : "reference";
5593
+ if (behavior === "range") {
5594
+ if (kind === "date") return "date";
5595
+ if (kind === "datetime") return "datetime";
5596
+ if (fmt === "percent" || fmt === "currency") return fmt;
5597
+ return "number";
5598
+ }
5599
+ if (behavior === "text") {
5600
+ if (multi) return "array";
5601
+ if (fmt === "json") return "object";
5602
+ for (const word of [fmt, shown]) {
5603
+ if (word === "time" || word === "email" || word === "url" || word === "phone" || word === "color" || word === "markdown") return word;
5604
+ }
5605
+ }
5606
+ return "string";
5607
+ }
5608
+ var POLICIES = /* @__PURE__ */ new Set(["include", "on_request", "exclude"]);
5609
+ var SENSITIVITIES = /* @__PURE__ */ new Set(["public", "internal", "confidential", "restricted"]);
5610
+ function contextFieldFromStore(row) {
5611
+ const d = row.data ?? {};
5612
+ const key = str(d.key);
5613
+ const policy = str(d.context_policy, "include");
5614
+ const sensitivity = str(d.sensitivity, "internal");
5615
+ return {
5616
+ id: row.id,
5617
+ scope_type_id: row.scope_type_id,
5618
+ organization_id: row.organization_id,
5619
+ key,
5620
+ label: str(d.label, key),
5621
+ description: str(d.description),
5622
+ kind: contextFieldKind(d, row.carried),
5623
+ type: str(d.type, "text"),
5624
+ multi: Boolean(d.multi),
5625
+ format: strOrNull(d.format),
5626
+ config: d.config ?? {},
5627
+ relation_target: strOrNull(d.relation_target),
5628
+ // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).
5629
+ sort: Math.max(0, num(d.sort) - 2),
5630
+ context_policy: POLICIES.has(policy) ? policy : "include",
5631
+ sensitivity: SENSITIVITIES.has(sensitivity) ? sensitivity : "internal",
5632
+ source: str(d.source, "manual"),
5633
+ status: str(d.status, "active"),
5634
+ status_note: strOrNull(d.status_note),
5635
+ category: strOrNull(d.category),
5636
+ tags: Array.isArray(d.tags) ? d.tags : [],
5637
+ max_items: typeof d.max_items === "number" ? d.max_items : 1,
5638
+ custom_component: d.custom_component ?? null,
5639
+ reference_source: d.reference_source ?? null,
5640
+ allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,
5641
+ allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,
5642
+ review_interval_days: typeof d.review_interval_days === "number" ? d.review_interval_days : null,
5643
+ depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],
5644
+ version: num(row.version, 1),
5645
+ created_by: row.created_by ?? null,
5646
+ created_at: row.created_at ?? "",
5647
+ updated_at: row.updated_at ?? ""
5648
+ };
5649
+ }
5650
+ var POLICY_TO_DOOR = { include: "always", on_request: "on_demand", exclude: "never" };
5651
+ var SENSITIVITY_TO_DOOR = {
5652
+ public: "public",
5653
+ internal: "internal",
5654
+ confidential: "restricted",
5655
+ restricted: "privileged"
5656
+ };
5657
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5658
+ function referencesOf(row) {
5659
+ const v = row.value;
5660
+ const list = Array.isArray(v) ? v : v == null ? [] : [v];
5661
+ const labels = row.labels ?? {};
5662
+ const files = row.files ?? {};
5663
+ const toFile = row.field?.relation_target === FILE_KERNEL_ID;
5664
+ const out = [];
5665
+ for (const el of list) {
5666
+ let ref = null;
5667
+ if (typeof el === "string" && UUID.test(el)) ref = { id: el, type: toFile ? "file" : "scope" };
5668
+ else if (el && typeof el === "object" && typeof el.id === "string") {
5669
+ const token = String(el.token ?? "");
5670
+ const own = el.label;
5671
+ ref = { id: el.id, type: token === "dataset" ? "table" : token || (toFile ? "file" : "scope") };
5672
+ if (typeof own === "string" && own) ref.label = own;
5673
+ }
5674
+ if (!ref) continue;
5675
+ const label = labels[ref.id];
5676
+ if (label) ref.label = label;
5677
+ const fileId = files[ref.id];
5678
+ if (fileId) ref.file_id = fileId;
5679
+ out.push(ref);
5680
+ }
5681
+ return out;
5682
+ }
5683
+ function contextValueFromStore(row) {
5684
+ const kind = contextFieldKind(row.field ?? {}, row.field?.carried);
5685
+ const carriedText = Boolean(row.field?.carried?.as_text);
5686
+ const isRef = !carriedText && (kind === "reference" || kind === "document");
5687
+ return {
5688
+ scope_id: row.scope_id,
5689
+ field_id: row.context_item_id,
5690
+ key: row.key,
5691
+ kind,
5692
+ value: row.value ?? null,
5693
+ references: isRef ? referencesOf(row) : [],
5694
+ version: num(row.version, 1),
5695
+ set_at: row.set_at ?? null,
5696
+ source_type: row.source_type ?? null,
5697
+ authored_by: row.authored_by ?? null,
5698
+ whole_value: row.whole_value ?? null,
5699
+ incomplete: null
5700
+ };
5701
+ }
5702
+ async function sha256Hex(text2) {
5703
+ const subtle = globalThis.crypto?.subtle;
5704
+ if (!subtle) return null;
5705
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text2));
5706
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
5707
+ }
5708
+ async function completeWholeValues(values, read) {
5709
+ const texts = /* @__PURE__ */ new Map();
5710
+ await Promise.all(
5711
+ values.map(async (cell) => {
5712
+ const w = cell.whole_value;
5713
+ if (!w || w.in_value || typeof cell.value !== "string") return;
5714
+ const head = cell.value;
5715
+ const chars = typeof w.chars === "number" ? w.chars : null;
5716
+ const incomplete = (fileId, why) => {
5717
+ cell.incomplete = { head, chars, file_id: fileId, why };
5718
+ };
5719
+ if (!w.file_id) return incomplete(null, "The rest of this text is still being saved.");
5720
+ if (!read) return incomplete(w.file_id, "This place cannot open the file that holds the whole text.");
5721
+ if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));
5722
+ try {
5723
+ const text2 = await texts.get(w.file_id);
5724
+ if (chars !== null && [...text2].length !== chars) {
5725
+ return incomplete(w.file_id, `The file holds ${[...text2].length} characters, not ${chars}.`);
5726
+ }
5727
+ if (w.sha256) {
5728
+ const sha = await sha256Hex(text2);
5729
+ if (sha === null) return incomplete(w.file_id, "This browser cannot check the file.");
5730
+ if (sha !== w.sha256) return incomplete(w.file_id, "The file's content is not the text the cell points at.");
5731
+ }
5732
+ cell.value = text2;
5733
+ } catch (thrown) {
5734
+ incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));
5735
+ }
5736
+ })
5737
+ );
5738
+ }
5739
+ function definedOnly(fields) {
5740
+ const out = {};
5741
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) out[k] = v;
5742
+ return out;
5743
+ }
5744
+ function fieldSpecForDoor(spec) {
5745
+ return definedOnly({
5746
+ key: spec.key,
5747
+ display_name: spec.label,
5748
+ value_type: spec.kind,
5749
+ description: spec.description,
5750
+ category: spec.category,
5751
+ fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : void 0,
5752
+ sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : void 0,
5753
+ tags: spec.tags,
5754
+ sort_order: spec.sort,
5755
+ status: spec.status,
5756
+ status_note: spec.status_note,
5757
+ custom_component: spec.custom_component,
5758
+ review_interval_days: spec.review_interval_days,
5759
+ allowed_reference_types: spec.allowed_reference_types,
5760
+ max_items: spec.max_items,
5761
+ allowed_scope_type_ids: spec.allowed_scope_type_ids,
5762
+ reference_source: spec.reference_source
5763
+ });
5764
+ }
5765
+ function referenceFence(references) {
5766
+ const kinds = [...new Set(references.map((r) => r.type))];
5767
+ const type = kinds.length === 1 ? kinds[0] : "mixed";
5768
+ const items = references.map((r) => {
5769
+ if (r.type === "file" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };
5770
+ const item2 = { id: r.id };
5771
+ if (r.label) item2.label = r.label;
5772
+ if (kinds.length > 1) item2.type = r.type;
5773
+ return item2;
5774
+ });
5775
+ return "```matrx\n" + JSON.stringify({ matrx_version: 1, kind: "reference", type, items }, null, 2) + "\n```";
5776
+ }
5777
+ function valuePayloadForDoor(write) {
5778
+ const base = definedOnly({
5779
+ scope_id: write.scope_id,
5780
+ context_item_id: write.field_id,
5781
+ source_type: write.source_type,
5782
+ change_summary: write.change_summary
5783
+ });
5784
+ const v = write.value;
5785
+ if (write.kind === "reference" || write.kind === "document") {
5786
+ if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };
5787
+ if (write.kind === "document" && typeof v === "string") return { ...base, value_document_url: v || null };
5788
+ return { ...base, value_text: typeof v === "string" ? v || null : null };
5789
+ }
5790
+ if (v === null || v === void 0 || v === "") {
5791
+ return { ...base, value_text: null };
5792
+ }
5793
+ switch (write.kind) {
5794
+ case "number":
5795
+ case "percent":
5796
+ return typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
5797
+ case "currency":
5798
+ return typeof v === "object" ? { ...base, value_json: v } : typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
5799
+ case "boolean":
5800
+ return typeof v === "boolean" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };
5801
+ case "date":
5802
+ return { ...base, value_date: String(v) };
5803
+ case "datetime":
5804
+ return { ...base, value_timestamp: String(v) };
5805
+ case "time":
5806
+ return { ...base, value_time: String(v) };
5807
+ case "object":
5808
+ case "array":
5809
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
5810
+ default:
5811
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
5812
+ }
5813
+ }
5814
+
5815
+ // src/scopes/rules.ts
5816
+ function toSlug(name) {
5817
+ return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
5818
+ }
5819
+ function isValidSlug(s) {
5820
+ return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);
5821
+ }
5822
+ var RESERVED_SCOPE_SLUGS = /* @__PURE__ */ new Set(["context-items", "scopes", "edit", "manage", "new", "settings"]);
5823
+ function isReservedSlug(s) {
5824
+ return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, "-"));
5825
+ }
5826
+ function resolveSlug(supplied, fallbackName) {
5827
+ const slug = supplied?.trim() || toSlug(fallbackName);
5828
+ if (!slug || !isValidSlug(slug)) {
5829
+ return {
5830
+ ok: false,
5831
+ error: { code: "invalid_argument", message: "Use letters, numbers and single hyphens for the short name." }
5832
+ };
5833
+ }
5834
+ if (isReservedSlug(slug)) {
5835
+ return { ok: false, error: { code: "invalid_argument", message: `"${slug}" is a page name here. Pick another short name.` } };
5836
+ }
5837
+ return { ok: true, data: slug };
5838
+ }
5839
+
5840
+ // src/scopes/doors.ts
5841
+ var SCOPES_PER_CALL = 500;
5842
+ var SCOPE_TYPES_PER_FIELDS_CALL = 100;
5843
+ var SCOPES_PER_VALUES_CALL = 200;
5844
+ var TYPE_SCOPES_PAGE = 200;
5845
+ var ARCHIVED_SCOPES_PAGE = 200;
5846
+ var uniq = (ids) => [...new Set(ids.filter(Boolean))];
5847
+ async function inBatches(ids, size, call) {
5848
+ const unique = uniq(ids);
5849
+ const batches = [];
5850
+ for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));
5851
+ const answers = await Promise.all(batches.map(call));
5852
+ const out = [];
5853
+ for (const a of answers) {
5854
+ if (!a.ok) return a;
5855
+ out.push(...a.data ?? []);
5856
+ }
5857
+ return { ok: true, data: out };
5858
+ }
5859
+ function noRow(door) {
5860
+ return { ok: false, error: { code: "internal", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };
5861
+ }
5862
+ var VALUE_DOOR_CODES = {
5863
+ unauthorized: "door",
5864
+ forbidden: "door",
5865
+ forbidden_org: "door",
5866
+ not_found: "not_found",
5867
+ invalid_argument: "invalid_argument",
5868
+ conflict: "stale_write",
5869
+ unavailable: "not_supported"
5870
+ };
5871
+ function createScopeDoors(call) {
5872
+ async function write(door, args) {
5873
+ const res = await call(door, args, `scopes.${door}`);
5874
+ if (!res.ok) return res;
5875
+ const row = res.data?.row;
5876
+ if (!row || typeof row !== "object") return noRow(door);
5877
+ return { ok: true, data: row };
5878
+ }
5879
+ async function archiveOrRestore(door, args, id) {
5880
+ const res = await call(door, args, `scopes.${door}`);
5881
+ return res.ok ? { ok: true, data: { id } } : res;
5882
+ }
5883
+ async function fieldById(scopeTypeId, fieldId, door) {
5884
+ const fields = await doors.fields([scopeTypeId]);
5885
+ if (!fields.ok) return fields;
5886
+ const field = fields.data.find((f) => f.id === fieldId);
5887
+ return field ? { ok: true, data: field } : noRow(door);
5888
+ }
5889
+ const doors = {
5890
+ async tree(organizationIds) {
5891
+ const ids = uniq(organizationIds);
5892
+ if (ids.length === 0) return { ok: true, data: [] };
5893
+ const res = await call("context_tree", { p_organization_ids: ids }, "scopes.tree");
5894
+ if (!res.ok) return res;
5895
+ const byType = /* @__PURE__ */ new Map();
5896
+ for (const s of res.data?.scopes ?? []) {
5897
+ const scope = scopeFromStore(s);
5898
+ const list = byType.get(scope.scope_type_id) ?? [];
5899
+ list.push(scope);
5900
+ byType.set(scope.scope_type_id, list);
5901
+ }
5902
+ return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };
5903
+ },
5904
+ async types(organizationIds, options) {
5905
+ const withCounts = options?.withCounts ?? true;
5906
+ const ids = uniq(organizationIds);
5907
+ if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };
5908
+ const res = await call("context_tree_types", { p_organization_ids: ids, p_with_counts: withCounts }, "scopes.types");
5909
+ if (!res.ok) return res;
5910
+ const rows2 = res.data?.types ?? [];
5911
+ const counts = withCounts ? {} : null;
5912
+ if (counts) for (const r of rows2) counts[r.id] = Number(r.scope_count ?? 0);
5913
+ return { ok: true, data: { types: rows2.map(scopeTypeFromStore), counts } };
5914
+ },
5915
+ async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {
5916
+ const res = await call(
5917
+ "context_tree_type_scopes",
5918
+ { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },
5919
+ "scopes.typeScopesPage"
5920
+ );
5921
+ if (!res.ok) return res;
5922
+ return {
5923
+ ok: true,
5924
+ data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null }
5925
+ };
5926
+ },
5927
+ async search(organizationIds, query, limit = 100) {
5928
+ const ids = uniq(organizationIds);
5929
+ const q = query.trim();
5930
+ if (ids.length === 0 || q === "") return { ok: true, data: { scopes: [], total: 0 } };
5931
+ const res = await call(
5932
+ "context_tree_search",
5933
+ { p_organization_ids: ids, p_query: q, p_limit: limit },
5934
+ "scopes.search"
5935
+ );
5936
+ if (!res.ok) return res;
5937
+ return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };
5938
+ },
5939
+ async scopes(ids) {
5940
+ const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call("context_scopes", { p_scope_ids: batch }, "scopes.scopes"));
5941
+ return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;
5942
+ },
5943
+ async fields(scopeTypeIds) {
5944
+ const res = await inBatches(
5945
+ scopeTypeIds,
5946
+ SCOPE_TYPES_PER_FIELDS_CALL,
5947
+ (batch) => call("context_items", { p_scope_type_ids: batch }, "scopes.fields")
5948
+ );
5949
+ return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;
5950
+ },
5951
+ async values(scopeIds, options) {
5952
+ const res = await inBatches(
5953
+ scopeIds,
5954
+ SCOPES_PER_VALUES_CALL,
5955
+ (batch) => call("context_values", { p_scope_ids: batch }, "scopes.values")
5956
+ );
5957
+ if (!res.ok) return res;
5958
+ const cells = res.data.map(contextValueFromStore);
5959
+ await completeWholeValues(cells, options?.readFileText ?? null);
5960
+ return { ok: true, data: cells };
5961
+ },
5962
+ async archivedTypes(organizationId) {
5963
+ const res = await call("context_archived_types", { p_organization_id: organizationId }, "scopes.archivedTypes");
5964
+ return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;
5965
+ },
5966
+ async archivedScopesOfType(organizationId, scopeTypeId, wanted) {
5967
+ const out = [];
5968
+ for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {
5969
+ const res = await call(
5970
+ "read_records_archived",
5971
+ { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: "org", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },
5972
+ "scopes.archivedScopesOfType"
5973
+ );
5974
+ if (!res.ok) return res;
5975
+ const rows2 = res.data ?? [];
5976
+ for (const r of rows2) {
5977
+ if (!wanted.has(r.id)) continue;
5978
+ out.push({
5979
+ id: r.id,
5980
+ name: typeof r.document?.name === "string" ? r.document.name : null,
5981
+ slug: typeof r.document?.slug === "string" ? r.document.slug : null,
5982
+ archived_at: r.archived_at ?? null
5983
+ });
5984
+ }
5985
+ if (rows2.length < ARCHIVED_SCOPES_PAGE) break;
5986
+ }
5987
+ return { ok: true, data: out };
5988
+ },
5989
+ async systemItems() {
5990
+ const res = await call("context_system_items", {}, "scopes.systemItems");
5991
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
5992
+ },
5993
+ async templates() {
5994
+ const res = await call("context_templates", {}, "scopes.templates");
5995
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
5996
+ },
5997
+ async createType(organizationId, spec) {
5998
+ const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || "");
5999
+ if (!slug.ok) return slug;
6000
+ const res = await write("context_type_write", {
6001
+ p_organization_id: organizationId,
6002
+ p_type_id: null,
6003
+ p_spec: definedOnly({
6004
+ label_singular: spec.label_singular,
6005
+ label_plural: spec.label_plural,
6006
+ icon: spec.icon ?? "folder",
6007
+ description: spec.description ?? "",
6008
+ sort_order: spec.sort_order ?? 0,
6009
+ max_assignments: spec.max_assignments_per_entity ?? void 0,
6010
+ default_variable_keys: spec.default_variable_keys ?? [],
6011
+ color: spec.color,
6012
+ slug: slug.data
6013
+ })
6014
+ });
6015
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
6016
+ },
6017
+ async updateType(typeId, spec) {
6018
+ let slug;
6019
+ if (spec.slug !== void 0) {
6020
+ const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? "");
6021
+ if (!resolved.ok) return resolved;
6022
+ slug = resolved.data;
6023
+ }
6024
+ const res = await write("context_type_write", {
6025
+ p_organization_id: null,
6026
+ p_type_id: typeId,
6027
+ p_spec: definedOnly({
6028
+ label_singular: spec.label_singular,
6029
+ label_plural: spec.label_plural,
6030
+ icon: spec.icon,
6031
+ description: spec.description,
6032
+ sort_order: spec.sort_order,
6033
+ max_assignments: spec.max_assignments_per_entity,
6034
+ color: spec.color,
6035
+ slug
6036
+ })
6037
+ });
6038
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
6039
+ },
6040
+ archiveType: (typeId) => archiveOrRestore("context_type_archive", { p_type_id: typeId }, typeId),
6041
+ restoreType: (typeId) => archiveOrRestore("context_type_restore", { p_type_id: typeId }, typeId),
6042
+ async createScope(organizationId, typeId, spec) {
6043
+ const slug = resolveSlug(spec.slug, spec.name ?? "");
6044
+ if (!slug.ok) return slug;
6045
+ const res = await write("context_scope_write", {
6046
+ p_organization_id: organizationId,
6047
+ p_scope_id: null,
6048
+ p_type_id: typeId,
6049
+ p_spec: definedOnly({
6050
+ name: spec.name,
6051
+ parent_scope_id: spec.parent_scope_id,
6052
+ description: spec.description ?? "",
6053
+ settings: spec.settings ?? {},
6054
+ slug: slug.data,
6055
+ sort_order: spec.sort_order
6056
+ })
6057
+ });
6058
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
6059
+ },
6060
+ async updateScope(scopeId, spec) {
6061
+ let slug;
6062
+ if (spec.slug !== void 0) {
6063
+ const resolved = resolveSlug(spec.slug, spec.name ?? "");
6064
+ if (!resolved.ok) return resolved;
6065
+ slug = resolved.data;
6066
+ }
6067
+ const res = await write("context_scope_write", {
6068
+ p_organization_id: null,
6069
+ p_scope_id: scopeId,
6070
+ p_type_id: null,
6071
+ p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order })
6072
+ });
6073
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
6074
+ },
6075
+ archiveScope: (scopeId) => archiveOrRestore("context_scope_archive", { p_scope_id: scopeId }, scopeId),
6076
+ restoreScope: (scopeId) => archiveOrRestore("context_scope_restore", { p_scope_id: scopeId }, scopeId),
6077
+ async createField(scopeTypeId, spec) {
6078
+ const res = await write("context_item_write", {
6079
+ p_item_id: null,
6080
+ p_scope_type_id: scopeTypeId,
6081
+ p_spec: fieldSpecForDoor({ kind: "string", description: "", context_policy: "on_request", sensitivity: "internal", tags: [], ...spec })
6082
+ });
6083
+ if (!res.ok) return res;
6084
+ return fieldById(scopeTypeId, String(res.data.id), "context_item_write");
6085
+ },
6086
+ async updateField(fieldId, scopeTypeId, spec) {
6087
+ const res = await write("context_item_write", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });
6088
+ if (!res.ok) return res;
6089
+ return fieldById(scopeTypeId, fieldId, "context_item_write");
6090
+ },
6091
+ archiveField: (fieldId) => archiveOrRestore("context_item_archive", { p_item_id: fieldId }, fieldId),
6092
+ restoreField: (fieldId) => archiveOrRestore("context_item_restore", { p_item_id: fieldId }, fieldId),
6093
+ async writeValue(cell) {
6094
+ const res = await call(
6095
+ "context_value_write",
6096
+ { p_payload: { source_type: "ai_enriched", ...valuePayloadForDoor(cell) } },
6097
+ "scopes.writeValue"
6098
+ );
6099
+ if (!res.ok) return res;
6100
+ const envelope = res.data ?? {};
6101
+ if (!envelope.ok) {
6102
+ const code = VALUE_DOOR_CODES[envelope.error?.code ?? ""] ?? "internal";
6103
+ return { ok: false, error: { code, message: envelope.error?.message ?? "The value was not saved." } };
6104
+ }
6105
+ return {
6106
+ ok: true,
6107
+ data: {
6108
+ scope_id: cell.scope_id,
6109
+ field_id: cell.field_id,
6110
+ version: Number(envelope.data?.version ?? 1),
6111
+ source_type: String(envelope.data?.source_type ?? cell.source_type ?? "ai_enriched")
6112
+ }
6113
+ };
6114
+ }
6115
+ };
6116
+ return doors;
6117
+ }
6118
+
5486
6119
  // src/core/keysetCursor.ts
5487
6120
  function utf8ToBinary(text2) {
5488
6121
  let out = "";
@@ -6779,6 +7412,7 @@ function createRecordsClient(given) {
6779
7412
  const unavailableReason = (error) => `${error.message}${error.hint ? ` ${error.hint}` : ""}`;
6780
7413
  const client = {
6781
7414
  config,
7415
+ scopes: createScopeDoors(callDoor),
6782
7416
  async recordWrite({ table_id, data }) {
6783
7417
  const result = await callDoor(
6784
7418
  DOORS.recordWrite,
@@ -10306,15 +10940,15 @@ function labelOf(field) {
10306
10940
  function ruleRefusal(field, rule, item2, values) {
10307
10941
  const label = labelOf(field);
10308
10942
  const base = { sqlstate: "23514", predicted_by: "custom.validate_values", field_key: field.key };
10309
- const num = typeof item2 === "number" ? item2 : null;
10943
+ const num2 = typeof item2 === "number" ? item2 : null;
10310
10944
  switch (rule.kind) {
10311
10945
  case "min":
10312
- if (num !== null && num < Number(rule.value)) {
10946
+ if (num2 !== null && num2 < Number(rule.value)) {
10313
10947
  return { ...base, message: `${label} has to be at least ${rule.value}`, hint: "FLD-3: an attached validation Rule, not a behavior." };
10314
10948
  }
10315
10949
  return null;
10316
10950
  case "max":
10317
- if (num !== null && num > Number(rule.value)) {
10951
+ if (num2 !== null && num2 > Number(rule.value)) {
10318
10952
  return { ...base, message: `${label} cannot be more than ${rule.value}`, hint: "FLD-3: an attached validation Rule, not a behavior." };
10319
10953
  }
10320
10954
  return null;