@notis_ai/cli 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +17 -0
  2. package/dist/scaffolds/notis-database/app/page.tsx +38 -41
  3. package/dist/scaffolds/notis-database/lib/types.ts +5 -7
  4. package/dist/scaffolds/notis-database/metadata/screenshot-1.png +0 -0
  5. package/dist/scaffolds/notis-database/metadata/screenshot-2.png +0 -0
  6. package/dist/scaffolds/notis-database/metadata/screenshot-3.png +0 -0
  7. package/dist/scaffolds/notis-database/metadata/screenshot-4.png +0 -0
  8. package/dist/scaffolds/notis-database/metadata/screenshot-5.png +0 -0
  9. package/dist/scaffolds/notis-database/metadata/screenshot-fixtures.json +1839 -0
  10. package/dist/scaffolds/notis-database/notis.config.ts +48 -1
  11. package/dist/scaffolds/notis-database/package-lock.json +3935 -0
  12. package/dist/scaffolds/notis-database/package.json +2 -1
  13. package/dist/scaffolds/notis-database/packages/sdk/package.json +36 -0
  14. package/dist/scaffolds/notis-database/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  15. package/dist/scaffolds/notis-database/packages/sdk/src/components/Markdown.tsx +60 -0
  16. package/dist/scaffolds/notis-database/packages/sdk/src/components/MultiSelectActionBar.tsx +278 -0
  17. package/dist/scaffolds/notis-database/packages/sdk/src/components/MultiSelectCheckbox.tsx +91 -0
  18. package/dist/scaffolds/notis-database/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  19. package/dist/scaffolds/notis-database/packages/sdk/src/config.ts +196 -0
  20. package/dist/scaffolds/notis-database/packages/sdk/src/documents.ts +229 -0
  21. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useBackend.ts +41 -0
  22. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  23. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDocument.ts +78 -0
  24. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDocuments.ts +121 -0
  25. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useMultiSelect.ts +539 -0
  26. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useNotis.ts +34 -0
  27. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useNotisNavigation.ts +49 -0
  28. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useTool.ts +64 -0
  29. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useTools.ts +56 -0
  30. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useTopBarSearch.ts +73 -0
  31. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  32. package/dist/scaffolds/notis-database/packages/sdk/src/index.ts +83 -0
  33. package/dist/scaffolds/notis-database/packages/sdk/src/provider.tsx +43 -0
  34. package/dist/scaffolds/notis-database/packages/sdk/src/runtime.ts +220 -0
  35. package/dist/scaffolds/notis-database/packages/sdk/src/styles.css +186 -0
  36. package/dist/scaffolds/notis-database/packages/sdk/src/ui.ts +15 -0
  37. package/dist/scaffolds/notis-database/packages/sdk/src/vite.ts +56 -0
  38. package/dist/scaffolds/notis-database/packages/sdk/tsconfig.json +15 -0
  39. package/dist/scaffolds/notis-database/src/mock-runtime.ts +4 -1
  40. package/dist/scaffolds/notis-journal/CHANGELOG.md +4 -0
  41. package/dist/scaffolds/notis-journal/app/page.tsx +1 -0
  42. package/dist/scaffolds/notis-journal/package-lock.json +4615 -0
  43. package/dist/scaffolds/notis-journal/package.json +2 -2
  44. package/dist/scaffolds/notis-journal/packages/sdk/src/config.ts +52 -1
  45. package/dist/scaffolds/notis-notes/app/page.tsx +39 -46
  46. package/dist/scaffolds/notis-notes/app/phosphor-icons.ts +596 -0
  47. package/dist/scaffolds/notis-notes/lib/visible-properties.ts +144 -0
  48. package/dist/scaffolds/notis-notes/metadata/screenshot-1.png +0 -0
  49. package/dist/scaffolds/notis-notes/metadata/screenshot-2.png +0 -0
  50. package/dist/scaffolds/notis-notes/metadata/screenshot-3.png +0 -0
  51. package/dist/scaffolds/notis-notes/metadata/screenshot-4.png +0 -0
  52. package/dist/scaffolds/notis-notes/metadata/screenshot-5.png +0 -0
  53. package/dist/scaffolds/notis-notes/metadata/screenshot-fixtures.json +752 -0
  54. package/dist/scaffolds/notis-notes/notis.config.ts +48 -3
  55. package/dist/scaffolds/notis-notes/package-lock.json +4636 -0
  56. package/dist/scaffolds/notis-notes/package.json +7 -3
  57. package/dist/scaffolds/notis-notes/packages/sdk/package.json +36 -0
  58. package/dist/scaffolds/notis-notes/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  59. package/dist/scaffolds/notis-notes/packages/sdk/src/components/Markdown.tsx +60 -0
  60. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectActionBar.tsx +278 -0
  61. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectCheckbox.tsx +91 -0
  62. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  63. package/dist/scaffolds/notis-notes/packages/sdk/src/config.ts +196 -0
  64. package/dist/scaffolds/notis-notes/packages/sdk/src/documents.ts +229 -0
  65. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useBackend.ts +41 -0
  66. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  67. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDocument.ts +78 -0
  68. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDocuments.ts +121 -0
  69. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useMultiSelect.ts +539 -0
  70. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useNotis.ts +34 -0
  71. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useNotisNavigation.ts +49 -0
  72. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTool.ts +64 -0
  73. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTools.ts +56 -0
  74. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTopBarSearch.ts +73 -0
  75. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  76. package/dist/scaffolds/notis-notes/packages/sdk/src/index.ts +83 -0
  77. package/dist/scaffolds/notis-notes/packages/sdk/src/provider.tsx +43 -0
  78. package/dist/scaffolds/notis-notes/packages/sdk/src/runtime.ts +220 -0
  79. package/dist/scaffolds/notis-notes/packages/sdk/src/styles.css +186 -0
  80. package/dist/scaffolds/notis-notes/packages/sdk/src/ui.ts +15 -0
  81. package/dist/scaffolds/notis-notes/packages/sdk/src/vite.ts +56 -0
  82. package/dist/scaffolds/notis-notes/packages/sdk/tsconfig.json +15 -0
  83. package/dist/scaffolds/notis-random/CHANGELOG.md +12 -2
  84. package/dist/scaffolds/notis-random/app/history/page.tsx +5 -4
  85. package/dist/scaffolds/notis-random/app/page.tsx +141 -74
  86. package/dist/scaffolds/notis-random/components/ui/button.tsx +50 -0
  87. package/dist/scaffolds/notis-random/components/ui/card.tsx +16 -0
  88. package/dist/scaffolds/notis-random/components/ui/input.tsx +23 -0
  89. package/dist/scaffolds/notis-random/components.json +20 -0
  90. package/dist/scaffolds/notis-random/lib/notis-tools.ts +26 -7
  91. package/dist/scaffolds/notis-random/lib/rng.ts +179 -19
  92. package/dist/scaffolds/notis-random/lib/roll-record.ts +103 -16
  93. package/dist/scaffolds/notis-random/metadata/screenshot-1.png +0 -0
  94. package/dist/scaffolds/notis-random/metadata/screenshot-2.png +0 -0
  95. package/dist/scaffolds/notis-random/metadata/screenshot-3.png +0 -0
  96. package/dist/scaffolds/notis-random/metadata/screenshot-4.png +0 -0
  97. package/dist/scaffolds/notis-random/metadata/screenshot-5.png +0 -0
  98. package/dist/scaffolds/notis-random/metadata/screenshot-fixtures.json +753 -0
  99. package/dist/scaffolds/notis-random/notis.config.ts +47 -3
  100. package/dist/scaffolds/notis-random/package-lock.json +4513 -0
  101. package/dist/scaffolds/notis-random/package.json +6 -2
  102. package/dist/scaffolds/notis-random/packages/sdk/package.json +36 -0
  103. package/dist/scaffolds/notis-random/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  104. package/dist/scaffolds/notis-random/packages/sdk/src/components/Markdown.tsx +60 -0
  105. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectActionBar.tsx +278 -0
  106. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectCheckbox.tsx +91 -0
  107. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  108. package/dist/scaffolds/notis-random/packages/sdk/src/config.ts +196 -0
  109. package/dist/scaffolds/notis-random/packages/sdk/src/documents.ts +229 -0
  110. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useBackend.ts +41 -0
  111. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  112. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDocument.ts +78 -0
  113. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDocuments.ts +121 -0
  114. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useMultiSelect.ts +539 -0
  115. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useNotis.ts +34 -0
  116. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useNotisNavigation.ts +49 -0
  117. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTool.ts +64 -0
  118. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTools.ts +56 -0
  119. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTopBarSearch.ts +73 -0
  120. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  121. package/dist/scaffolds/notis-random/packages/sdk/src/index.ts +83 -0
  122. package/dist/scaffolds/notis-random/packages/sdk/src/provider.tsx +43 -0
  123. package/dist/scaffolds/notis-random/packages/sdk/src/runtime.ts +220 -0
  124. package/dist/scaffolds/notis-random/packages/sdk/src/styles.css +186 -0
  125. package/dist/scaffolds/notis-random/packages/sdk/src/ui.ts +15 -0
  126. package/dist/scaffolds/notis-random/packages/sdk/src/vite.ts +56 -0
  127. package/dist/scaffolds/notis-random/packages/sdk/tsconfig.json +15 -0
  128. package/dist/scaffolds/notis-random/tailwind.config.ts +8 -1
  129. package/dist/scaffolds.json +8 -6
  130. package/package.json +2 -1
  131. package/skills/notis-apps/SKILL.md +449 -144
  132. package/skills/notis-apps/cli.md +15 -0
  133. package/skills/notis-cli/SKILL.md +8 -4
  134. package/skills/notis-onboarding/BRIEF.md +93 -0
  135. package/src/cli.js +52 -7
  136. package/src/command-specs/apps.js +154 -21
  137. package/src/command-specs/diagnostics.js +674 -0
  138. package/src/command-specs/helpers.js +4 -1
  139. package/src/command-specs/index.js +8 -0
  140. package/src/command-specs/onboarding.js +216 -0
  141. package/src/command-specs/smoke.js +386 -0
  142. package/src/command-specs/tools.js +189 -5
  143. package/src/runtime/app-platform.js +65 -4
  144. package/src/runtime/desktop-auth.js +66 -17
  145. package/src/runtime/errors.js +1 -0
  146. package/src/runtime/output.js +21 -3
  147. package/src/runtime/profiles.js +214 -18
  148. package/src/runtime/telemetry.js +92 -0
  149. package/src/runtime/transport.js +29 -1
  150. package/template/.harness/index.html.tmpl +30 -2
  151. package/template/packages/sdk/src/config.ts +38 -1
