@ai-matrx/records 0.96.14 → 0.97.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +13 -3
@@ -1,5 +1,5 @@
1
1
  import { RealtimeManager } from '@ai-matrx/realtime';
2
- import { R as RecordsClient } from '../client-DKgbZUNt.cjs';
2
+ import { R as RecordsClient } from '../client-pFV_8AhM.cjs';
3
3
  import { C as CreateEntityDataPortOptions, E as EntityDataPort } from '../port-CEf9hsW4.cjs';
4
4
  import { R as RecordOrganizationPort, O as ObjectOrganizationAnswer } from '../objectOrganization-CDAoE7Ft.cjs';
5
5
  import { a as RecordsConfig, b as RowAgentPort, c as RecordsErrorSink, d as RecordsDataSource, e as RecordsChangeSink, f as RowAgentTarget } from '../ports-DEkN-WfA.cjs';
@@ -10,6 +10,7 @@ import '../field-DjS7iId2.cjs';
10
10
  import '../subscription-ycCVo9e2.cjs';
11
11
  import '../rule-CbBXN-FW.cjs';
12
12
  import '../relation-BbPDcXp5.cjs';
13
+ import '../doors-CJPHsohF.cjs';
13
14
  import '../portal-CUwIsXsx.cjs';
14
15
  import '../types-Dxc8Pt7Y.cjs';
15
16
 
@@ -1,5 +1,5 @@
1
1
  import { RealtimeManager } from '@ai-matrx/realtime';
2
- import { R as RecordsClient } from '../client-D7bvxEZW.js';
2
+ import { R as RecordsClient } from '../client-MVuEbxKl.js';
3
3
  import { C as CreateEntityDataPortOptions, E as EntityDataPort } from '../port-BNXXJINy.js';
4
4
  import { R as RecordOrganizationPort, O as ObjectOrganizationAnswer } from '../objectOrganization-IBxZqFZQ.js';
5
5
  import { a as RecordsConfig, b as RowAgentPort, c as RecordsErrorSink, d as RecordsDataSource, e as RecordsChangeSink, f as RowAgentTarget } from '../ports-YOhD5T7h.js';
@@ -10,6 +10,7 @@ import '../field-D-1OKy5r.js';
10
10
  import '../subscription-DucBLG-Y.js';
11
11
  import '../rule-BVX1C83I.js';
12
12
  import '../relation-Dk9-VzY0.js';
13
+ import '../doors-C43_5HjC.js';
13
14
  import '../portal-DDOmQR1f.js';
14
15
  import '../types-Du4Q9Rvi.js';
15
16
 
@@ -418,6 +418,639 @@ function createOpLedger() {
418
418
  }
419
419
  var defaultOpLedger = ledgerOver(globalSlot2("ai-matrx.records.op-ledger", () => /* @__PURE__ */ new Map()));
420
420
 
