@inferencebureau/apps-sdk 0.16.4 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -260,8 +260,15 @@ export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends
260
260
  filter?: Filter<M["filter"]>;
261
261
  sort?: SortOf<M> | SortOf<M>[];
262
262
  first?: number;
263
- /** The `endCursor` of the page before: the fast way to page on. */
263
+ /**
264
+ * The `endCursor` of the page before: the records after its last one in the order, so a page never repeats or skips
265
+ * records written meanwhile. The way to read every page, past the 10,000 records `skip` reaches.
266
+ */
264
267
  after?: string | null;
268
+ /** Paging back: the page size, the last `last` records before `before` (or the last of all without it). */
269
+ last?: number;
270
+ /** The `startCursor` of the page after, with `last`. */
271
+ before?: string | null;
265
272
  /**
266
273
  * Records to pass over first, after the filter and sort, for a page by number (`skip: (page - 1) * first`) or a
267
274
  * library that asks for an offset; at most 10,000, and not with `after`. Cursors are faster for reading every page.
@@ -520,10 +527,16 @@ export type ModelRecord<N extends string> = ModelOf<N>["record"];
520
527
  export type ModelInput<N extends string> = ModelOf<N>["input"];
521
528
  /** What `enqueue` passes an action (ActionName) as its params. */
522
529
  export type ParamsOf<A extends string> = A extends `${infer M}.${infer N}` ? M extends keyof AppModels ? AppModels[M] extends ModelTypes ? N extends keyof AppModels[M]["actions"] ? AppModels[M]["actions"][N]["params"] : never : never : GlobalOf<A>["params"] : GlobalOf<A>["params"];
530
+ /**
531
+ * A page of records. `endCursor` (for `after`) and `startCursor` (for `before`) are its last and first records' places
532
+ * in the order. `hasPreviousPage` says whether the read started past the beginning.
533
+ */
523
534
  export interface RecordPage<T = AppRecord> {
524
535
  records: T[];
525
536
  hasNextPage: boolean;
526
537
  endCursor: string | null;
538
+ hasPreviousPage: boolean;
539
+ startCursor: string | null;
527
540
  }
528
541
  /**
529
542
  * A model as the API describes it (`describe()`): its fields in schema order between `id` and the timestamps, which
@@ -717,7 +730,7 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
717
730
  select?: S;
718
731
  }): Promise<ReadOf<M, S> | null>;
719
732
  findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
720
- findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after">): Promise<ReadOf<M, S> | null>;
733
+ findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after" | "last" | "before">): Promise<ReadOf<M, S> | null>;
721
734
  /** Counts, sums, averages, least and most over the records, in groups or all together (AggregateOptions). */