@@ -0,0 +1,50 @@
1
+ import * as React from 'react';
2
+ import { Slot } from '@radix-ui/react-slot';
3
+ import { cva, type VariantProps } from 'class-variance-authority';
4
+
5
+ import { cn } from '@/lib/utils';
6
+
7
+ const buttonVariants = cva(
8
+ 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
9
+ {
10
+ variants: {
11
+ variant: {
12
+ default: 'bg-foreground text-background hover:bg-foreground/90',
13
+ outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
14
+ ghost: 'hover:bg-accent hover:text-accent-foreground',
15
+ },
16
+ size: {
17
+ default: 'h-10 px-4 py-2',
18
+ sm: 'h-9 rounded-md px-3',
19
+ lg: 'h-11 rounded-md px-8',
20
+ icon: 'h-10 w-10',
21
+ },
22
+ },
23
+ defaultVariants: {
24
+ variant: 'default',
25
+ size: 'default',
26
+ },
27
+ },
28
+ );
29
+
30
+ export interface ButtonProps
31
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
32
+ VariantProps<typeof buttonVariants> {
33
+ asChild?: boolean;
34
+ }
35
+
36
+ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
37
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
38
+ const Comp = asChild ? Slot : 'button';
39
+ return (
40
+ <Comp
41
+ className={cn(buttonVariants({ variant, size, className }))}
42
+ ref={ref}
43
+ {...props}
44
+ />
45
+ );
46
+ },
47
+ );
48
+ Button.displayName = 'Button';
49
+
50
+ export { Button, buttonVariants };
@@ -0,0 +1,16 @@
1
+ import * as React from 'react';
2
+
3
+ import { cn } from '@/lib/utils';
4
+
5
+ const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
6
+ ({ className, ...props }, ref) => (
7
+ <div
8
+ ref={ref}
9
+ className={cn('rounded-xl border border-border bg-card text-card-foreground', className)}
10
+ {...props}
11
+ />
12
+ ),
13
+ );
14
+ Card.displayName = 'Card';
15
+
16
+ export { Card };
@@ -0,0 +1,23 @@
1
+ import * as React from 'react';
2
+
3
+ import { cn } from '@/lib/utils';
4
+
5
+ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
6
+ ({ className, type, ...props }, ref) => (
7
+ <input
8
+ type={type}
9
+ className={cn(
10
+ 'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground ring-offset-background',
11
+ 'file:border-0 file:bg-transparent file:text-sm file:font-medium',
12
+ 'placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
13
+ 'disabled:cursor-not-allowed disabled:opacity-50',
14
+ className,
15
+ )}
16
+ ref={ref}
17
+ {...props}
18
+ />
19
+ ),
20
+ );
21
+ Input.displayName = 'Input';
22
+
23
+ export { Input };
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "new-york",
4
+ "rsc": false,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "tailwind.config.ts",
8
+ "css": "app/globals.css",
9
+ "baseColor": "zinc",
10
+ "cssVariables": true,
11
+ "prefix": ""
12
+ },
13
+ "aliases": {
14
+ "components": "@/components",
15
+ "utils": "@/lib/utils",
16
+ "ui": "@/components/ui",
17
+ "lib": "@/lib",
18
+ "hooks": "@/hooks"
19
+ }
20
+ }
@@ -16,6 +16,8 @@ type QueryRollsArgs = {
16
16
 
17
17
  type QueryRollsResult = {
18
18
  documents?: RollDocument[];
19
+ has_more?: boolean;
20
+ next_offset?: number | null;
19
21
  message?: string;
20
22
  error?: string;
21
23
  };
@@ -36,7 +38,7 @@ type UpsertRollResult = {
36
38
  error?: string;
37
39
  };
38
40
 
39
- export function useRollDocuments(pageSize?: number) {
41
+ export function useRollDocuments(pageSize = 20, fetchAll = false) {
40
42
  const queryRolls = useTool<QueryRollsArgs, QueryRollsResult>('LOCAL_NOTIS_DATABASE_QUERY');
41
43
  const [documents, setDocuments] = useState<RollDocument[]>([]);
42
44
  const [error, setError] = useState<Error | null>(null);
@@ -50,15 +52,32 @@ export function useRollDocuments(pageSize?: number) {
50
52
  let cancelled = false;
51
53
  setError(null);
52
54
 
53
- queryRolls
54
- .call({ database_slug: 'rolls', query: { page_size: pageSize } })
55
- .then((result) => {
56
- if (cancelled) return;
55
+ const fetchRolls = async (): Promise<RollDocument[]> => {
56
+ const allDocuments: RollDocument[] = [];
57
+ let offset = 0;
58
+ while (true) {
59
+ const result = await queryRolls.call({
60
+ database_slug: 'rolls',
61
+ query: { page_size: pageSize },
62
+ ...(offset > 0 ? { offset } : {}),
63
+ });
57
64
  const message = result.error ?? result.message;
58
65
  if (message && !result.documents) {
59
66
  throw new Error(message);
60
67
  }
61
- setDocuments(result.documents ?? []);
68
+ allDocuments.push(...(result.documents ?? []));
69
+ if (!fetchAll || !result.has_more) return allDocuments;
70
+ if (typeof result.next_offset !== 'number' || result.next_offset <= offset) {
71
+ throw new Error('Roll history returned an invalid pagination offset.');
72
+ }
73
+ offset = result.next_offset;
74
+ }
75
+ };
76
+
77
+ fetchRolls()
78
+ .then((result) => {
79
+ if (cancelled) return;
80
+ setDocuments(result);
62
81
  })
63
82
  .catch((err) => {
64
83
  if (cancelled) return;
@@ -69,7 +88,7 @@ export function useRollDocuments(pageSize?: number) {
69
88
  return () => {
70
89
  cancelled = true;
71
90
  };
72
- }, [fetchKey, pageSize, queryRolls.call]);
91
+ }, [fetchAll, fetchKey, pageSize, queryRolls.call]);
73
92
 
74
93
  return {
75
94
  documents,
@@ -8,35 +8,195 @@ export interface Roll {
8
8
  at: string;
9
9
  }
10
10
 
11
- function cryptoRandom(): number {
11
+ /** Standard polyhedral dice offered in dice mode. */
12
+ export const DICE_SIDES = [4, 6, 8, 10, 12, 20] as const;
13
+ export type DiceSides = (typeof DICE_SIDES)[number];
14
+ export const DEFAULT_DICE_SIDES: DiceSides = 6;
15
+
16
+ /** Largest span we accept for an integer draw (stays inside Number.MAX_SAFE_INTEGER). */
17
+ export const MAX_INTEGER_SPAN = 2 ** 32;
18
+
19
+ const UINT32_RANGE = 0x1_0000_0000; // 2 ** 32
20
+
21
+ /** Convert an editable numeric draft without treating an empty field as zero. */
22
+ export function parseBoundDraft(value: string): number {
23
+ return value.trim() === '' ? Number.NaN : Number(value);
24
+ }
25
+
26
+ function randomUint32(): number {
12
27
  const array = new Uint32Array(1);
13
28
  crypto.getRandomValues(array);
14
- return (array[0] ?? 0) / 0xffffffff;
29
+ return array[0] ?? 0;
30
+ }
31
+
32
+ /**
33
+ * Uniform float in [0, 1) — note the exclusive upper bound. Dividing by 2**32
34
+ * (not 2**32 - 1) is what keeps 1.0 unreachable, so callers can safely scale
35
+ * the result without ever landing one past the top of their range.
36
+ */
37
+ export function randomUnit(): number {
38
+ return randomUint32() / UINT32_RANGE;
39
+ }
40
+
41
+ /**
42
+ * Uniform integer in [lo, hi], both inclusive.
43
+ *
44
+ * `Math.floor(randomUnit() * span)` alone is biased whenever `span` does not
45
+ * divide 2**32 evenly: the first `2**32 % span` buckets would each get one
46
+ * extra source value. We remove that by rejecting draws that fall in the
47
+ * ragged tail of the uint32 space, which makes every bucket exactly the same
48
+ * size. The expected number of retries is below 1 for any span we allow.
49
+ */
50
+ export function randomIntInclusive(lo: number, hi: number): number {
51
+ const low = Math.ceil(lo);
52
+ const high = Math.floor(hi);
53
+ if (!Number.isFinite(low) || !Number.isFinite(high) || high < low) {
54
+ throw new RangeError(`Invalid integer range [${lo}, ${hi}]`);
55
+ }
56
+ if (!Number.isSafeInteger(low) || !Number.isSafeInteger(high)) {
57
+ throw new RangeError(`Integer bounds must be safe integers: [${lo}, ${hi}]`);
58
+ }
59
+
60
+ const span = high - low + 1;
61
+ if (span <= 1) return low;
62
+ if (span > MAX_INTEGER_SPAN) {
63
+ throw new RangeError(`Integer range too wide: ${span} values`);
64
+ }
65
+ if (span === UINT32_RANGE) {
66
+ return low + randomUint32();
67
+ }
68
+
69
+ // Values at or above `limit` fall outside the last whole bucket; redraw them.
70
+ const limit = UINT32_RANGE - (UINT32_RANGE % span);
71
+ let draw = randomUint32();
72
+ while (draw >= limit) {
73
+ draw = randomUint32();
74
+ }
75
+ return low + (draw % span);
15
76
  }
16
77
 
78
+ /** Uniform float in [lo, hi) — inclusive low, exclusive high. */
79
+ export function randomFloat(lo: number, hi: number): number {
80
+ if (hi === lo) return lo;
81
+ const span = hi - lo;
82
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || !Number.isFinite(span) || span < 0) {
83
+ throw new RangeError(`Invalid decimal range [${lo}, ${hi}]`);
84
+ }
85
+ return lo + randomUnit() * span;
86
+ }
87
+
88
+ export type BoundsIssue =
89
+ | { code: 'min-not-a-number'; message: string }
90
+ | { code: 'max-not-a-number'; message: string }
91
+ | { code: 'min-not-finite'; message: string }
92
+ | { code: 'max-not-finite'; message: string }
93
+ | { code: 'min-not-below-max'; message: string }
94
+ | { code: 'empty-integer-range'; message: string }
95
+ | { code: 'range-too-wide'; message: string };
96
+
97
+ export interface BoundsCheck {
98
+ ok: boolean;
99
+ issue: BoundsIssue | null;
100
+ /** Bounds actually used by `roll`, after integer snapping. Null when invalid. */
101
+ min: number | null;
102
+ max: number | null;
103
+ }
104
+
105
+ /**
106
+ * Validates a min/max pair for a given mode and reports the bounds that would
107
+ * actually be used. Integer and dice modes snap inward (ceil the low end, floor
108
+ * the high end) so a range like [1.2, 4.8] draws from {2, 3, 4} rather than
109
+ * producing fractional "integers".
110
+ */
111
+ export function checkBounds(min: number, max: number, mode: Mode): BoundsCheck {
112
+ const invalid = (issue: BoundsIssue): BoundsCheck => ({ ok: false, issue, min: null, max: null });
113
+
114
+ if (Number.isNaN(min)) {
115
+ return invalid({ code: 'min-not-a-number', message: 'Minimum must be a number.' });
116
+ }
117
+ if (Number.isNaN(max)) {
118
+ return invalid({ code: 'max-not-a-number', message: 'Maximum must be a number.' });
119
+ }
120
+ if (!Number.isFinite(min)) {
121
+ return invalid({ code: 'min-not-finite', message: 'Minimum must be finite.' });
122
+ }
123
+ if (!Number.isFinite(max)) {
124
+ return invalid({ code: 'max-not-finite', message: 'Maximum must be finite.' });
125
+ }
126
+ if (min >= max) {
127
+ return invalid({
128
+ code: 'min-not-below-max',
129
+ message: 'Minimum must be strictly lower than maximum.',
130
+ });
131
+ }
132
+
133
+ if (mode === 'decimal') {
134
+ if (!Number.isFinite(max - min)) {
135
+ return invalid({
136
+ code: 'range-too-wide',
137
+ message: 'Range is too wide for a decimal draw.',
138
+ });
139
+ }
140
+ return { ok: true, issue: null, min, max };
141
+ }
142
+
143
+ const low = Math.ceil(min);
144
+ const high = Math.floor(max);
145
+ if (high < low) {
146
+ return invalid({
147
+ code: 'empty-integer-range',
148
+ message: `No whole number sits between ${min} and ${max}.`,
149
+ });
150
+ }
151
+ if (!Number.isSafeInteger(low) || !Number.isSafeInteger(high)) {
152
+ return invalid({
153
+ code: 'range-too-wide',
154
+ message: 'Whole-number bounds must be safe integers.',
155
+ });
156
+ }
157
+ if (high - low + 1 > MAX_INTEGER_SPAN) {
158
+ return invalid({
159
+ code: 'range-too-wide',
160
+ message: 'Range is too wide for a whole-number draw.',
161
+ });
162
+ }
163
+ return { ok: true, issue: null, min: low, max: high };
164
+ }
165
+
166
+ /**
167
+ * Draws one value.
168
+ *
169
+ * - `integer` / `dice`: uniform over the whole numbers in [min, max], both ends
170
+ * inclusive and equally likely.
171
+ * - `decimal`: uniform over the continuous interval [min, max) — the low bound
172
+ * is reachable, the high bound is not.
173
+ *
174
+ * Throws a `RangeError` when the bounds are unusable; call `checkBounds` first
175
+ * to surface the reason to the user.
176
+ */
17
177
  export function roll(min: number, max: number, mode: Mode): Roll {
18
- const lo = Math.min(min, max);
19
- const hi = Math.max(min, max);
20
- let value: number;
21
- if (mode === 'integer' || mode === 'dice') {
22
- value = Math.floor(cryptoRandom() * (hi - lo + 1)) + lo;
23
- } else {
24
- value = cryptoRandom() * (hi - lo) + lo;
178
+ const check = checkBounds(min, max, mode);
179
+ if (!check.ok || check.min == null || check.max == null) {
180
+ throw new RangeError(check.issue?.message ?? 'Invalid range.');
25
181
  }
182
+
183
+ const value =
184
+ mode === 'decimal'
185
+ ? randomFloat(check.min, check.max)
186
+ : randomIntInclusive(check.min, check.max);
187
+
26
188
  return {
27
189
  value,
28
190
  mode,
29
- min: lo,
30
- max: hi,
191
+ min: check.min,
192
+ max: check.max,
31
193
  at: new Date().toISOString(),
32
194
  };
33
195
  }
34
196
 
35
- export const DICE_FACES: Record<number, string> = {
36
- 1: 'dice-1',
37
- 2: 'dice-2',
38
- 3: 'dice-3',
39
- 4: 'dice-4',
40
- 5: 'dice-5',
41
- 6: 'dice-6',
42
- };
197
+ /** Human label for a mode, matching the `Mode` select options in the database. */
198
+ export function modeLabel(mode: Mode): string {
199
+ if (mode === 'decimal') return 'Decimal';
200
+ if (mode === 'dice') return 'Dice';
201
+ return 'Integer';
202
+ }
@@ -2,41 +2,88 @@ import type { Mode } from '@/lib/rng';
2
2
 
3
3
  export interface RollDocument {
4
4
  id: string;
5
- title: string;
5
+ title?: string;
6
6
  properties?: Record<string, unknown>;
7
7
  createdAt?: string | null;
8
8
  created_at?: string | null;
9
9
  created_time?: string | null;
10
+ createdTime?: string | null;
10
11
  lastEditedTime?: string | null;
11
12
  last_edited_time?: string | null;
12
13
  updated_at?: string | null;
13
14
  }
14
15
 
16
+ function asRecord(value: unknown): Record<string, unknown> | null {
17
+ return value && typeof value === 'object' && !Array.isArray(value)
18
+ ? (value as Record<string, unknown>)
19
+ : null;
20
+ }
21
+
22
+ /** Flattens a Notion-shaped rich_text / title array to plain text. */
23
+ function flattenRichText(value: unknown): string {
24
+ if (typeof value === 'string') return value;
25
+ if (!Array.isArray(value)) return '';
26
+ return value
27
+ .map((item) => {
28
+ const record = asRecord(item);
29
+ const text = asRecord(record?.text);
30
+ if (typeof text?.content === 'string') return text.content;
31
+ if (typeof record?.plain_text === 'string') return record.plain_text;
32
+ return '';
33
+ })
34
+ .join('');
35
+ }
36
+
37
+ /**
38
+ * Collapses a Notion-shaped property value (`{type: 'number', number: 42}`)
39
+ * to the underlying primitive. The native database tools return this shape,
40
+ * while fixtures and older rows may already be flat, so both are accepted and
41
+ * anything unrecognised passes straight through.
42
+ */
43
+ export function unwrapProperty(value: unknown): unknown {
44
+ const record = asRecord(value);
45
+ if (!record) return value;
46
+
47
+ const type = typeof record.type === 'string' ? record.type : null;
48
+ if (!type) return value;
49
+
50
+ if (type === 'title') return flattenRichText(record.title);
51
+ if (type === 'rich_text') return flattenRichText(record.rich_text);
52
+ if (type === 'select' || type === 'status') {
53
+ const inner = asRecord(record[type]);
54
+ return typeof inner?.name === 'string' ? inner.name : (record[type] ?? null);
55
+ }
56
+ if (type === 'date') {
57
+ const inner = asRecord(record.date);
58
+ return typeof inner?.start === 'string' ? inner.start : (record.date ?? null);
59
+ }
60
+ if (type in record) return record[type];
61
+ return value;
62
+ }
63
+
15
64
  function readString(value: unknown): string | null {
16
- if (typeof value === 'string') {
17
- const trimmed = value.trim();
65
+ const unwrapped = unwrapProperty(value);
66
+ if (typeof unwrapped === 'string') {
67
+ const trimmed = unwrapped.trim();
18
68
  return trimmed.length ? trimmed : null;
19
69
  }
20
- if (typeof value === 'number' || typeof value === 'boolean') {
21
- return String(value);
70
+ if (typeof unwrapped === 'number' || typeof unwrapped === 'boolean') {
71
+ return String(unwrapped);
22
72
  }
23
- if (value && typeof value === 'object') {
24
- const record = value as Record<string, unknown>;
25
- if (typeof record.name === 'string') {
26
- return record.name;
27
- }
28
- if (typeof record.start === 'string') {
29
- return record.start;
30
- }
73
+ const record = asRecord(unwrapped);
74
+ if (record) {
75
+ if (typeof record.name === 'string') return record.name;
76
+ if (typeof record.start === 'string') return record.start;
31
77
  }
32
78
  return null;
33
79
  }
34
80
 
35
81
  function readNumber(value: unknown): number | null {
36
- if (typeof value === 'number' && Number.isFinite(value)) {
37
- return value;
82
+ const unwrapped = unwrapProperty(value);
83
+ if (typeof unwrapped === 'number' && Number.isFinite(unwrapped)) {
84
+ return unwrapped;
38
85
  }
39
- const stringValue = readString(value);
86
+ const stringValue = readString(unwrapped);
40
87
  if (!stringValue) {
41
88
  return null;
42
89
  }
@@ -58,6 +105,7 @@ function readTimestamp(doc: RollDocument): string {
58
105
  doc.createdAt ||
59
106
  doc.created_at ||
60
107
  doc.created_time ||
108
+ doc.createdTime ||
61
109
  doc.lastEditedTime ||
62
110
  doc.last_edited_time ||
63
111
  doc.updated_at ||
@@ -100,3 +148,42 @@ export function normalizeRollRecord(doc: RollDocument): RollRecord {
100
148
  export function sortRollRecordsDesc(a: RollRecord, b: RollRecord): number {
101
149
  return sortTimestamp(b.at) - sortTimestamp(a.at);
102
150
  }
151
+
152
+ /** Merges optimistic local rolls with fetched rows, newest first, id-deduped. */
153
+ export function mergeRollRecords(...groups: RollRecord[][]): RollRecord[] {
154
+ const byId = new Map<string, RollRecord>();
155
+ for (const group of groups) {
156
+ for (const record of group) {
157
+ if (!byId.has(record.id)) {
158
+ byId.set(record.id, record);
159
+ }
160
+ }
161
+ }
162
+ return Array.from(byId.values()).sort(sortRollRecordsDesc);
163
+ }
164
+
165
+ export interface RollStats {
166
+ count: number;
167
+ lowest: number;
168
+ highest: number;
169
+ average: number;
170
+ }
171
+
172
+ /** Summary of a set of rolls. Returns null for an empty set. */
173
+ export function summarizeRolls(records: RollRecord[]): RollStats | null {
174
+ if (records.length === 0) return null;
175
+ let lowest = Number.POSITIVE_INFINITY;
176
+ let highest = Number.NEGATIVE_INFINITY;
177
+ let total = 0;
178
+ for (const record of records) {
179
+ if (record.value < lowest) lowest = record.value;
180
+ if (record.value > highest) highest = record.value;
181
+ total += record.value;
182
+ }
183
+ return {
184
+ count: records.length,
185
+ lowest,
186
+ highest,
187
+ average: total / records.length,
188
+ };
189
+ }