421
+ // src/scopes/codec.ts
422
+ var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
423
+ var strOrNull = (v) => typeof v === "string" ? v : null;
424
+ var num = (v, fallback = 0) => {
425
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
426
+ return Number.isFinite(n) ? n : fallback;
427
+ };
428
+ function scopeTypeFromStore(row) {
429
+ const singular = row.label_singular ?? row.name ?? "";
430
+ return {
431
+ id: row.id,
432
+ organization_id: row.organization_id,
433
+ label_singular: singular,
434
+ label_plural: row.label_plural ?? singular,
435
+ icon: row.icon ?? "folder",
436
+ color: row.color ?? "",
437
+ slug: row.slug ?? null,
438
+ description: row.description ?? "",
439
+ sort_order: num(row.sort_order),
440
+ max_assignments_per_entity: row.max_assignments_per_entity ?? null,
441
+ default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],
442
+ created_by: row.created_by ?? null,
443
+ created_at: row.created_at ?? "",
444
+ updated_at: row.updated_at ?? ""
445
+ };
446
+ }
447
+ function scopeTypeLabelFromStore(t) {
448
+ const singular = t.label_singular ?? t.name ?? "";
449
+ return { id: t.id, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };
450
+ }
451
+ function settingFromStore(value) {
452
+ if (!Array.isArray(value)) return value;
453
+ return value.map((el) => {
454
+ if (typeof el !== "string") return el;
455
+ const t = el.trim();
456
+ if (!(t.startsWith("{") && t.endsWith("}")) && !(t.startsWith("[") && t.endsWith("]"))) return el;
457
+ try {
458
+ return JSON.parse(t);
459
+ } catch {
460
+ return el;
461
+ }
462
+ });
463
+ }
464
+ function scopeFromStore(row) {
465
+ const settings = {};
466
+ for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);
467
+ return {
468
+ id: row.id,
469
+ scope_type_id: row.scope_type_id,
470
+ organization_id: row.organization_id,
471
+ name: row.name ?? "",
472
+ description: row.description ?? "",
473
+ slug: row.slug ?? null,
474
+ sort_order: num(row.sort_order),
475
+ parent_scope_id: row.parent_scope_id ?? null,
476
+ settings,
477
+ created_by: row.created_by ?? null,
478
+ created_at: row.created_at ?? "",
479
+ updated_at: row.updated_at ?? ""
480
+ };
481
+ }
482
+ function scopeWithTypeFromStore(row) {
483
+ return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };
484
+ }
485
+ function archivedScopeTypeFromStore(row) {
486
+ const singular = row.label_singular ?? "";
487
+ return {
488
+ id: row.id,
489
+ organization_id: row.organization_id,
490
+ label_singular: singular,
491
+ label_plural: row.label_plural ?? singular,
492
+ icon: row.icon ?? "folder",
493
+ color: row.color ?? "",
494
+ archived_at: row.deleted_at ?? "",
495
+ created_by: row.created_by ?? null,
496
+ archived_scope_count: row.archived_scope_count ?? 0
497
+ };
498
+ }
499
+ var FILE_KERNEL_ID = "11111111-0000-4000-8000-000000000006";
500
+ var KINDS = /* @__PURE__ */ new Set([
501
+ "string",
502
+ "markdown",
503
+ "email",
504
+ "url",
505
+ "phone",
506
+ "color",
507
+ "number",
508
+ "percent",
509
+ "currency",
510
+ "boolean",
511
+ "date",
512
+ "datetime",
513
+ "time",
514
+ "object",
515
+ "array",
516
+ "reference",
517
+ "document"
518
+ ]);
519
+ function contextFieldKind(doc, carried) {
520
+ if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type;
521
+ const behavior = String(doc.type ?? "text");
522
+ const fmt = doc.format ? String(doc.format) : "";
523
+ const shown = doc.display_format && typeof doc.display_format === "object" ? String(doc.display_format.id ?? "") : "";
524
+ const kind = String(doc.config?.kind ?? "");
525
+ const multi = Boolean(doc.multi);
526
+ if (behavior === "boolean") return "boolean";
527
+ if (behavior === "relation") return doc.relation_target === FILE_KERNEL_ID && !multi ? "document" : "reference";
528
+ if (behavior === "range") {
529
+ if (kind === "date") return "date";
530
+ if (kind === "datetime") return "datetime";
531
+ if (fmt === "percent" || fmt === "currency") return fmt;
532
+ return "number";
533
+ }
534
+ if (behavior === "text") {
535
+ if (multi) return "array";
536
+ if (fmt === "json") return "object";
537
+ for (const word of [fmt, shown]) {
538
+ if (word === "time" || word === "email" || word === "url" || word === "phone" || word === "color" || word === "markdown") return word;
539
+ }
540
+ }
541
+ return "string";
542
+ }
543
+ var POLICIES = /* @__PURE__ */ new Set(["include", "on_request", "exclude"]);
544
+ var SENSITIVITIES = /* @__PURE__ */ new Set(["public", "internal", "confidential", "restricted"]);
545
+ function contextFieldFromStore(row) {
546
+ const d = row.data ?? {};
547
+ const key = str(d.key);
548
+ const policy = str(d.context_policy, "include");
549
+ const sensitivity = str(d.sensitivity, "internal");
550
+ return {
551
+ id: row.id,
552
+ scope_type_id: row.scope_type_id,
553
+ organization_id: row.organization_id,
554
+ key,
555
+ label: str(d.label, key),
556
+ description: str(d.description),
557
+ kind: contextFieldKind(d, row.carried),
558
+ type: str(d.type, "text"),
559
+ multi: Boolean(d.multi),
560
+ format: strOrNull(d.format),
561
+ config: d.config ?? {},
562
+ relation_target: strOrNull(d.relation_target),
563
+ // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).
564
+ sort: Math.max(0, num(d.sort) - 2),
565
+ context_policy: POLICIES.has(policy) ? policy : "include",
566
+ sensitivity: SENSITIVITIES.has(sensitivity) ? sensitivity : "internal",
567
+ source: str(d.source, "manual"),
568
+ status: str(d.status, "active"),
569
+ status_note: strOrNull(d.status_note),
570
+ category: strOrNull(d.category),
571
+ tags: Array.isArray(d.tags) ? d.tags : [],
572
+ max_items: typeof d.max_items === "number" ? d.max_items : 1,
573
+ custom_component: d.custom_component ?? null,
574
+ reference_source: d.reference_source ?? null,
575
+ allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,
576
+ allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,
577
+ review_interval_days: typeof d.review_interval_days === "number" ? d.review_interval_days : null,
578
+ depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],
579
+ version: num(row.version, 1),
580
+ created_by: row.created_by ?? null,
581
+ created_at: row.created_at ?? "",
582
+ updated_at: row.updated_at ?? ""
583
+ };
584
+ }
585
+ var POLICY_TO_DOOR = { include: "always", on_request: "on_demand", exclude: "never" };
586
+ var SENSITIVITY_TO_DOOR = {
587
+ public: "public",
588
+ internal: "internal",
589
+ confidential: "restricted",
590
+ restricted: "privileged"
591
+ };
592
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
593
+ function referencesOf(row) {
594
+ const v = row.value;
595
+ const list = Array.isArray(v) ? v : v == null ? [] : [v];
596
+ const labels = row.labels ?? {};
597
+ const files = row.files ?? {};
598
+ const toFile = row.field?.relation_target === FILE_KERNEL_ID;
599
+ const out = [];
600
+ for (const el of list) {
601
+ let ref = null;
602
+ if (typeof el === "string" && UUID.test(el)) ref = { id: el, type: toFile ? "file" : "scope" };
603
+ else if (el && typeof el === "object" && typeof el.id === "string") {
604
+ const token = String(el.token ?? "");
605
+ const own = el.label;
606
+ ref = { id: el.id, type: token === "dataset" ? "table" : token || (toFile ? "file" : "scope") };
607
+ if (typeof own === "string" && own) ref.label = own;
608
+ }
609
+ if (!ref) continue;
610
+ const label = labels[ref.id];
611
+ if (label) ref.label = label;
612
+ const fileId = files[ref.id];
613
+ if (fileId) ref.file_id = fileId;
614
+ out.push(ref);
615
+ }
616
+ return out;
617
+ }
618
+ function contextValueFromStore(row) {
619
+ const kind = contextFieldKind(row.field ?? {}, row.field?.carried);
620
+ const carriedText = Boolean(row.field?.carried?.as_text);
621
+ const isRef2 = !carriedText && (kind === "reference" || kind === "document");
622
+ return {
623
+ scope_id: row.scope_id,
624
+ field_id: row.context_item_id,
625
+ key: row.key,
626
+ kind,
627
+ value: row.value ?? null,
628
+ references: isRef2 ? referencesOf(row) : [],
629
+ version: num(row.version, 1),
630
+ set_at: row.set_at ?? null,
631
+ source_type: row.source_type ?? null,
632
+ authored_by: row.authored_by ?? null,
633
+ whole_value: row.whole_value ?? null,
634
+ incomplete: null
635
+ };
636
+ }
637
+ async function sha256Hex(text) {
638
+ const subtle = globalThis.crypto?.subtle;
639
+ if (!subtle) return null;
640
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text));
641
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
642
+ }
643
+ async function completeWholeValues(values, read) {
644
+ const texts = /* @__PURE__ */ new Map();
645
+ await Promise.all(
646
+ values.map(async (cell) => {
647
+ const w = cell.whole_value;
648
+ if (!w || w.in_value || typeof cell.value !== "string") return;
649
+ const head = cell.value;
650
+ const chars = typeof w.chars === "number" ? w.chars : null;
651
+ const incomplete = (fileId, why) => {
652
+ cell.incomplete = { head, chars, file_id: fileId, why };
653
+ };
654
+ if (!w.file_id) return incomplete(null, "The rest of this text is still being saved.");
655
+ if (!read) return incomplete(w.file_id, "This place cannot open the file that holds the whole text.");
656
+ if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));
657
+ try {
658
+ const text = await texts.get(w.file_id);
659
+ if (chars !== null && [...text].length !== chars) {
660
+ return incomplete(w.file_id, `The file holds ${[...text].length} characters, not ${chars}.`);
661
+ }
662
+ if (w.sha256) {
663
+ const sha = await sha256Hex(text);
664
+ if (sha === null) return incomplete(w.file_id, "This browser cannot check the file.");
665
+ if (sha !== w.sha256) return incomplete(w.file_id, "The file's content is not the text the cell points at.");
666
+ }
667
+ cell.value = text;
668
+ } catch (thrown) {
669
+ incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));
670
+ }
671
+ })
672
+ );
673
+ }
674
+ function definedOnly(fields) {
675
+ const out = {};
676
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) out[k] = v;
677
+ return out;
678
+ }
679
+ function fieldSpecForDoor(spec) {
680
+ return definedOnly({
681
+ key: spec.key,
682
+ display_name: spec.label,
683
+ value_type: spec.kind,
684
+ description: spec.description,
685
+ category: spec.category,
686
+ fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : void 0,
687
+ sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : void 0,
688
+ tags: spec.tags,
689
+ sort_order: spec.sort,
690
+ status: spec.status,
691
+ status_note: spec.status_note,
692
+ custom_component: spec.custom_component,
693
+ review_interval_days: spec.review_interval_days,
694
+ allowed_reference_types: spec.allowed_reference_types,
695
+ max_items: spec.max_items,
696
+ allowed_scope_type_ids: spec.allowed_scope_type_ids,
697
+ reference_source: spec.reference_source
698
+ });
699
+ }
700
+ function referenceFence(references) {
701
+ const kinds = [...new Set(references.map((r) => r.type))];
702
+ const type = kinds.length === 1 ? kinds[0] : "mixed";
703
+ const items = references.map((r) => {
704
+ if (r.type === "file" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };
705
+ const item = { id: r.id };
706
+ if (r.label) item.label = r.label;
707
+ if (kinds.length > 1) item.type = r.type;
708
+ return item;
709
+ });
710
+ return "```matrx\n" + JSON.stringify({ matrx_version: 1, kind: "reference", type, items }, null, 2) + "\n```";
711
+ }
712
+ function valuePayloadForDoor(write) {
713
+ const base = definedOnly({
714
+ scope_id: write.scope_id,
715
+ context_item_id: write.field_id,
716
+ source_type: write.source_type,
717
+ change_summary: write.change_summary
718
+ });
719
+ const v = write.value;
720
+ if (write.kind === "reference" || write.kind === "document") {
721
+ if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };
722
+ if (write.kind === "document" && typeof v === "string") return { ...base, value_document_url: v || null };
723
+ return { ...base, value_text: typeof v === "string" ? v || null : null };
724
+ }
725
+ if (v === null || v === void 0 || v === "") {
726
+ return { ...base, value_text: null };
727
+ }
728
+ switch (write.kind) {
729
+ case "number":
730
+ case "percent":
731
+ return typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
732
+ case "currency":
733
+ return typeof v === "object" ? { ...base, value_json: v } : typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
734
+ case "boolean":
735
+ return typeof v === "boolean" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };
736
+ case "date":
737
+ return { ...base, value_date: String(v) };
738
+ case "datetime":
739
+ return { ...base, value_timestamp: String(v) };
740
+ case "time":
741
+ return { ...base, value_time: String(v) };
742
+ case "object":
743
+ case "array":
744
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
745
+ default:
746
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
747
+ }
748
+ }
749
+
750
+ // src/scopes/rules.ts
751
+ function toSlug(name) {
752
+ return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
753
+ }
754
+ function isValidSlug(s) {
755
+ return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);
756
+ }
757
+ var RESERVED_SCOPE_SLUGS = /* @__PURE__ */ new Set(["context-items", "scopes", "edit", "manage", "new", "settings"]);
758
+ function isReservedSlug(s) {
759
+ return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, "-"));
760
+ }
761
+ function resolveSlug(supplied, fallbackName) {
762
+ const slug = supplied?.trim() || toSlug(fallbackName);
763
+ if (!slug || !isValidSlug(slug)) {
764
+ return {
765
+ ok: false,
766
+ error: { code: "invalid_argument", message: "Use letters, numbers and single hyphens for the short name." }
767
+ };
768
+ }
769
+ if (isReservedSlug(slug)) {
770
+ return { ok: false, error: { code: "invalid_argument", message: `"${slug}" is a page name here. Pick another short name.` } };
771
+ }
772
+ return { ok: true, data: slug };
773
+ }
774
+
775
+ // src/scopes/doors.ts
776
+ var SCOPES_PER_CALL = 500;
777
+ var SCOPE_TYPES_PER_FIELDS_CALL = 100;
778
+ var SCOPES_PER_VALUES_CALL = 200;
779
+ var TYPE_SCOPES_PAGE = 200;
780
+ var ARCHIVED_SCOPES_PAGE = 200;
781
+ var uniq = (ids) => [...new Set(ids.filter(Boolean))];
782
+ async function inBatches(ids, size, call) {
783
+ const unique = uniq(ids);
784
+ const batches = [];
785
+ for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));
786
+ const answers = await Promise.all(batches.map(call));
787
+ const out = [];
788
+ for (const a of answers) {
789
+ if (!a.ok) return a;
790
+ out.push(...a.data ?? []);
791
+ }
792
+ return { ok: true, data: out };
793
+ }
794
+ function noRow(door) {
795
+ return { ok: false, error: { code: "internal", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };
796
+ }
797
+ var VALUE_DOOR_CODES = {
798
+ unauthorized: "door",
799
+ forbidden: "door",
800
+ forbidden_org: "door",
801
+ not_found: "not_found",
802
+ invalid_argument: "invalid_argument",
803
+ conflict: "stale_write",
804
+ unavailable: "not_supported"
805
+ };
806
+ function createScopeDoors(call) {
807
+ async function write(door, args) {
808
+ const res = await call(door, args, `scopes.${door}`);
809
+ if (!res.ok) return res;
810
+ const row = res.data?.row;
811
+ if (!row || typeof row !== "object") return noRow(door);
812
+ return { ok: true, data: row };
813
+ }
814
+ async function archiveOrRestore(door, args, id) {
815
+ const res = await call(door, args, `scopes.${door}`);
816
+ return res.ok ? { ok: true, data: { id } } : res;
817
+ }
818
+ async function fieldById(scopeTypeId, fieldId, door) {
819
+ const fields = await doors.fields([scopeTypeId]);
820
+ if (!fields.ok) return fields;
821
+ const field = fields.data.find((f) => f.id === fieldId);
822
+ return field ? { ok: true, data: field } : noRow(door);
823
+ }
824
+ const doors = {
825
+ async tree(organizationIds) {
826
+ const ids = uniq(organizationIds);
827
+ if (ids.length === 0) return { ok: true, data: [] };
828
+ const res = await call("context_tree", { p_organization_ids: ids }, "scopes.tree");
829
+ if (!res.ok) return res;
830
+ const byType = /* @__PURE__ */ new Map();
831
+ for (const s of res.data?.scopes ?? []) {
832
+ const scope = scopeFromStore(s);
833
+ const list = byType.get(scope.scope_type_id) ?? [];
834
+ list.push(scope);
835
+ byType.set(scope.scope_type_id, list);
836
+ }
837
+ return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };
838
+ },
839
+ async types(organizationIds, options) {
840
+ const withCounts = options?.withCounts ?? true;
841
+ const ids = uniq(organizationIds);
842
+ if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };
843
+ const res = await call("context_tree_types", { p_organization_ids: ids, p_with_counts: withCounts }, "scopes.types");
844
+ if (!res.ok) return res;
845
+ const rows = res.data?.types ?? [];
846
+ const counts = withCounts ? {} : null;
847
+ if (counts) for (const r of rows) counts[r.id] = Number(r.scope_count ?? 0);
848
+ return { ok: true, data: { types: rows.map(scopeTypeFromStore), counts } };
849
+ },
850
+ async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {
851
+ const res = await call(
852
+ "context_tree_type_scopes",
853
+ { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },
854
+ "scopes.typeScopesPage"
855
+ );
856
+ if (!res.ok) return res;
857
+ return {
858
+ ok: true,
859
+ data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null }
860
+ };
861
+ },
862
+ async search(organizationIds, query, limit = 100) {
863
+ const ids = uniq(organizationIds);
864
+ const q = query.trim();
865
+ if (ids.length === 0 || q === "") return { ok: true, data: { scopes: [], total: 0 } };
866
+ const res = await call(
867
+ "context_tree_search",
868
+ { p_organization_ids: ids, p_query: q, p_limit: limit },
869
+ "scopes.search"
870
+ );
871
+ if (!res.ok) return res;
872
+ return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };
873
+ },
874
+ async scopes(ids) {
875
+ const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call("context_scopes", { p_scope_ids: batch }, "scopes.scopes"));
876
+ return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;
877
+ },
878
+ async fields(scopeTypeIds) {
879
+ const res = await inBatches(
880
+ scopeTypeIds,
881
+ SCOPE_TYPES_PER_FIELDS_CALL,
882
+ (batch) => call("context_items", { p_scope_type_ids: batch }, "scopes.fields")
883
+ );
884
+ return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;
885
+ },
886
+ async values(scopeIds, options) {
887
+ const res = await inBatches(
888
+ scopeIds,
889
+ SCOPES_PER_VALUES_CALL,
890
+ (batch) => call("context_values", { p_scope_ids: batch }, "scopes.values")
891
+ );
892
+ if (!res.ok) return res;
893
+ const cells = res.data.map(contextValueFromStore);
894
+ await completeWholeValues(cells, options?.readFileText ?? null);
895
+ return { ok: true, data: cells };
896
+ },
897
+ async archivedTypes(organizationId) {
898
+ const res = await call("context_archived_types", { p_organization_id: organizationId }, "scopes.archivedTypes");
899
+ return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;
900
+ },
901
+ async archivedScopesOfType(organizationId, scopeTypeId, wanted) {
902
+ const out = [];
903
+ for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {
904
+ const res = await call(
905
+ "read_records_archived",
906
+ { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: "org", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },
907
+ "scopes.archivedScopesOfType"
908
+ );
909
+ if (!res.ok) return res;
910
+ const rows = res.data ?? [];
911
+ for (const r of rows) {
912
+ if (!wanted.has(r.id)) continue;
913
+ out.push({
914
+ id: r.id,
915
+ name: typeof r.document?.name === "string" ? r.document.name : null,
916
+ slug: typeof r.document?.slug === "string" ? r.document.slug : null,
917
+ archived_at: r.archived_at ?? null
918
+ });
919
+ }
920
+ if (rows.length < ARCHIVED_SCOPES_PAGE) break;
921
+ }
922
+ return { ok: true, data: out };
923
+ },
924
+ async systemItems() {
925
+ const res = await call("context_system_items", {}, "scopes.systemItems");
926
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
927
+ },
928
+ async templates() {
929
+ const res = await call("context_templates", {}, "scopes.templates");
930
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
931
+ },
932
+ async createType(organizationId, spec) {
933
+ const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || "");
934
+ if (!slug.ok) return slug;
935
+ const res = await write("context_type_write", {
936
+ p_organization_id: organizationId,
937
+ p_type_id: null,
938
+ p_spec: definedOnly({
939
+ label_singular: spec.label_singular,
940
+ label_plural: spec.label_plural,
941
+ icon: spec.icon ?? "folder",
942
+ description: spec.description ?? "",
943
+ sort_order: spec.sort_order ?? 0,
944
+ max_assignments: spec.max_assignments_per_entity ?? void 0,
945
+ default_variable_keys: spec.default_variable_keys ?? [],
946
+ color: spec.color,
947
+ slug: slug.data
948
+ })
949
+ });
950
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
951
+ },
952
+ async updateType(typeId, spec) {
953
+ let slug;
954
+ if (spec.slug !== void 0) {
955
+ const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? "");
956
+ if (!resolved.ok) return resolved;
957
+ slug = resolved.data;
958
+ }
959
+ const res = await write("context_type_write", {
960
+ p_organization_id: null,
961
+ p_type_id: typeId,
962
+ p_spec: definedOnly({
963
+ label_singular: spec.label_singular,
964
+ label_plural: spec.label_plural,
965
+ icon: spec.icon,
966
+ description: spec.description,
967
+ sort_order: spec.sort_order,
968
+ max_assignments: spec.max_assignments_per_entity,
969
+ color: spec.color,
970
+ slug
971
+ })
972
+ });
973
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
974
+ },
975
+ archiveType: (typeId) => archiveOrRestore("context_type_archive", { p_type_id: typeId }, typeId),
976
+ restoreType: (typeId) => archiveOrRestore("context_type_restore", { p_type_id: typeId }, typeId),
977
+ async createScope(organizationId, typeId, spec) {
978
+ const slug = resolveSlug(spec.slug, spec.name ?? "");
979
+ if (!slug.ok) return slug;
980
+ const res = await write("context_scope_write", {
981
+ p_organization_id: organizationId,
982
+ p_scope_id: null,
983
+ p_type_id: typeId,
984
+ p_spec: definedOnly({
985
+ name: spec.name,
986
+ parent_scope_id: spec.parent_scope_id,
987
+ description: spec.description ?? "",
988
+ settings: spec.settings ?? {},
989
+ slug: slug.data,
990
+ sort_order: spec.sort_order
991
+ })
992
+ });
993
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
994
+ },
995
+ async updateScope(scopeId, spec) {
996
+ let slug;
997
+ if (spec.slug !== void 0) {
998
+ const resolved = resolveSlug(spec.slug, spec.name ?? "");
999
+ if (!resolved.ok) return resolved;
1000
+ slug = resolved.data;
1001
+ }
1002
+ const res = await write("context_scope_write", {
1003
+ p_organization_id: null,
1004
+ p_scope_id: scopeId,
1005
+ p_type_id: null,
1006
+ p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order })
1007
+ });
1008
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
1009
+ },
1010
+ archiveScope: (scopeId) => archiveOrRestore("context_scope_archive", { p_scope_id: scopeId }, scopeId),
1011
+ restoreScope: (scopeId) => archiveOrRestore("context_scope_restore", { p_scope_id: scopeId }, scopeId),
1012
+ async createField(scopeTypeId, spec) {
1013
+ const res = await write("context_item_write", {
1014
+ p_item_id: null,
1015
+ p_scope_type_id: scopeTypeId,
1016
+ p_spec: fieldSpecForDoor({ kind: "string", description: "", context_policy: "on_request", sensitivity: "internal", tags: [], ...spec })
1017
+ });
1018
+ if (!res.ok) return res;
1019
+ return fieldById(scopeTypeId, String(res.data.id), "context_item_write");
1020
+ },
1021
+ async updateField(fieldId, scopeTypeId, spec) {
1022
+ const res = await write("context_item_write", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });
1023
+ if (!res.ok) return res;
1024
+ return fieldById(scopeTypeId, fieldId, "context_item_write");
1025
+ },
1026
+ archiveField: (fieldId) => archiveOrRestore("context_item_archive", { p_item_id: fieldId }, fieldId),
1027
+ restoreField: (fieldId) => archiveOrRestore("context_item_restore", { p_item_id: fieldId }, fieldId),
1028
+ async writeValue(cell) {
1029
+ const res = await call(
1030
+ "context_value_write",
1031
+ { p_payload: { source_type: "ai_enriched", ...valuePayloadForDoor(cell) } },
1032
+ "scopes.writeValue"
1033
+ );
1034
+ if (!res.ok) return res;
1035
+ const envelope = res.data ?? {};
1036
+ if (!envelope.ok) {
1037
+ const code = VALUE_DOOR_CODES[envelope.error?.code ?? ""] ?? "internal";
1038
+ return { ok: false, error: { code, message: envelope.error?.message ?? "The value was not saved." } };
1039
+ }
1040
+ return {
1041
+ ok: true,
1042
+ data: {
1043
+ scope_id: cell.scope_id,
1044
+ field_id: cell.field_id,
1045
+ version: Number(envelope.data?.version ?? 1),
1046
+ source_type: String(envelope.data?.source_type ?? cell.source_type ?? "ai_enriched")
1047
+ }
1048
+ };
1049
+ }
1050
+ };
1051
+ return doors;
1052
+ }
1053
+
421
1054
  // src/choice.ts
422
1055
  import { isUuidShape as isUuidShape2 } from "@ai-matrx/kit/uuid";
423
1056
  var CHOICE_NUDGES = ["ask", "always_add", "never_add"];
@@ -2859,6 +3492,7 @@ function createRecordsClient(given) {
2859
3492
  const unavailableReason = (error) => `${error.message}${error.hint ? ` ${error.hint}` : ""}`;
2860
3493
  const client = {
2861
3494
  config,
3495
+ scopes: createScopeDoors(callDoor),
2862
3496
  async recordWrite({ table_id, data }) {
2863
3497
  const result = await callDoor(
2864
3498
  DOORS.recordWrite,