722
735
  aggregate<A extends {
723
736
  [name: string]: AggregateSpec<M["sortable"]>;
@@ -1269,6 +1282,8 @@ export interface SubscriptionRequest {
1269
1282
  * start another (default true). The trial runs from when it first started, installed or not.
1270
1283
  */
1271
1284
  trackTrial?: boolean;
1285
+ /** The time to count the trial's days to, in milliseconds (for tests); now by default. */
1286
+ now?: number;
1272
1287
  }
1273
1288
  export interface AppSubscription {
1274
1289
  id: string;
package/dist/index.js CHANGED
@@ -562,7 +562,7 @@ export async function requestSubscription(shopify, plan) {
562
562
  ...(plan.usage ? [{ plan: { appUsagePricingDetails: { cappedAmount: money(plan.usage.cappedAmount), terms: plan.usage.terms } } }] : []),
563
563
  ];
564
564
  const test = await isTestCharge(shopify, plan.test);
565
- const trialDays = plan.trialDays && plan.trackTrial !== false ? await trialDaysLeft(shopify, plan.trialDays) : plan.trialDays;
565
+ const trialDays = plan.trialDays && plan.trackTrial !== false ? await trialDaysLeft(shopify, plan.trialDays, plan.now) : plan.trialDays;
566
566
  const data = await shopify.graphql(`
567
567
  mutation BillingSubscribe($name: String!, $lineItems: [AppSubscriptionLineItemInput!]!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $replacementBehavior: AppSubscriptionReplacementBehavior) {
568
568
  appSubscriptionCreate(name: $name, lineItems: $lineItems, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, replacementBehavior: $replacementBehavior) {
package/dist/react.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * (a long poll, paused while the tab is hidden), and the route answers which models changed; the read that follows
15
15
  * goes through the route like any other, so it sees only what the viewer may.
16
16
  */
17
- import { type FormEvent, type ReactNode } from "react";
17
+ import { type CSSProperties, type FormEvent, type ReactNode } from "react";
18
18
  import { ApiError, type ActionName, type AggregateOptions, type AggregateResult, type AggregateSpec, type AppRecord, type BulkDeleteResult, type EnqueueOptions, type Filter, type FindManyOptions, type GlobalName, type GlobalOf, type Job, type ModelDescription, type ModelName, type ModelOf, type ModelTypes, type ParamsOf, type ReadOf, type RecordPage, type SelectOf, type Sort, type UntypedModel } from "./index.js";
19
19
  import { type Column, type ColumnOption, type Display, type FieldOption, type FormFieldSpec, type FormValue, type SortOption } from "./auto.js";
20
20
  export { labelOf, recordLabel } from "./auto.js";
@@ -135,7 +135,7 @@ export declare function useFindOne<N extends ModelName, S extends SelectOf<Model
135
135
  select?: S;
136
136
  }): Query<ReadOf<ModelOf<N>, S> | null>;
137
137
  /** The first record matching, or null. */
138
- export declare function useFindFirst<N extends ModelName, S extends SelectOf<ModelOf<N>> | undefined = undefined>(model: N, options?: Omit<FindManyOptions<ModelOf<N>, S>, "first" | "after">, o?: ReadHookOptions): Query<ReadOf<ModelOf<N>, S> | null>;
138
+ export declare function useFindFirst<N extends ModelName, S extends SelectOf<ModelOf<N>> | undefined = undefined>(model: N, options?: Omit<FindManyOptions<ModelOf<N>, S>, "first" | "after" | "last" | "before">, o?: ReadHookOptions): Query<ReadOf<ModelOf<N>, S> | null>;
139
139
  /** Groups of a model's records with their counts, sums and averages, for a chart or a report; again after a write to it. */
140
140
  export declare function useAggregate<N extends ModelName, A extends {
141
141
  [name: string]: AggregateSpec<ModelOf<N>["sortable"]>;
@@ -301,6 +301,31 @@ export interface AutoTableProps extends AutoTableOptions {
301
301
  }
302
302
  /** A model's records as a table: search, sort by a column's heading, pages, and bulk delete when `selectable`. */
303
303
  export declare function AutoTable({ model, rowHref, onRowClick, emptyText, searchable, ...o }: AutoTableProps): import("react").JSX.Element;
304
+ export type PickerKind = "date" | "time" | "datetime";
305
+ export interface DateTimePickerProps {
306
+ /** What it picks; a date and a time unless given. */
307
+ kind?: PickerKind;
308
+ value?: string;
309
+ defaultValue?: string;
310
+ onChange?: (value: string) => void;
311
+ /** Posts the value from a hidden input, for a plain form. */
312
+ name?: string;
313
+ /** The visible input's id, for a `<label htmlFor>`. */
314
+ id?: string;
315
+ min?: string;
316
+ max?: string;
317
+ required?: boolean;
318
+ disabled?: boolean;
319
+ /** `UTC` labels the field and reads the clock in UTC for Today and Now; the value itself has no zone either way. */
320
+ zone?: "UTC" | "local";
321
+ placeholder?: string;
322
+ "aria-label"?: string;
323
+ "aria-describedby"?: string | undefined;
324
+ "aria-invalid"?: boolean | undefined;
325
+ className?: string;
326
+ style?: CSSProperties;
327
+ }
328
+ export declare function DateTimePicker({ kind, value: controlled, defaultValue, onChange, name, id: givenId, min, max, required, disabled, zone, placeholder, "aria-label": ariaLabel, "aria-describedby": describedBy, "aria-invalid": invalid, className, style, }: DateTimePickerProps): import("react").JSX.Element;
304
329
  /** One field's control as standard elements, for the plain form. */
305
330
  export declare function PlainInput({ field: f }: {
306
331
  field: AutoFormField;
package/dist/react.js CHANGED
@@ -16,7 +16,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
16
16
  * (a long poll, paused while the tab is hidden), and the route answers which models changed; the read that follows
17
17
  * goes through the route like any other, so it sees only what the viewer may.
18
18
  */
19
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
19
+ import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
20
20
  import { ApiError, } from "./index.js";
21
21
  import { sessionFetch } from "./browser.js";
22
22
  import { choicesOf, columnsOf, display, formFieldsOf, initialValue, problemField, selectFor, sortOptions, toRecordValue, unchanged, } from "./auto.js";
@@ -583,6 +583,265 @@ export function AutoTable({ model, rowHref, onRowClick, emptyText, searchable =
583
583
  onRowClick(r.record);
584
584
  } }, children: _jsx(PlainCell, { value: cell }) }) : _jsx(PlainCell, { value: cell }) }, t.columns[i].name)))] }, r.id))), !t.rows.length && (_jsx("tr", { className: "auto-none", children: _jsx("td", { colSpan: span || 1, children: t.fetching ? "Loading…" : t.search ? "No records match." : emptyText ?? "No records yet." }) }))] })] }) }), (t.hasNextPage || t.hasPreviousPage) && (_jsxs("div", { className: "auto-pager", children: [_jsx("button", { type: "button", className: "btn sm ghost", disabled: !t.hasPreviousPage || t.fetching, onClick: t.previousPage, children: "Previous" }), _jsxs("span", { children: ["Page ", t.page] }), _jsx("button", { type: "button", className: "btn sm ghost", disabled: !t.hasNextPage || t.fetching, onClick: t.nextPage, children: "Next" })] }))] }));
585
585
  }
586
+ const pad = (n) => String(n).padStart(2, "0");
587
+ const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
588
+ const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
589
+ const WEEKDAYS = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
590
+ const DATE_RE = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
591
+ const TIME_RE = /^(\d{1,2}):(\d{2})$/;
592
+ const daysIn = (y, mo) => new Date(Date.UTC(y, mo, 0)).getUTCDate();
593
+ /** The parts a value or typed text names; `{}` for nothing, null for text that isn't one. */
594
+ function parse(kind, text) {
595
+ const t = text.trim();
596
+ if (!t)
597
+ return {};
598
+ let dateS, timeS;
599
+ if (kind === "time")
600
+ timeS = t;
601
+ else if (kind === "date")
602
+ dateS = t;
603
+ else {
604
+ const m = /^([\d-]+)(?:[ T](\S+))?$/.exec(t);
605
+ if (!m)
606
+ return null;
607
+ dateS = m[1];
608
+ timeS = m[2];
609
+ }
610
+ const out = {};
611
+ if (dateS !== undefined) {
612
+ const m = DATE_RE.exec(dateS);
613
+ if (!m)
614
+ return null;
615
+ const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]);
616
+ if (mo < 1 || mo > 12 || d < 1 || d > daysIn(y, mo))
617
+ return null;
618
+ Object.assign(out, { y, mo, d });
619
+ }
620
+ if (timeS !== undefined) {
621
+ const m = TIME_RE.exec(timeS);
622
+ if (!m)
623
+ return null;
624
+ const h = Number(m[1]), mi = Number(m[2]);
625
+ if (h > 23 || mi > 59)
626
+ return null;
627
+ Object.assign(out, { h, mi });
628
+ }
629
+ return out;
630
+ }
631
+ /** The value string for the parts, or "" while a part the kind needs is missing. */
632
+ function serialize(kind, p) {
633
+ const date = p.y !== undefined && p.mo !== undefined && p.d !== undefined ? `${p.y}-${pad(p.mo)}-${pad(p.d)}` : "";
634
+ const time = p.h !== undefined && p.mi !== undefined ? `${pad(p.h)}:${pad(p.mi)}` : "";
635
+ if (kind === "date")
636
+ return date;
637
+ if (kind === "time")
638
+ return time;
639
+ return date && time ? `${date}T${time}` : "";
640
+ }
641
+ function now(zone) {
642
+ const d = new Date();
643
+ return zone === "UTC"
644
+ ? { y: d.getUTCFullYear(), mo: d.getUTCMonth() + 1, d: d.getUTCDate(), h: d.getUTCHours(), mi: d.getUTCMinutes() }
645
+ : { y: d.getFullYear(), mo: d.getMonth() + 1, d: d.getDate(), h: d.getHours(), mi: d.getMinutes() };
646
+ }
647
+ const CalendarIcon = () => (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("rect", { x: "1.5", y: "2.5", width: "9", height: "8", rx: "1.5" }), _jsx("path", { d: "M1.5 5h9M4 1.5v2M8 1.5v2" })] }));
648
+ const ClockIcon = () => (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M6 3.5v3l2 1.2" })] }));
649
+ const Chevron = ({ dir }) => (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: dir === "left" ? "M7.5 2.5 4 6l3.5 3.5" : "M4.5 2.5 8 6l-3.5 3.5" }) }));
650
+ export function DateTimePicker({ kind = "datetime", value: controlled, defaultValue, onChange, name, id: givenId, min, max, required, disabled, zone = "local", placeholder, "aria-label": ariaLabel, "aria-describedby": describedBy, "aria-invalid": invalid, className, style, }) {
651
+ const autoId = useId();
652
+ const id = givenId ?? `dtp-${autoId}`;
653
+ const [inner, setInner] = useState(defaultValue ?? "");
654
+ const value = controlled ?? inner;
655
+ const parts = useMemo(() => parse(kind, value) ?? {}, [kind, value]);
656
+ const today = now(zone);
657
+ const [open, setOpen] = useState(false);
658
+ /** The field's text while it is being typed; null shows the value. */
659
+ const [text, setText] = useState(null);
660
+ /** The time fields' text while they are being typed. */
661
+ const [hm, setHm] = useState(null);
662
+ const [view, setView] = useState({ y: parts.y ?? today.y, mo: parts.mo ?? today.mo });
663
+ const [place, setPlace] = useState({ end: false, up: false });
664
+ const rootRef = useRef(null);
665
+ const inputRef = useRef(null);
666
+ const popRef = useRef(null);
667
+ const focusDay = useRef(false);
668
+ const minP = useMemo(() => (min ? parse(kind, min) ?? {} : {}), [kind, min]);
669
+ const maxP = useMemo(() => (max ? parse(kind, max) ?? {} : {}), [kind, max]);
670
+ const commit = (next) => {
671
+ const v = serialize(kind, next);
672
+ if (controlled === undefined)
673
+ setInner(v);
674
+ if (v !== value)
675
+ onChange?.(v);
676
+ };
677
+ const withDate = (y, mo, d) => {
678
+ // A day picked before any time means midnight; a time set before any day means today.
679
+ const p = { ...parts, y, mo, d };
680
+ if (kind === "datetime" && p.h === undefined) {
681
+ p.h = 0;
682
+ p.mi = 0;
683
+ }
684
+ return p;
685
+ };
686
+ const withTime = (h, mi) => {
687
+ const p = { ...parts, h, mi };
688
+ if (kind === "datetime" && p.y === undefined) {
689
+ p.y = today.y;
690
+ p.mo = today.mo;
691
+ p.d = today.d;
692
+ }
693
+ return p;
694
+ };
695
+ const show = (y, mo) => setView({ y, mo });
696
+ const openPicker = (toDay) => {
697
+ if (disabled)
698
+ return;
699
+ show(parts.y ?? today.y, parts.mo ?? today.mo);
700
+ focusDay.current = toDay;
701
+ setOpen(true);
702
+ };
703
+ const close = (back = true) => { setOpen(false); setHm(null); if (back)
704
+ inputRef.current?.focus(); };
705
+ // Closes on a click elsewhere.
706
+ useEffect(() => {
707
+ if (!open)
708
+ return;
709
+ const away = (e) => { if (!rootRef.current?.contains(e.target))
710
+ close(false); };
711
+ document.addEventListener("pointerdown", away, true);
712
+ return () => document.removeEventListener("pointerdown", away, true);
713
+ }, [open]);
714
+ // Opens to the side and direction with room; moves focus to the day when the icon opened it.
715
+ useLayoutEffect(() => {
716
+ if (!open)
717
+ return;
718
+ const pop = popRef.current, root = rootRef.current;
719
+ if (pop && root) {
720
+ const r = root.getBoundingClientRect();
721
+ setPlace({ end: r.left + pop.offsetWidth > window.innerWidth - 8 && r.right - pop.offsetWidth >= 8, up: r.bottom + pop.offsetHeight > window.innerHeight - 8 && r.top - pop.offsetHeight >= 8 });
722
+ }
723
+ if (focusDay.current) {
724
+ focusDay.current = false;
725
+ (pop?.querySelector(kind === "time" ? "input" : ".dtp-d.sel, .dtp-d.today, .dtp-d:not(:disabled)"))?.focus();
726
+ }
727
+ }, [open, kind]);
728
+ const dayKey = (y, mo, d) => (e) => {
729
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[e.key];
730
+ if (!step)
731
+ return;
732
+ e.preventDefault();
733
+ const t = new Date(Date.UTC(y, mo - 1, d + step));
734
+ const ny = t.getUTCFullYear(), nmo = t.getUTCMonth() + 1, nd = t.getUTCDate();
735
+ if (dayDisabled(ny, nmo, nd))
736
+ return;
737
+ show(ny, nmo);
738
+ commit(withDate(ny, nmo, nd));
739
+ focusDay.current = true;
740
+ };
741
+ useEffect(() => {
742
+ if (open && focusDay.current && kind !== "time") {
743
+ focusDay.current = false;
744
+ popRef.current?.querySelector(".dtp-d.sel")?.focus();
745
+ }
746
+ }, [open, kind, value]);
747
+ const dayDisabled = (y, mo, d) => {
748
+ const s = `${y}-${pad(mo)}-${pad(d)}`;
749
+ const lo = minP.y !== undefined ? `${minP.y}-${pad(minP.mo)}-${pad(minP.d)}` : null;
750
+ const hi = maxP.y !== undefined ? `${maxP.y}-${pad(maxP.mo)}-${pad(maxP.d)}` : null;
751
+ return (lo !== null && s < lo) || (hi !== null && s > hi);
752
+ };
753
+ const inRange = (p) => {
754
+ const s = serialize(kind, p);
755
+ return !s || ((!min || s >= min) && (!max || s <= max));
756
+ };
757
+ const onText = (t) => {
758
+ setText(t);
759
+ const p = parse(kind, t);
760
+ if (p && (kind === "time" ? p.h !== undefined : p.y !== undefined) && inRange(p)) {
761
+ const next = kind === "datetime" && p.h === undefined ? { ...withDate(p.y, p.mo, p.d) } : p;
762
+ commit(next);
763
+ if (next.y !== undefined)
764
+ show(next.y, next.mo);
765
+ }
766
+ else if (p && Object.keys(p).length === 0)
767
+ commit({});
768
+ };
769
+ const onFieldKey = (e) => {
770
+ if (e.key === "ArrowDown" && !open) {
771
+ e.preventDefault();
772
+ openPicker(true);
773
+ }
774
+ else if (e.key === "Enter" && open) {
775
+ e.preventDefault();
776
+ setText(null);
777
+ close();
778
+ }
779
+ };
780
+ const onRootKey = (e) => { if (e.key === "Escape" && open) {
781
+ e.preventDefault();
782
+ e.stopPropagation();
783
+ close();
784
+ } };
785
+ const clampH = (v) => Math.min(23, Math.max(0, v));
786
+ const clampM = (v) => Math.min(59, Math.max(0, v));
787
+ const hText = hm?.h ?? (parts.h !== undefined ? pad(parts.h) : "");
788
+ const mText = hm?.mi ?? (parts.mi !== undefined ? pad(parts.mi) : "");
789
+ const commitTime = (hs, ms) => {
790
+ const h = parseInt(hs, 10), mi = parseInt(ms, 10);
791
+ if (Number.isFinite(h)) {
792
+ const p = withTime(clampH(h), Number.isFinite(mi) ? clampM(mi) : 0);
793
+ if (inRange(p))
794
+ commit(p);
795
+ }
796
+ setHm(null);
797
+ };
798
+ const timeKey = (field) => (e) => {
799
+ const step = e.key === "ArrowUp" ? 1 : e.key === "ArrowDown" ? -1 : 0;
800
+ if (e.key === "Enter") {
801
+ e.preventDefault();
802
+ commitTime(hText, mText);
803
+ return;
804
+ }
805
+ if (!step)
806
+ return;
807
+ e.preventDefault();
808
+ const h = parts.h ?? 0, mi = parts.mi ?? 0;
809
+ const p = field === "h" ? withTime(clampH(h + step), mi) : withTime(h, clampM(mi + step));
810
+ if (inRange(p))
811
+ commit(p);
812
+ setHm(null);
813
+ };
814
+ const presets = useMemo(() => [
815
+ { name: "Now", h: today.h, mi: today.mi },
816
+ { name: "Start of day", h: 0, mi: 0 },
817
+ { name: "Noon", h: 12, mi: 0 },
818
+ { name: "End of day", h: 23, mi: 59 },
819
+ ], [today.h, today.mi]);
820
+ // The month shown.
821
+ const first = new Date(Date.UTC(view.y, view.mo - 1, 1)).getUTCDay();
822
+ const dim = daysIn(view.y, view.mo), prevDim = view.mo === 1 ? daysIn(view.y - 1, 12) : daysIn(view.y, view.mo - 1);
823
+ const cells = Array.from({ length: 42 }, (_, i) => {
824
+ const n = i - first + 1;
825
+ const out = n < 1 || n > dim;
826
+ const shown = n < 1 ? prevDim + n : n > dim ? n - dim : n;
827
+ const selected = !out && parts.y === view.y && parts.mo === view.mo && parts.d === n;
828
+ const isToday = !out && today.y === view.y && today.mo === view.mo && today.d === n;
829
+ return { key: i, n, shown, out, selected, isToday, off: out || dayDisabled(view.y, view.mo, n) };
830
+ });
831
+ const prevMonth = () => show(view.mo === 1 ? view.y - 1 : view.y, view.mo === 1 ? 12 : view.mo - 1);
832
+ const nextMonth = () => show(view.mo === 12 ? view.y + 1 : view.y, view.mo === 12 ? 1 : view.mo + 1);
833
+ const readout = parts.y !== undefined && parts.h !== undefined
834
+ ? `${DAYS[new Date(Date.UTC(parts.y, parts.mo - 1, parts.d)).getUTCDay()].slice(0, 3)}, ${parts.d} ${MONTHS[parts.mo - 1].slice(0, 3)} ${parts.y} · ${pad(parts.h)}:${pad(parts.mi)}${zone === "UTC" ? " UTC" : ""}`
835
+ : kind === "time" && parts.h !== undefined ? `${pad(parts.h)}:${pad(parts.mi)}${zone === "UTC" ? " UTC" : ""}` : "Nothing picked";
836
+ const hint = kind === "date" ? "YYYY-MM-DD" : kind === "time" ? "HH:MM" : "YYYY-MM-DD HH:MM";
837
+ const popId = `${id}-pop`;
838
+ return (_jsxs("div", { ref: rootRef, className: cx("dtp", kind === "time" && "time-only", open && "open", className), style: style, onKeyDown: onRootKey, children: [_jsxs("div", { className: "dtp-field", children: [_jsx("input", { ref: inputRef, id: id, type: "text", inputMode: "numeric", autoComplete: "off", spellCheck: false, placeholder: placeholder ?? hint, "aria-label": ariaLabel, "aria-describedby": describedBy, "aria-invalid": invalid, value: text ?? value.replace("T", " "), required: required, disabled: disabled, onChange: (e) => onText(e.target.value), onBlur: () => setText(null), onKeyDown: onFieldKey }), zone === "UTC" && _jsx("span", { className: "dtp-zone", children: "UTC" }), _jsx("button", { type: "button", className: "dtp-ic", "aria-label": kind === "time" ? "Pick a time" : kind === "date" ? "Pick a date" : "Pick a date and time", "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": popId, disabled: disabled, onClick: () => (open ? close() : openPicker(true)), children: kind === "time" ? _jsx(ClockIcon, {}) : _jsx(CalendarIcon, {}) })] }), name && _jsx("input", { type: "hidden", name: name, value: value }), open && (_jsxs("div", { ref: popRef, id: popId, className: cx("dtp-pop", place.end && "end", place.up && "up"), role: "dialog", "aria-label": kind === "time" ? "Time" : kind === "date" ? "Date" : "Date and time", children: [kind !== "time" && (_jsxs("div", { className: "dtp-cal", children: [_jsxs("div", { className: "dtp-head", children: [_jsxs("span", { className: "dtp-month", "aria-live": "polite", children: [MONTHS[view.mo - 1], " ", view.y] }), _jsxs("span", { className: "dtp-nav", children: [_jsx("button", { type: "button", "aria-label": "Previous month", onClick: prevMonth, children: _jsx(Chevron, { dir: "left" }) }), _jsx("button", { type: "button", "aria-label": "Next month", onClick: nextMonth, children: _jsx(Chevron, { dir: "right" }) })] })] }), _jsx("div", { className: "dtp-wd", "aria-hidden": "true", children: WEEKDAYS.map((w) => _jsx("span", { children: w }, w)) }), _jsx("div", { className: "dtp-grid", role: "group", "aria-label": "Days", children: cells.map((c) => (_jsx("button", { type: "button", className: cx("dtp-d", c.out && "out", c.isToday && "today", c.selected && "sel"), disabled: c.off, tabIndex: c.selected || (parts.y === undefined && c.isToday) ? 0 : -1, "aria-pressed": c.out ? undefined : c.selected, "aria-label": c.out ? undefined : `${DAYS[(first + c.n - 1) % 7]} ${c.n} ${MONTHS[view.mo - 1]} ${view.y}`, onClick: () => { commit(withDate(view.y, view.mo, c.n)); if (kind === "date")
839
+ close(); }, onKeyDown: dayKey(view.y, view.mo, c.n), children: c.shown }, c.key))) }), _jsxs("div", { className: "dtp-foot", children: [_jsx("button", { type: "button", className: "dtp-link", onClick: () => commit({}), children: "Clear" }), _jsx("button", { type: "button", className: "dtp-link", disabled: dayDisabled(today.y, today.mo, today.d), onClick: () => { show(today.y, today.mo); commit(withDate(today.y, today.mo, today.d)); if (kind === "date")
840
+ close(); }, children: "Today" })] })] })), kind !== "date" && (_jsxs("div", { className: "dtp-time", children: [_jsx("span", { className: "dtp-k", children: "Time \u00B7 24-hour" }), _jsxs("div", { className: "dtp-hm", children: [_jsx("input", { type: "text", inputMode: "numeric", "aria-label": "Hour", value: hText, placeholder: "HH", onChange: (e) => setHm({ h: e.target.value, mi: mText }), onBlur: () => commitTime(hText, mText), onKeyDown: timeKey("h") }), _jsx("span", { className: "colon", "aria-hidden": "true", children: ":" }), _jsx("input", { type: "text", inputMode: "numeric", "aria-label": "Minute", value: mText, placeholder: "MM", onChange: (e) => setHm({ h: hText, mi: e.target.value }), onBlur: () => commitTime(hText, mText), onKeyDown: timeKey("mi") }), zone === "UTC" && _jsx("span", { className: "dtp-zone", children: "UTC" })] }), _jsx("div", { className: "dtp-presets", role: "group", "aria-label": "Common times", children: presets.map((p) => {
841
+ const next = withTime(p.h, p.mi);
842
+ return (_jsxs("button", { type: "button", "aria-pressed": parts.h === p.h && parts.mi === p.mi, disabled: !inRange(next), onClick: () => commit(next), children: [_jsx("span", { children: p.name }), _jsxs("span", { className: "t", children: [pad(p.h), ":", pad(p.mi)] })] }, p.name));
843
+ }) }), _jsxs("div", { className: "dtp-out", children: [kind === "time" ? _jsx("button", { type: "button", className: "dtp-link", onClick: () => commit({}), children: "Clear" }) : _jsx("span", { className: "v", children: readout }), _jsx("button", { type: "button", className: "dtp-done", onClick: () => close(), children: "Done" })] })] }))] }))] }));
844
+ }
586
845
  /** One field's control as standard elements, for the plain form. */
587
846
  export function PlainInput({ field: f }) {
588
847
  const id = `auto-${f.name}`;
@@ -599,7 +858,7 @@ export function PlainInput({ field: f }) {
599
858
  return (_jsx("span", { className: "auto-choices", role: "group", "aria-labelledby": `${id}-label`, children: f.options.map((x) => (_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: chosen.includes(x), onChange: (e) => f.set(e.target.checked ? [...chosen, x] : chosen.filter((c) => c !== x)) }), x] }, x))) }));
600
859
  }
601
860
  case "file": return (_jsxs("span", { className: "auto-filefield", children: [f.current && _jsx("span", { className: "auto-current", children: f.current.url ? _jsx("a", { href: f.current.url, target: "_blank", rel: "noreferrer", children: f.current.fileName }) : f.current.fileName }), _jsx("input", { ...common, type: "file", onChange: (e) => f.set(e.target.files?.[0] ?? null) })] }));
602
- case "dateTime": return _jsx("input", { ...common, type: "datetime-local", value: text, onChange: (e) => f.set(e.target.value) });
861
+ case "dateTime": return _jsx(DateTimePicker, { ...common, value: text, onChange: (v) => f.set(v) });
603
862
  case "number": return _jsx("input", { ...common, type: "text", inputMode: "decimal", value: text, onChange: (e) => f.set(e.target.value) });
604
863
  case "color": return _jsxs("span", { className: "auto-colorfield", children: [_jsx("input", { type: "color", "aria-label": `${f.label} picker`, value: /^#[0-9a-f]{6}$/i.test(text) ? text : "#000000", onChange: (e) => f.set(e.target.value) }), _jsx("input", { ...common, type: "text", value: text, onChange: (e) => f.set(e.target.value) })] });
605
864
  case "password": return _jsx("input", { ...common, type: "password", autoComplete: "new-password", value: text, onChange: (e) => f.set(e.target.value) });
package/dist/test.js CHANGED
@@ -1067,14 +1067,23 @@ class Records {
1067
1067
  return ok;
1068
1068
  }
1069
1069
  sorted(m, rows, sort, readable) {
1070
+ const { tuple, compare } = this.order(m, sort, readable);
1071
+ return [...rows].sort((a, b) => compare(tuple(a), tuple(b)));
1072
+ }
1073
+ /**
1074
+ * A list's order as the API's (records.ts orderTerms): the sort's values, else the best text matches (`rank`) and the
1075
+ * newest, then the id. `tuple` is a row's values in turn, which a keyset cursor carries; `compare` orders two.
1076
+ */
1077
+ order(m, sort, readable, rank) {
1070
1078
  const ctx = { ...CTX, readable };
1071
1079
  const keys = (Array.isArray(sort) ? sort : sort ? [sort] : []).flatMap((s) => this.sortKeys(m, s, ctx));
1072
1080
  if (!keys.length)
1073
- keys.push({ at: (r) => r.createdAt, desc: true });
1081
+ keys.push(...(rank ? [{ at: rank, desc: true }] : []), { at: (r) => r.createdAt, desc: true });
1074
1082
  keys.push({ at: (r) => r.id, desc: true });
1075
- return [...rows].sort((a, b) => {
1076
- for (const k of keys) {
1077
- const x = k.at(a), y = k.at(b);
1083
+ const tuple = (r) => keys.map((k) => k.at(r) ?? null);
1084
+ const compare = (a, b) => {
1085
+ for (let i = 0; i < keys.length; i++) {
1086
+ const x = a[i], y = b[i];
1078
1087
  if (x === y)
1079
1088
  continue;
1080
1089
  // Nulls last, either way.
@@ -1083,10 +1092,11 @@ class Records {
1083
1092
  if (y === null)
1084
1093
  return -1;
1085
1094
  const c = (typeof x === "boolean" ? Number(x) : x) < (typeof y === "boolean" ? Number(y) : y) ? -1 : 1;
1086
- return k.desc ? -c : c;
1095
+ return keys[i].desc ? -c : c;
1087
1096
  }
1088
1097
  return 0;
1089
- });
1098
+ };
1099
+ return { tuple, compare };
1090
1100
  }
1091
1101
  /** A sort's values to order by, in turn (records.ts: sortTerms); a belongsTo's are read from its record, null without one the caller can read. */
1092
1102
  sortKeys(m, sort, ctx) {
@@ -1129,17 +1139,18 @@ class Records {
1129
1139
  async findMany(model, o = {}) {
1130
1140
  const m = this.model(model);
1131
1141
  const plan = this.plan(m, o.select);
1132
- const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
1133
- const offset = startOf(o);
1142
+ const nearest = !!o.search && typeof o.search === "object";
1143
+ const print = orderPrint(o.sort, typeof o.search === "string" ? o.search : null);
1144
+ const p = pagingOf(o, print, !nearest);
1134
1145
  const ctx = { ...CTX, readable: o.readable };
1135
1146
  let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter, ctx));
1136
1147
  let distances = null;
1148
+ let order = null;
1137
1149
  const text = typeof o.search === "string" ? this.textSearch(m, rows, o.search) : null;
1138
1150
  if (text) {
1139
- rows = this.sorted(m, text.rows, o.sort, o.readable);
1140
- // Unsorted, the best matches come first (a stable sort keeps the default order within a score).
1141
- if (!o.sort)
1142
- rows.sort((a, b) => text.score.get(b.id) - text.score.get(a.id));
1151
+ // Unsorted, the best matches come first.
1152
+ order = this.order(m, o.sort, o.readable, (r) => text.score.get(r.id));
1153
+ rows = [...text.rows].sort((a, b) => order.compare(order.tuple(a), order.tuple(b)));
1143
1154
  }
1144
1155
  else if (o.search && typeof o.search === "object") {
1145
1156
  const f = m.byName.get(o.search.field);
@@ -1163,15 +1174,31 @@ class Records {
1163
1174
  }
1164
1175
  rows = rows.filter((r) => distances.has(r.id)).sort((a, b) => distances.get(a.id) - distances.get(b.id) || (a.id < b.id ? -1 : 1));
1165
1176
  }
1166
- else
1167
- rows = this.sorted(m, rows, o.sort, o.readable);
1168
- const page = rows.slice(offset, offset + first);
1177
+ else {
1178
+ order = this.order(m, o.sort, o.readable);
1179
+ rows = [...rows].sort((a, b) => order.compare(order.tuple(a), order.tuple(b)));
1180
+ }
1181
+ // Where the page sits: past a keyset cursor's values (before them, walking back), else from the offset.
1182
+ const at = (v, from) => { const i = rows.findIndex((r) => order.compare(order.tuple(r), v) >= from); return i < 0 ? rows.length : i; };
1183
+ let start = p.offset, end = p.offset + p.size;
1184
+ if (p.backward) {
1185
+ end = p.values ? at(p.values, 0) : rows.length;
1186
+ start = Math.max(0, end - p.size);
1187
+ }
1188
+ else if (p.values) {
1189
+ start = at(p.values, 1);
1190
+ end = start + p.size;
1191
+ }
1192
+ const page = rows.slice(start, end);
1169
1193
  const budget = { left: 5000 };
1170
1194
  const read = (r) => (plan ? this.selected(m, r, plan, o.readable, budget, false) : this.present(m, r, false));
1195
+ const cursor = (r, i) => (!r ? null : order ? keysetCursor(order.tuple(r), print) : cursorOf(i));
1171
1196
  return {
1172
1197
  records: page.map((r) => (distances ? { ...read(r), _distance: distances.get(r.id) } : read(r))),
1173
- hasNextPage: rows.length > offset + first,
1174
- endCursor: page.length ? cursorOf(offset + page.length) : null,
1198
+ hasNextPage: p.backward ? !!o.before : p.endsAt || rows.length > end,
1199
+ endCursor: cursor(page.at(-1), start + page.length),
1200
+ hasPreviousPage: start > 0,
1201
+ startCursor: cursor(page[0], start),
1175
1202
  };
1176
1203
  }
1177
1204
  count(model, filter, readable) {
@@ -1700,31 +1727,80 @@ function cosineDistance(a, b) {
1700
1727
  return na && nb ? 1 - dot / Math.sqrt(na * nb) : 1;
1701
1728
  }
1702
1729
  const base64url = (s) => btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1730
+ const unbase64url = (s) => { try {
1731
+ return decodeURIComponent(escape(atob(s.replace(/-/g, "+").replace(/_/g, "/"))));
1732
+ }
1733
+ catch {
1734
+ return "";
1735
+ } };
1703
1736
  const cursorOf = (offset) => base64url(`o:${offset}`);
1704
- function offsetOf(cursor) {
1705
- if (!cursor)
1706
- return 0;
1707
- let text = "";
1708
- try {
1709
- text = atob(cursor.replace(/-/g, "+").replace(/_/g, "/"));
1710
- }
1711
- catch { /* reported below */ }
1737
+ /** As the API's keyset cursor (records.ts keysetCursor): a record's place in the order, with the order's print. */
1738
+ const keysetCursor = (values, print) => base64url(unescape(encodeURIComponent(`k:${JSON.stringify({ v: values, s: print })}`)));
1739
+ /** The sort and search a keyset cursor belongs to (FNV-1a over them; the API hashes them too). */
1740
+ function orderPrint(sort, search) {
1741
+ let h = 0x811c9dc5;
1742
+ for (const ch of JSON.stringify([sort ?? null, search]))
1743
+ h = Math.imul(h ^ ch.charCodeAt(0), 0x01000193) >>> 0;
1744
+ return h.toString(36);
1745
+ }
1746
+ function readCursor(cursor, field) {
1747
+ const text = unbase64url(cursor);
1712
1748
  const m = /^o:(\d+)$/.exec(text);
1713
- if (!m)
1714
- throw invalid([{ field: "after", message: "isn't a cursor from this API" }]);
1715
- return Number(m[1]);
1749
+ if (m)
1750
+ return { offset: Number(m[1]) };
1751
+ if (text.startsWith("k:")) {
1752
+ try {
1753
+ const j = JSON.parse(text.slice(2));
1754
+ if (Array.isArray(j.v) && j.v.length && typeof j.s === "string")
1755
+ return { values: j.v, print: j.s };
1756
+ }
1757
+ catch { /* reported below */ }
1758
+ }
1759
+ throw invalid([{ field, message: "isn't a cursor from this API" }]);
1716
1760
  }
1717
- /** As the API's: `after`'s cursor or `skip`, one or the other, and `skip` at most MAX_SKIP. */
1718
- function startOf(o) {
1719
- if (o.skip === undefined)
1720
- return offsetOf(o.after);
1721
- if (o.after)
1722
- throw invalid([{ field: "skip", message: "can't be given with after; use one or the other" }]);
1723
- if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1724
- throw invalid([{ field: "skip", message: "must be a whole number, 0 or more" }]);
1725
- if (o.skip > MAX_SKIP)
1726
- throw invalid([{ field: "skip", message: `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before` }]);
1727
- return o.skip;
1761
+ /**
1762
+ * As the API's (records.ts pagingOf): `after` and `skip` page forward, `before` and `last` back; an offset `before` is
1763
+ * the forward page that ends there. `keyset`: whether the read takes keyset cursors (a nearest search's doesn't).
1764
+ */
1765
+ function pagingOf(o, print, keyset) {
1766
+ const bad = (field, message) => invalid([{ field, message }]);
1767
+ const sizeOf = (n) => Math.min(Math.max(1, Math.floor(n ?? 50)), MAX_PAGE);
1768
+ const keysOf = (c, field) => {
1769
+ if ("offset" in c)
1770
+ return null;
1771
+ if (!keyset)
1772
+ throw bad(field, "is a cursor from a sorted read; a nearest search pages by its own cursors");
1773
+ if (c.print !== print)
1774
+ throw bad(field, "is a cursor from a read with another sort or search: start again without it");
1775
+ return c.values;
1776
+ };
1777
+ if (o.after && o.before)
1778
+ throw bad("before", "can't be given with after; use one or the other");
1779
+ if (o.before || o.last !== undefined) {
1780
+ if (o.first !== undefined)
1781
+ throw bad("first", "goes with after; paging back with before, use last");
1782
+ if (o.skip !== undefined)
1783
+ throw bad("skip", "can't be given with before or last");
1784
+ const size = sizeOf(o.last);
1785
+ const c = o.before ? readCursor(o.before, "before") : null;
1786
+ if (c && "offset" in c)
1787
+ return { size: Math.min(size, c.offset), offset: Math.max(0, c.offset - size), values: null, backward: false, endsAt: true };
1788
+ if (!keyset)
1789
+ throw bad("last", "a nearest search pages forward: use first and after");
1790
+ return { size, offset: 0, values: c ? keysOf(c, "before") : null, backward: true, endsAt: false };
1791
+ }
1792
+ const size = sizeOf(o.first);
1793
+ if (o.skip !== undefined) {
1794
+ if (o.after)
1795
+ throw bad("skip", "can't be given with after; use one or the other");
1796
+ if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1797
+ throw bad("skip", "must be a whole number, 0 or more");
1798
+ if (o.skip > MAX_SKIP)
1799
+ throw bad("skip", `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before`);
1800
+ return { size, offset: o.skip, values: null, backward: false, endsAt: false };
1801
+ }
1802
+ const c = o.after ? readCursor(o.after, "after") : null;
1803
+ return c && "offset" in c ? { size, offset: c.offset, values: null, backward: false, endsAt: false } : { size, offset: 0, values: c ? keysOf(c, "after") : null, backward: false, endsAt: false };
1728
1804
  }
1729
1805
  // ---- Shopify ----
1730
1806
  /** The store a test app installs on and runs as, unless a test names another. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.16.4",
3
+ "version": "0.16.6",
4
4
  "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [