@protobase/ui 0.121.0 → 0.121.2
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/account/blocks/personal-mail-block.js +4 -0
- package/dist/account/messages.d.ts +2 -2
- package/dist/activity-chart/messages.d.ts +2 -2
- package/dist/app/change-confirm/messages.d.ts +2 -2
- package/dist/app/charts/messages.d.ts +2 -2
- package/dist/app/comments/messages.d.ts +2 -2
- package/dist/app/confirm-sign-in-messages.d.ts +2 -2
- package/dist/app/conversation/messages.d.ts +2 -2
- package/dist/app/conversation-page/messages.d.ts +2 -2
- package/dist/app/create/messages.d.ts +2 -2
- package/dist/app/delete/messages.d.ts +2 -2
- package/dist/app/displays/messages.d.ts +2 -2
- package/dist/app/embedded-list/messages.d.ts +2 -2
- package/dist/app/export/builder.js +2 -1
- package/dist/app/export/messages.d.ts +2 -2
- package/dist/app/field-editor.js +8 -1
- package/dist/app/field-errors.js +2 -1
- package/dist/app/field-messages.d.ts +2 -2
- package/dist/app/field-types/custom-step-container/messages.d.ts +2 -2
- package/dist/app/field-types/runner-install/messages.d.ts +2 -2
- package/dist/app/field-types/workflow/cache-field.js +1 -1
- package/dist/app/field-types/workflow/definition.d.ts +1 -1
- package/dist/app/field-types/workflow/flow-elements.js +2 -2
- package/dist/app/field-types/workflow/flow-nodes.js +2 -2
- package/dist/app/field-types/workflow/messages.d.ts +2 -2
- package/dist/app/field-types/workflow/node-panel.js +2 -2
- package/dist/app/field-types/workflow/pins/data-edits.js +1 -1
- package/dist/app/field-types/workflow/pins/pin-text.js +1 -1
- package/dist/app/field-types/workflow/task-fields.js +2 -2
- package/dist/app/field-types/workflow/trigger-fields.js +1 -1
- package/dist/app/field-types/workflow/workflow-canvas.js +3 -3
- package/dist/app/field-types/workflow/workflow-field.js +1 -1
- package/dist/app/field-types/workflow/workflow-graph-editor.js +3 -3
- package/dist/app/field-types/workflow-page/insert-value-view.js +3 -3
- package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-page/publish-panel.js +2 -2
- package/dist/app/field-types/workflow-page/rerun-panel.js +1 -1
- package/dist/app/field-types/workflow-page/run-notice.js +1 -1
- package/dist/app/field-types/workflow-page/runs-panel.js +1 -1
- package/dist/app/field-types/workflow-page/test-run-panel.js +2 -2
- package/dist/app/field-types/workflow-page/use-workflow-page.js +2 -2
- package/dist/app/field-types/workflow-page/workbench-bar.js +2 -2
- package/dist/app/field-types/workflow-page/workflow-workbench.js +12 -12
- package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-run/run-trace-view.js +4 -4
- package/dist/app/field-types/workflow-run/step-card.js +1 -1
- package/dist/app/field-types/workflow-run/step-panel.js +1 -1
- package/dist/app/focus/messages.d.ts +2 -2
- package/dist/app/gallery/gallery-layout.d.ts +2 -2
- package/dist/app/gallery/messages.d.ts +2 -2
- package/dist/app/hand-order/messages.d.ts +2 -2
- package/dist/app/history/messages.d.ts +2 -2
- package/dist/app/import/messages.d.ts +2 -2
- package/dist/app/list-messages.d.ts +2 -2
- package/dist/app/messages.d.ts +2 -2
- package/dist/app/meta-gate-messages.d.ts +2 -2
- package/dist/app/new-version/messages.d.ts +2 -2
- package/dist/app/pages/field-value.d.ts +1 -1
- package/dist/app/pages/field-value.js +3 -1
- package/dist/app/pages/messages.d.ts +2 -2
- package/dist/app/record-chart/messages.d.ts +2 -2
- package/dist/app/record-messages.d.ts +2 -2
- package/dist/app/record-row/messages.d.ts +2 -2
- package/dist/app/related-cards/messages.d.ts +2 -2
- package/dist/app/runtime/messages.d.ts +2 -2
- package/dist/app/saved/messages.d.ts +2 -2
- package/dist/app/searches/messages.d.ts +2 -2
- package/dist/app-shell/messages.d.ts +2 -2
- package/dist/assistant-dock/messages.d.ts +2 -2
- package/dist/auth/messages.d.ts +2 -2
- package/dist/calls/messages.d.ts +2 -2
- package/dist/chat/messages.d.ts +2 -2
- package/dist/data-grid/column-spec.d.ts +1 -1
- package/dist/data-grid/messages.d.ts +2 -2
- package/dist/filter-panel/messages.d.ts +2 -2
- package/dist/format/messages.d.ts +2 -2
- package/dist/forms/messages.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inline-child-table/messages.d.ts +2 -2
- package/dist/invitations/messages.d.ts +2 -2
- package/dist/live/field-values.js +2 -1
- package/dist/live/messages.d.ts +2 -2
- package/dist/locale/en.js +9 -1
- package/dist/locale/en.json.d.ts +8 -0
- package/dist/locale/messages.d.ts +16 -0
- package/dist/locale/nl.js +9 -1
- package/dist/mailbox/mail-sender-select.d.ts +23 -0
- package/dist/mailbox/mail-sender-select.js +81 -0
- package/dist/mailbox/mailbox-connect.js +1 -1
- package/dist/mailbox/messages.d.ts +2 -2
- package/dist/mailbox/sender-options-read.d.ts +14 -0
- package/dist/mailbox/sender-options-read.js +31 -0
- package/dist/mailbox/sender-options.d.ts +17 -0
- package/dist/mailbox/sender-options.js +17 -0
- package/dist/mailbox/use-sender-options.d.ts +14 -0
- package/dist/mailbox/use-sender-options.js +57 -0
- package/dist/mocks/customers.d.ts +1 -1
- package/dist/mocks/invoices.d.ts +2 -2
- package/dist/mocks/orders.d.ts +3 -3
- package/dist/notifications/bell/messages.d.ts +2 -2
- package/dist/organizations/messages.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/plugins/messages.d.ts +2 -2
- package/dist/primitives/messages.d.ts +2 -2
- package/dist/shell/assets/{account-page-DIIa49Sf.js → account-page-BEMlob92.js} +2 -2
- package/dist/shell/assets/app-CwxoFZn2.js +34 -0
- package/dist/shell/assets/{assistant-shell-CLGyb2ss.js → assistant-shell-D1PLZHeQ.js} +2 -2
- package/dist/shell/assets/board-display-BZb6Av24.js +2 -0
- package/dist/shell/assets/calendar-display-CNFg47Me.js +2 -0
- package/dist/shell/assets/{call-rings-AviIOqM7.js → call-rings-B0cAdcLq.js} +2 -2
- package/dist/shell/assets/{calls-C2CUgWkn.js → calls-CJX48uHr.js} +2 -2
- package/dist/shell/assets/{circle-alert-DOaXkZQv.js → circle-alert-B-bmotNV.js} +2 -2
- package/dist/shell/assets/composed-page-itsBuYQN.js +2 -0
- package/dist/shell/assets/{composer-section-BLqTkqi8.js → composer-section-CcOJo5ti.js} +2 -2
- package/dist/shell/assets/{connect-route-41MPQMtp.js → connect-route-CFKOOd6G.js} +2 -2
- package/dist/shell/assets/{copy-field-Ct-6xn8T.js → copy-field-DOFRIY_Q.js} +2 -2
- package/dist/shell/assets/create-route-Dv-SPGqY.js +2 -0
- package/dist/shell/assets/{custom-step-container-field-C0uZrHjV.js → custom-step-container-field-Cpk6ImRJ.js} +4 -4
- package/dist/shell/assets/embedded-list-DoHDT3Av.js +3 -0
- package/dist/shell/assets/en-C_BQKBSV.js +2 -0
- package/dist/shell/assets/{export-dialog-BerhgfFO.js → export-dialog-Ivzdiuhz.js} +2 -2
- package/dist/shell/assets/export-worker-C46NatsO.js +15 -0
- package/dist/shell/assets/{first-organization-page-CKYevHep.js → first-organization-page-in6WzIgy.js} +2 -2
- package/dist/shell/assets/{graph-view-CoLu3Uhs.js → graph-view-BRuO-SOE.js} +2 -2
- package/dist/shell/assets/{group-donut-B8v2SWzP.js → group-donut-3NIqjraT.js} +2 -2
- package/dist/shell/assets/{guest-call-page-DqQMPCVU.js → guest-call-page-NZyVZiKI.js} +3 -3
- package/dist/shell/assets/{html-viewer-BntGWVRA.js → html-viewer-C1KycBYl.js} +2 -2
- package/dist/shell/assets/{import-dialog-DThTUXFS.js → import-dialog-CyB3vJn7.js} +2 -2
- package/dist/shell/assets/{import-table-dialog-C-XIx1Dd.js → import-table-dialog-D8yGy95h.js} +2 -2
- package/dist/shell/assets/{index-CI7L8s0t.js → index-CkkBg7C6.js} +1 -1
- package/dist/shell/assets/{invitations-page-COFjv2AV.js → invitations-page-BjEW7hIz.js} +2 -2
- package/dist/shell/assets/{layout-grid-CvCNKDtn.js → layout-grid-OO8eIGYq.js} +2 -2
- package/dist/shell/assets/{legend-item-9nkaAII6.js → legend-item-eNQOaTxV.js} +2 -2
- package/dist/shell/assets/{lib-zod-B92j-KH2.js → lib-zod-CxxP7Qhu.js} +2 -2
- package/dist/shell/assets/list-page-bIQkpGOc.js +4 -0
- package/dist/shell/assets/{maplibre-5GcVztUc.js → maplibre-DV3j-5Y6.js} +2 -2
- package/dist/shell/assets/{markdown-content-DVmg_kx3.js → markdown-content-C08v-1FZ.js} +2 -2
- package/dist/shell/assets/members-page-B9hyyuVp.js +2 -0
- package/dist/shell/assets/{message-content-BpfTrsWh.js → message-content-DLKHIzRa.js} +3 -3
- package/dist/shell/assets/messages-NBuAsjFr.js +2 -0
- package/dist/shell/assets/nl-DzJ_yv1H.js +2 -0
- package/dist/shell/assets/organization-page-DeTS9uAn.js +2 -0
- package/dist/shell/assets/organizations-page-qM5TQfyb.js +2 -0
- package/dist/shell/assets/parse-worker-COWuolaE.js +35 -0
- package/dist/shell/assets/{pending-invitation-row-t63yAwI8.js → pending-invitation-row-9-2Fmy3F.js} +2 -2
- package/dist/shell/assets/{period-chart-BVv9kC_E.js → period-chart-UOm7kPWB.js} +2 -2
- package/dist/shell/assets/{person-row-CgvcHRmL.js → person-row-DOXM02rY.js} +2 -2
- package/dist/shell/assets/public-form-page-Bj9YxgGp.js +2 -0
- package/dist/shell/assets/{record-lines-Dts68Cfq.js → record-lines-PZ4g8sb5.js} +2 -2
- package/dist/shell/assets/{record-map-BO9rZaxg.js → record-map-CkWjStZn.js} +2 -2
- package/dist/shell/assets/{record-opens-Ds9nDyw1.js → record-opens-6vtBiJ2O.js} +2 -2
- package/dist/shell/assets/record-page-DrQL98n9.js +3 -0
- package/dist/shell/assets/{record-preview-CwySCCRj.js → record-preview-BSqik7HQ.js} +2 -2
- package/dist/shell/assets/{records-map-Bq_dBgiT.js → records-map-CXBbBlYG.js} +2 -2
- package/dist/shell/assets/render-node-DEyR63E8.js +3 -0
- package/dist/shell/assets/reorder-button-CdgrzXlf.js +2 -0
- package/dist/shell/assets/{run-trace-view-BtyPPUyt.js → run-trace-view-CqcgX5lE.js} +2 -2
- package/dist/shell/assets/{runner-install-field-DvuPCX28.js → runner-install-field-Dm7GhYaF.js} +2 -2
- package/dist/shell/assets/{runtime-update-e56Spv--.js → runtime-update-BdhyiFl9.js} +2 -2
- package/dist/shell/assets/shared-protobase-ui-CDtJQrEp.js +1 -0
- package/dist/shell/assets/{sheet-source-Cenf8A74.js → sheet-source-NKu1Enl2.js} +3 -3
- package/dist/shell/assets/sign-in-policy-page-DINzAtyt.js +2 -0
- package/dist/shell/assets/start-block-queries-Bc743CdL.js +2 -0
- package/dist/shell/assets/step-catalog-B9QbvZP_.js +2 -0
- package/dist/shell/assets/{step-panel-DD821ue5.js → step-panel-C5Pnb-Vb.js} +2 -2
- package/dist/shell/assets/timeline-display-hbo62z0J.js +2 -0
- package/dist/shell/assets/{trash-Ch2JFURM.js → trash-YqRXn8JG.js} +2 -2
- package/dist/shell/assets/{update-set-Zch9kB-u.js → update-set-DFWECx_E.js} +2 -2
- package/dist/shell/assets/use-calendar-move-D_6TlMr4.js +2 -0
- package/dist/shell/assets/{use-display-rows-s-zuk4Lc.js → use-display-rows-1Xjy5pR2.js} +2 -2
- package/dist/shell/assets/use-my-invitations-CrSF37dB.js +2 -0
- package/dist/shell/assets/{use-paged-search-CxaSlMkh.js → use-paged-search-CtD7Lf-E.js} +2 -2
- package/dist/shell/assets/{use-run-trace-CRG2_uVq.js → use-run-trace-5H4UJvB-.js} +2 -2
- package/dist/shell/assets/{use-workflow-page-BPZWN9Iv.js → use-workflow-page-dAWuZvWk.js} +2 -2
- package/dist/shell/assets/{use-workflow-types-Dk4FOVoz.js → use-workflow-types-Cjkw47Mf.js} +2 -2
- package/dist/shell/assets/{workflow-canvas-DBlvFI_n.js → workflow-canvas-BkFimRd2.js} +4 -4
- package/dist/shell/assets/{workflow-field-DXiYYH5X.js → workflow-field-BQImywHx.js} +3 -3
- package/dist/shell/assets/{workflow-graph-editor-BtNoPI_a.js → workflow-graph-editor-DYBqdH_O.js} +2 -2
- package/dist/shell/assets/{workflow-run-field-CztPPLbi.js → workflow-run-field-CyxK0W7w.js} +3 -3
- package/dist/shell/assets/workflow-status-field-Bzri4NHN.js +2 -0
- package/dist/shell/assets/workflow-workbench-DC2gtXz1.js +4 -0
- package/dist/shell/index.html +3 -3
- package/dist/shell/protobase.shell.json +2 -2
- package/dist/shell/protobase.sw.js +2 -2
- package/dist/shell-source-maps/assets/{account-page-DIIa49Sf.js.map → account-page-BEMlob92.js.map} +1 -1
- package/dist/shell-source-maps/assets/app-CwxoFZn2.js.map +1 -0
- package/dist/shell-source-maps/assets/{assistant-shell-CLGyb2ss.js.map → assistant-shell-D1PLZHeQ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{board-display-DJJD_jjY.js.map → board-display-BZb6Av24.js.map} +1 -1
- package/dist/shell-source-maps/assets/{calendar-display-7R7Vz5Vm.js.map → calendar-display-CNFg47Me.js.map} +1 -1
- package/dist/shell-source-maps/assets/{call-rings-AviIOqM7.js.map → call-rings-B0cAdcLq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{calls-C2CUgWkn.js.map → calls-CJX48uHr.js.map} +1 -1
- package/dist/shell-source-maps/assets/{circle-alert-DOaXkZQv.js.map → circle-alert-B-bmotNV.js.map} +1 -1
- package/dist/shell-source-maps/assets/{composed-page-DjGZy9C7.js.map → composed-page-itsBuYQN.js.map} +1 -1
- package/dist/shell-source-maps/assets/{composer-section-BLqTkqi8.js.map → composer-section-CcOJo5ti.js.map} +1 -1
- package/dist/shell-source-maps/assets/{connect-route-41MPQMtp.js.map → connect-route-CFKOOd6G.js.map} +1 -1
- package/dist/shell-source-maps/assets/{copy-field-Ct-6xn8T.js.map → copy-field-DOFRIY_Q.js.map} +1 -1
- package/dist/shell-source-maps/assets/{create-route-CRZSYoTi.js.map → create-route-Dv-SPGqY.js.map} +1 -1
- package/dist/shell-source-maps/assets/{custom-step-container-field-C0uZrHjV.js.map → custom-step-container-field-Cpk6ImRJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/embedded-list-DoHDT3Av.js.map +1 -0
- package/dist/shell-source-maps/assets/en-C_BQKBSV.js.map +1 -0
- package/dist/shell-source-maps/assets/{export-dialog-BerhgfFO.js.map → export-dialog-Ivzdiuhz.js.map} +1 -1
- package/dist/shell-source-maps/assets/export-worker-C46NatsO.js.map +1 -0
- package/dist/shell-source-maps/assets/{first-organization-page-CKYevHep.js.map → first-organization-page-in6WzIgy.js.map} +1 -1
- package/dist/shell-source-maps/assets/{graph-view-CoLu3Uhs.js.map → graph-view-BRuO-SOE.js.map} +1 -1
- package/dist/shell-source-maps/assets/{group-donut-B8v2SWzP.js.map → group-donut-3NIqjraT.js.map} +1 -1
- package/dist/shell-source-maps/assets/{guest-call-page-DqQMPCVU.js.map → guest-call-page-NZyVZiKI.js.map} +1 -1
- package/dist/shell-source-maps/assets/{html-viewer-BntGWVRA.js.map → html-viewer-C1KycBYl.js.map} +1 -1
- package/dist/shell-source-maps/assets/{import-dialog-DThTUXFS.js.map → import-dialog-CyB3vJn7.js.map} +1 -1
- package/dist/shell-source-maps/assets/{import-table-dialog-C-XIx1Dd.js.map → import-table-dialog-D8yGy95h.js.map} +1 -1
- package/dist/shell-source-maps/assets/{invitations-page-COFjv2AV.js.map → invitations-page-BjEW7hIz.js.map} +1 -1
- package/dist/shell-source-maps/assets/{layout-grid-CvCNKDtn.js.map → layout-grid-OO8eIGYq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{legend-item-9nkaAII6.js.map → legend-item-eNQOaTxV.js.map} +1 -1
- package/dist/shell-source-maps/assets/lib-zod-CxxP7Qhu.js.map +1 -0
- package/dist/shell-source-maps/assets/{list-page-D3nIEwGf.js.map → list-page-bIQkpGOc.js.map} +1 -1
- package/dist/shell-source-maps/assets/{maplibre-5GcVztUc.js.map → maplibre-DV3j-5Y6.js.map} +1 -1
- package/dist/shell-source-maps/assets/{markdown-content-DVmg_kx3.js.map → markdown-content-C08v-1FZ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{members-page-DoRl-b9K.js.map → members-page-B9hyyuVp.js.map} +1 -1
- package/dist/shell-source-maps/assets/{message-content-BpfTrsWh.js.map → message-content-DLKHIzRa.js.map} +1 -1
- package/dist/shell-source-maps/assets/{messages-CZQvPUZQ.js.map → messages-NBuAsjFr.js.map} +1 -1
- package/dist/shell-source-maps/assets/nl-DzJ_yv1H.js.map +1 -0
- package/dist/shell-source-maps/assets/{organization-page-DeaQlPop.js.map → organization-page-DeTS9uAn.js.map} +1 -1
- package/dist/shell-source-maps/assets/{organizations-page-Dlosll2b.js.map → organizations-page-qM5TQfyb.js.map} +1 -1
- package/dist/shell-source-maps/assets/parse-worker-COWuolaE.js.map +1 -0
- package/dist/shell-source-maps/assets/{pending-invitation-row-t63yAwI8.js.map → pending-invitation-row-9-2Fmy3F.js.map} +1 -1
- package/dist/shell-source-maps/assets/{period-chart-BVv9kC_E.js.map → period-chart-UOm7kPWB.js.map} +1 -1
- package/dist/shell-source-maps/assets/{person-row-CgvcHRmL.js.map → person-row-DOXM02rY.js.map} +1 -1
- package/dist/shell-source-maps/assets/{public-form-page-CruNnqqc.js.map → public-form-page-Bj9YxgGp.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-lines-Dts68Cfq.js.map → record-lines-PZ4g8sb5.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-map-BO9rZaxg.js.map → record-map-CkWjStZn.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-opens-Ds9nDyw1.js.map → record-opens-6vtBiJ2O.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-page-DJgscks5.js.map → record-page-DrQL98n9.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-preview-CwySCCRj.js.map → record-preview-BSqik7HQ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{records-map-Bq_dBgiT.js.map → records-map-CXBbBlYG.js.map} +1 -1
- package/dist/shell-source-maps/assets/render-node-DEyR63E8.js.map +1 -0
- package/dist/shell-source-maps/assets/{reorder-button-BGgoLDx3.js.map → reorder-button-CdgrzXlf.js.map} +1 -1
- package/dist/shell-source-maps/assets/{run-trace-view-BtyPPUyt.js.map → run-trace-view-CqcgX5lE.js.map} +1 -1
- package/dist/shell-source-maps/assets/{runner-install-field-DvuPCX28.js.map → runner-install-field-Dm7GhYaF.js.map} +1 -1
- package/dist/shell-source-maps/assets/{runtime-update-e56Spv--.js.map → runtime-update-BdhyiFl9.js.map} +1 -1
- package/dist/shell-source-maps/assets/{sheet-source-Cenf8A74.js.map → sheet-source-NKu1Enl2.js.map} +1 -1
- package/dist/shell-source-maps/assets/{sign-in-policy-page-CUiU8ZIN.js.map → sign-in-policy-page-DINzAtyt.js.map} +1 -1
- package/dist/shell-source-maps/assets/{start-block-queries-DUvYFyeX.js.map → start-block-queries-Bc743CdL.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-catalog-CKmRa3SA.js.map → step-catalog-B9QbvZP_.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-panel-DD821ue5.js.map → step-panel-C5Pnb-Vb.js.map} +1 -1
- package/dist/shell-source-maps/assets/{timeline-display-ChPHZfO_.js.map → timeline-display-hbo62z0J.js.map} +1 -1
- package/dist/shell-source-maps/assets/{trash-Ch2JFURM.js.map → trash-YqRXn8JG.js.map} +1 -1
- package/dist/shell-source-maps/assets/{update-set-Zch9kB-u.js.map → update-set-DFWECx_E.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-calendar-move-Cl14_xWL.js.map → use-calendar-move-D_6TlMr4.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-display-rows-s-zuk4Lc.js.map → use-display-rows-1Xjy5pR2.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-my-invitations-APXH_Xf1.js.map → use-my-invitations-CrSF37dB.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-paged-search-CxaSlMkh.js.map → use-paged-search-CtD7Lf-E.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-run-trace-CRG2_uVq.js.map → use-run-trace-5H4UJvB-.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-workflow-page-BPZWN9Iv.js.map → use-workflow-page-dAWuZvWk.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-workflow-types-Dk4FOVoz.js.map → use-workflow-types-Cjkw47Mf.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-canvas-DBlvFI_n.js.map → workflow-canvas-BkFimRd2.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-field-DXiYYH5X.js.map → workflow-field-BQImywHx.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-graph-editor-BtNoPI_a.js.map → workflow-graph-editor-DYBqdH_O.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-run-field-CztPPLbi.js.map → workflow-run-field-CyxK0W7w.js.map} +1 -1
- package/dist/shell-source-maps/assets/workflow-status-field-Bzri4NHN.js.map +1 -0
- package/dist/shell-source-maps/assets/{workflow-workbench-CAz04v9t.js.map → workflow-workbench-DC2gtXz1.js.map} +1 -1
- package/dist/status/messages.d.ts +2 -2
- package/dist/users/messages.d.ts +2 -2
- package/package.json +5 -5
- package/dist/shell/assets/app-B8KcM2Z-.js +0 -34
- package/dist/shell/assets/board-display-DJJD_jjY.js +0 -2
- package/dist/shell/assets/calendar-display-7R7Vz5Vm.js +0 -2
- package/dist/shell/assets/composed-page-DjGZy9C7.js +0 -2
- package/dist/shell/assets/create-route-CRZSYoTi.js +0 -2
- package/dist/shell/assets/embedded-list-C3nd1V5o.js +0 -3
- package/dist/shell/assets/en-BHrKuf4K.js +0 -2
- package/dist/shell/assets/export-worker-CNhkzttC.js +0 -15
- package/dist/shell/assets/list-page-D3nIEwGf.js +0 -4
- package/dist/shell/assets/members-page-DoRl-b9K.js +0 -2
- package/dist/shell/assets/messages-CZQvPUZQ.js +0 -2
- package/dist/shell/assets/nl-D11b5T7-.js +0 -2
- package/dist/shell/assets/organization-page-DeaQlPop.js +0 -2
- package/dist/shell/assets/organizations-page-Dlosll2b.js +0 -2
- package/dist/shell/assets/parse-worker-CAcPVcu7.js +0 -35
- package/dist/shell/assets/public-form-page-CruNnqqc.js +0 -2
- package/dist/shell/assets/record-page-DJgscks5.js +0 -3
- package/dist/shell/assets/render-node-zjMYynnA.js +0 -3
- package/dist/shell/assets/reorder-button-BGgoLDx3.js +0 -2
- package/dist/shell/assets/shared-protobase-ui-QP42FY24.js +0 -1
- package/dist/shell/assets/sign-in-policy-page-CUiU8ZIN.js +0 -2
- package/dist/shell/assets/start-block-queries-DUvYFyeX.js +0 -2
- package/dist/shell/assets/step-catalog-CKmRa3SA.js +0 -2
- package/dist/shell/assets/timeline-display-ChPHZfO_.js +0 -2
- package/dist/shell/assets/use-calendar-move-Cl14_xWL.js +0 -2
- package/dist/shell/assets/use-my-invitations-APXH_Xf1.js +0 -2
- package/dist/shell/assets/workflow-status-field-K3DE4tPj.js +0 -2
- package/dist/shell/assets/workflow-workbench-CAz04v9t.js +0 -4
- package/dist/shell-source-maps/assets/app-B8KcM2Z-.js.map +0 -1
- package/dist/shell-source-maps/assets/embedded-list-C3nd1V5o.js.map +0 -1
- package/dist/shell-source-maps/assets/en-BHrKuf4K.js.map +0 -1
- package/dist/shell-source-maps/assets/export-worker-CNhkzttC.js.map +0 -1
- package/dist/shell-source-maps/assets/lib-zod-B92j-KH2.js.map +0 -1
- package/dist/shell-source-maps/assets/nl-D11b5T7-.js.map +0 -1
- package/dist/shell-source-maps/assets/parse-worker-CAcPVcu7.js.map +0 -1
- package/dist/shell-source-maps/assets/render-node-zjMYynnA.js.map +0 -1
- package/dist/shell-source-maps/assets/workflow-status-field-K3DE4tPj.js.map +0 -1
package/dist/shell-source-maps/assets/{sheet-source-Cenf8A74.js.map → sheet-source-NKu1Enl2.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sheet-source-Cenf8A74.js","names":["message","normalized","text","message","useId","useId","n","a","t","__toESM","require_react","require_jsx_runtime","cn","printFilter","createLucideIcon","createWhere","isApiError","enumLabel","Spinner","humanize","ErrorBanner","parseNumberText","Download","activeLocale","formatTag","saveFile","Button","displayValue","isEmptyCell","text","isSheetDate","cellText","isSheetJson","__iconData","FileSpreadsheet","import_react","import_jsx_runtime","csvField","failedRowsCsv","lines","rows","b","headers","row","column","fields","ImportCounts","label","counts","name","value","fieldLabel","view","importableTypes","relationTarget","target","field","resources","importableFields","model","json","matchableTypes","matchFields","key","others","relationModel","requiredOnCreate","normalized$1","autoMapping","taken","header","candidate","unmappedRequired","mode","mapped","mapping","entry","ok","problem","quoted","cell","toNumberText","options","integerValue","text$1","whole","fraction","decimalValue","text$2","trueWords","falseWords","booleanValue","text$3","pad","calendarDate","at","year","month","day","timePattern","readWallTime","iso","local","order","date","hours","minutes","seconds","wallTimeOf","time","notDate","dateValue","timestampValue","normalized","enumValue","values","text$4","matches","hints","textValue","jsonValue","convertCell","singularOf","views","resource","pluralOf","convertRow","context","data","problems","relations","plan","by","matchBy","converted","match","foundOne","keys","finding","named","isBlank","prepareRows","wanted","relation","id","written","found","existing","prepared","sampleRows","previewRows","readHead","chunks","source","sheet","first","dataRows","chunk","checkImport","check","signal","onProgress","refusal","error","runImport","progress","write","pending","ops","client","result","results","index","refused","queue","flush","all","cancelled","listedProblems","downloadRows","fileName","ProblemList","ImportChecking","ImportCheckStep","shown","columns","extensions","mediaTypes","androidMediaTypes","isAndroid","userAgent","importAccept","ImportSelect","className","onChange","event","option","help","ImportFileStep","reading","chosen","onChoose","file","sheets","onSheet","count","ImportProgressStep","done","cancelling","total","ImportSummary","stopped","where","valuesPerRequest","lookupKey","createLookups","known","foundOf","missing","asked","filter","pageToken","page","clientFor","record","chunkRows","startWorker","worker","replies","waiting","resolve","failed","request","workerSheetSource","reply"],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/file-spreadsheet.mjs","../../../src/app/import/failed-rows.ts","../../../src/app/import/import-counts.tsx","../../../src/app/import/mapping.ts","../../../src/app/import/convert.ts","../../../src/app/import/prepare-rows.ts","../../../src/app/import/run-import.ts","../../../src/app/import/import-check-step.tsx","../../../src/app/import/import-accept.ts","../../../src/app/import/import-select.tsx","../../../src/app/import/import-file-step.tsx","../../../src/app/import/import-result-step.tsx","../../../src/app/import/lookups.ts","../../../src/app/import/sheet-source.ts"],"sourcesContent":["/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"file-spreadsheet\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\",\n key: \"1oefj6\"\n }\n ],\n [\"path\", { d: \"M14 2v5a1 1 0 0 0 1 1h5\", key: \"wfsgrz\" }],\n [\"path\", { d: \"M8 13h2\", key: \"yr2amv\" }],\n [\"path\", { d: \"M14 13h2\", key: \"un5t4a\" }],\n [\"path\", { d: \"M8 17h2\", key: \"2yhykz\" }],\n [\"path\", { d: \"M14 17h2\", key: \"10kma7\" }]\n ]\n};\n__iconData.node;\nconst FileSpreadsheet = createLucideIcon(__iconData);\n\nexport { __iconData, FileSpreadsheet as default };\n//# sourceMappingURL=file-spreadsheet.mjs.map\n","import type { FailedRow } from './run-import'\nimport { cellText } from './sheet-cell'\nimport { text as message } from './messages'\n\n// A CSV field, quoted when it holds a delimiter, a quote or a line break\nconst csvField = (text: string) => (/[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text)\n\n/**\n * The rows an import did not write as a CSV file to fix and import again: the file's own columns, then the row's line in\n * the file and why it was not written. Sorted by line, with a byte order mark so spreadsheet programs read it as UTF-8.\n */\nexport const failedRowsCsv = (headers: string[], rows: FailedRow[]) => {\n const lines = [...rows]\n .sort((a, b) => a.line - b.line)\n .map((row) => [...headers.map((_, column) => cellText(row.cells[column] ?? null)), String(row.line), row.problems.join('; ')])\n return `${[[...headers, message('line'), message('problems')], ...lines].map((fields) => fields.map(csvField).join(',')).join('\\r\\n')}\\r\\n`\n}\n","import { formatTag } from '../../locale/active-locale'\n\n/** Counts side by side, each under its label, such as the rows an import created and updated. */\nexport const ImportCounts = ({ label, counts }: { label: string; counts: Array<[label: string, value: number]> }) => (\n <dl aria-label={label} className=\"grid grid-cols-2 gap-3 sm:grid-cols-4\">\n {counts.map(([name, value]) => (\n <div key={name} className=\"rounded-lg border px-3 py-2\">\n <dt className=\"text-xs text-muted-foreground\">{name}</dt>\n <dd className=\"text-lg font-semibold tabular-nums\">{value.toLocaleString(formatTag())}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\n\n/** What an import does with each row: create a record, update the one it matches, or update it when there is one and create it when not. */\nexport type ImportMode = 'create' | 'update' | 'upsert'\n\n/** A column of the file and the field it fills; `matchBy` names the field of the related record a relation is found by. */\nexport type ColumnMapping = { column: number; field: string; matchBy?: string }\n\n/** How a field reads in the import: its view's label, as everywhere else in the app. */\nexport const fieldLabel = (view: ViewModel | undefined, name: string) => view?.fields[name]?.label ?? humanize(name)\n\n// Types whose values a cell can hold: not structured data or files\nconst importableTypes = new Set<FieldModel['type']>(['text', 'integer', 'bigint', 'decimal', 'boolean', 'date', 'timestamp', 'uuid', 'enum', 'relation', 'currency', 'country'])\n\n// A relation an import can fill: one whose target is a resource the app knows, with a key of one field\nconst relationTarget = (field: FieldModel, resources: Record<string, ResourceModel>) => {\n const target = field.relation ? resources[field.relation.resource] : undefined\n return target?.primaryKey.length === 1 ? target : undefined\n}\n\n/**\n * The fields an import may write: not read-only, not the tenant, and of a type a cell can hold; a JSON field too when\n * the file is JSON, whose values it takes as they are.\n */\nexport const importableFields = (model: ResourceModel, resources: Record<string, ResourceModel>, { json = false } = {}) =>\n Object.values(model.fields).filter((field) => {\n if (field.readOnly || field.name === model.tenant) return false\n if (field.type === 'json') return json\n if (!importableTypes.has(field.type)) return false\n return field.type !== 'relation' || relationTarget(field, resources) !== undefined\n })\n\n// Types a record can be found by, with an equality filter on the value\nconst matchableTypes = new Set<FieldModel['type']>(['text', 'integer', 'bigint', 'uuid', 'date', 'currency', 'country', 'enum'])\n\n/**\n * The fields records of `model` can be found by: its key when it is one field, then the filterable fields whose values\n * single records out, such as an email or an order number. The user says which is unique; a value that matches several\n * records is an error on its row.\n */\nexport const matchFields = (model: ResourceModel) => {\n const key = model.primaryKey.length === 1 ? [model.fields[model.primaryKey[0]!]!] : []\n const others = Object.values(model.fields).filter((field) => field.filterable && !field.sensitive && matchableTypes.has(field.type) && !model.primaryKey.includes(field.name))\n return [...key, ...others]\n}\n\n/** The resource a relation field points at, when an import can fill it. */\nexport const relationModel = (field: FieldModel, resources: Record<string, ResourceModel>) => relationTarget(field, resources)\n\n/** Whether a new record needs the field: it can be neither empty nor filled in by a default. */\nexport const requiredOnCreate = (field: FieldModel) => !field.nullable && !field.default\n\n// Lower case without spaces, underscores or dashes: \"Customer email\", \"customer_email\" and \"CustomerEmail\" are one\nconst normalized = (text: string) => text.toLowerCase().replace(/[\\s_-]+/g, '')\n\n/**\n * Each column whose header is a field's label or name, ignoring case and spacing, mapped to that field; a field takes\n * the first column that matches it, and a column that matches none is skipped.\n */\nexport const autoMapping = (headers: string[], fields: FieldModel[], view: ViewModel | undefined): ColumnMapping[] => {\n const taken = new Set<string>()\n return headers.flatMap((header, column) => {\n const text = normalized(header)\n if (text === '') return []\n const field = fields.find((candidate) => !taken.has(candidate.name) && (normalized(fieldLabel(view, candidate.name)) === text || normalized(candidate.name) === text))\n if (!field) return []\n taken.add(field.name)\n return [{ column, field: field.name }]\n })\n}\n\n/** The fields a new record needs that no column fills, which a create, or a create-or-update, must have. */\nexport const unmappedRequired = (mode: ImportMode, fields: FieldModel[], mapping: ColumnMapping[]) => {\n if (mode === 'update') return []\n const mapped = new Set(mapping.map((entry) => entry.field))\n return fields.filter((field) => requiredOnCreate(field) && !mapped.has(field.name))\n}\n","import { enumLabel, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { parseNumberText, type DecimalSeparator } from '../../format/number-text'\nimport { cellText, isEmptyCell, isSheetDate, isSheetJson, type SheetCell } from './sheet-cell'\nimport { text as message } from './messages'\n\n/**\n * How the file writes what is ambiguous in text: the decimal separator of numbers (`1,234.5` or `1.234,5`), and whether\n * a date such as 03/04/2026 starts with the day or the month. ISO dates (2026-04-03) read the same either way.\n */\nexport type ConvertOptions = {\n decimal: DecimalSeparator\n dateOrder: 'dmy' | 'mdy'\n /** A true or false cell fills a text field as the file shows it (TRUE or FALSE), as in a table made from the file. */\n booleanText?: boolean\n}\n\nexport type Converted = { ok: true; value: unknown } | { ok: false; problem: string }\n\nconst ok = (value: unknown): Converted => ({ ok: true, value })\nconst problem = (text: string): Converted => ({ ok: false, problem: text })\nconst quoted = (cell: SheetCell) => `“${cellText(cell)}”`\n\nconst toNumberText = (cell: SheetCell, options: ConvertOptions) => {\n if (typeof cell === 'number') return String(cell)\n if (typeof cell === 'string') return parseNumberText(cell, options.decimal)\n return undefined\n}\n\nconst integerValue = (field: FieldModel, cell: SheetCell, options: ConvertOptions): Converted => {\n const text = toNumberText(cell, options)\n if (text === undefined) return problem(message('notNumber', { cell: quoted(cell) }))\n const [whole, fraction = ''] = text.split('.')\n if (/[1-9]/.test(fraction) || /e/i.test(text)) return problem(message('notWholeNumber', { cell: quoted(cell) }))\n if (field.type === 'bigint') return ok(String(BigInt(whole!)))\n const value = Number(whole)\n return Number.isSafeInteger(value) ? ok(value) : problem(message('tooLarge', { cell: quoted(cell) }))\n}\n\nconst decimalValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const text = toNumberText(cell, options)\n return text === undefined ? problem(message('notNumber', { cell: quoted(cell) })) : ok(text)\n}\n\nconst trueWords = new Set(['true', 'yes', '1'])\nconst falseWords = new Set(['false', 'no', '0'])\n\nconst booleanValue = (cell: SheetCell): Converted => {\n if (typeof cell === 'boolean') return ok(cell)\n const text = typeof cell === 'string' || typeof cell === 'number' ? String(cell).trim().toLowerCase() : ''\n if (trueWords.has(text)) return ok(true)\n if (falseWords.has(text)) return ok(false)\n return problem(message('notBoolean', { cell: quoted(cell) }))\n}\n\nconst pad = (value: number) => String(value).padStart(2, '0')\n\n// A calendar date that exists, as YYYY-MM-DD\nconst calendarDate = (year: number, month: number, day: number) => {\n const at = new Date(Date.UTC(year, month - 1, day))\n if (at.getUTCFullYear() !== year || at.getUTCMonth() !== month - 1 || at.getUTCDate() !== day) return undefined\n return `${year}-${pad(month)}-${pad(day)}`\n}\n\ntype WallTime = { date: string; time?: string; zone?: string }\n\nconst timePattern = '(\\\\d{1,2}):(\\\\d{2})(?::(\\\\d{2})(?:\\\\.\\\\d+)?)?'\n\n// A date and time written as text: ISO (2026-04-03, 2026-04-03T14:30:00+02:00) or day and month in the file's order\n// (03/04/2026 14:30), with a four-digit year\nconst readWallTime = (text: string, order: ConvertOptions['dateOrder']): WallTime | undefined => {\n const iso = new RegExp(`^(\\\\d{4})[-/](\\\\d{1,2})[-/](\\\\d{1,2})(?:[T ]${timePattern}(Z|[+-]\\\\d{2}:?\\\\d{2})?)?$`).exec(text.trim())\n const local = new RegExp(`^(\\\\d{1,2})[./-](\\\\d{1,2})[./-](\\\\d{4})(?: ${timePattern})?$`).exec(text.trim())\n if (!iso && !local) return undefined\n const [year, month, day] = iso ? [iso[1], iso[2], iso[3]].map(Number) : order === 'dmy' ? [local![3], local![2], local![1]].map(Number) : [local![3], local![1], local![2]].map(Number)\n const date = calendarDate(year!, month!, day!)\n if (!date) return undefined\n const [hours, minutes, seconds = '0'] = (iso ? iso.slice(4, 7) : local!.slice(4, 7)) as [string | undefined, string | undefined, string | undefined]\n if (hours === undefined) return { date }\n if (Number(hours) > 23 || Number(minutes) > 59 || Number(seconds) > 59) return undefined\n return { date, time: `${pad(Number(hours))}:${minutes}:${pad(Number(seconds))}`, zone: iso?.[7] }\n}\n\nconst wallTimeOf = (cell: SheetCell, options: ConvertOptions): WallTime | undefined => {\n if (isSheetDate(cell)) {\n const [date, time] = cell.date.split('T')\n return { date: date!, time }\n }\n return typeof cell === 'string' ? readWallTime(cell, options.dateOrder) : undefined\n}\n\nconst notDate = (cell: SheetCell, options: ConvertOptions) =>\n problem(message('notDate', { cell: quoted(cell), dayFirst: options.dateOrder === 'dmy' }))\n\nconst dateValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const at = wallTimeOf(cell, options)\n if (!at) return notDate(cell, options)\n if (at.time && at.time !== '00:00:00') return problem(message('hasTime', { cell: quoted(cell) }))\n return ok(at.date)\n}\n\n// A time without a zone is the browser's local time, as the person reading the sheet sees it\nconst timestampValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const at = wallTimeOf(cell, options)\n if (!at) return notDate(cell, options)\n if (at.zone) return ok(new Date(`${at.date}T${at.time}${at.zone === 'Z' ? 'Z' : at.zone.replace(/^([+-]\\d{2})(\\d{2})$/, '$1:$2')}`).toISOString())\n const [year, month, day] = at.date.split('-').map(Number)\n const [hours, minutes, seconds] = (at.time ?? '00:00:00').split(':').map(Number)\n return ok(new Date(year!, month! - 1, day!, hours, minutes, seconds).toISOString())\n}\n\nconst normalized = (text: string) => text.trim().toLowerCase().replace(/\\s+/g, ' ')\n\nconst enumValue = (field: FieldModel, hints: FieldViewModel | undefined, cell: SheetCell): Converted => {\n const values = field.enumValues ?? []\n const text = normalized(cellText(cell))\n const matches = values.filter((value) => normalized(value) === text || normalized(enumLabel(value, hints?.valueLabels)) === text)\n if (matches.length === 1) return ok(matches[0])\n if (matches.length > 1) return problem(message('severalValues', { cell: quoted(cell), values: matches.map((value) => enumLabel(value, hints?.valueLabels)).join(', ') }))\n return problem(message('notOneOf', { cell: quoted(cell), values: values.map((value) => enumLabel(value, hints?.valueLabels)).join(', ') }))\n}\n\nconst textValue = (cell: SheetCell, options: ConvertOptions): Converted =>\n typeof cell === 'boolean' && !options.booleanText ? problem(message('notText', { cell: quoted(cell) })) : ok(cellText(cell))\n\n// A JSON file's value as it is: a nested object or array, or a string, number or boolean\nconst jsonValue = (cell: SheetCell): Converted => (isSheetJson(cell) ? ok(cell.json) : ok(cell))\n\n/**\n * The value a cell gives a field, as the API takes it, or the problem that keeps it from being one: never a guess, and an\n * empty cell is null, never a default. A relation's cell is the value of the field its records are found by, so it\n * converts as that field (`convertCell(targetField, ...)`).\n */\nexport const convertCell = (field: FieldModel, hints: FieldViewModel | undefined, cell: SheetCell, options: ConvertOptions): Converted => {\n if (isEmptyCell(cell)) return field.nullable ? ok(null) : problem(message('emptyRequired'))\n if (field.type === 'json') return jsonValue(cell)\n if (isSheetJson(cell)) return problem(message('nestedValue', { cell: quoted(cell) }))\n switch (field.type) {\n case 'integer':\n case 'bigint':\n return integerValue(field, cell, options)\n case 'decimal':\n return decimalValue(cell, options)\n case 'boolean':\n return booleanValue(cell)\n case 'date':\n return dateValue(cell, options)\n case 'timestamp':\n return timestampValue(cell, options)\n case 'enum':\n return enumValue(field, hints, cell)\n case 'text':\n case 'uuid':\n case 'currency':\n case 'country':\n return textValue(cell, options)\n default:\n throw new Error(`Not implemented: importing ${field.type} fields, which importableFields leaves out`)\n }\n}\n","import type { BatchOp } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\nimport { convertCell, type ConvertOptions } from './convert'\nimport type { Lookups } from './lookups'\nimport { fieldLabel, relationModel, type ColumnMapping, type ImportMode } from './mapping'\nimport { cellText, isEmptyCell, type SheetCell, type SheetRow } from './sheet-cell'\nimport { text } from './messages'\n\n/** What an import does: its mode, which column fills which field, the column records are found by, and how the file writes numbers and dates. */\nexport type ImportPlan = {\n mode: ImportMode\n columns: ColumnMapping[]\n /** For an update or create-or-update: the column whose value finds the record, by the field it holds. */\n match?: { column: number; field: string }\n options: ConvertOptions\n}\n\n/** The app's models, and the lookups that find related and updated records. */\nexport type ImportContext = {\n model: ResourceModel\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n lookups: Lookups\n}\n\n/**\n * A row as the import will write it: the write, or the problems that keep it from being written. `values` are the\n * converted values by field, a relation's as the file names the record, for the preview.\n */\nexport type PreparedRow = { line: number; cells: SheetCell[]; values: Record<string, unknown>; problems: string[]; op?: BatchOp }\n\nconst singularOf = (views: Record<string, ViewModel>, resource: string) => views[resource]?.names?.singular ?? humanize(resource)\nconst pluralOf = (views: Record<string, ViewModel>, resource: string) => views[resource]?.names?.plural ?? humanize(resource)\n\ntype Finding = { model: ResourceModel; field: string; value: unknown }\n\n// A row's converted values and the records it needs found, before any lookup\nconst convertRow = (row: SheetRow, plan: ImportPlan, context: ImportContext) => {\n const { model, resources, views } = context\n const view = views[model.name]\n const values: Record<string, unknown> = {}\n const data: Record<string, unknown> = {}\n const problems: string[] = []\n const relations: Array<{ field: string; finding: Finding }> = []\n for (const { column, field: name, matchBy } of plan.columns) {\n const field = model.fields[name]!\n const cell = row.cells[column] ?? null\n const label = fieldLabel(view, name)\n const target = relationModel(field, resources)\n if (target && !isEmptyCell(cell)) {\n const by = matchBy ?? target.primaryKey[0]!\n const converted = convertCell(target.fields[by]!, views[target.name]?.fields[by], cell, plan.options)\n if (!converted.ok) problems.push(`${label}: ${converted.problem}`)\n else relations.push({ field: name, finding: { model: target, field: by, value: converted.value } })\n values[name] = cellText(cell)\n continue\n }\n const converted = convertCell(field, view?.fields[name], cell, plan.options)\n if (!converted.ok) problems.push(`${label}: ${converted.problem}`)\n else data[name] = values[name] = converted.value\n }\n let match: Finding | undefined\n if (plan.match && plan.mode !== 'create') {\n const field = model.fields[plan.match.field]!\n const converted = convertCell({ ...field, nullable: false }, view?.fields[field.name], row.cells[plan.match.column] ?? null, plan.options)\n if (!converted.ok) problems.push(`${fieldLabel(view, field.name)}: ${converted.problem}`)\n else match = { model, field: field.name, value: converted.value }\n }\n return { values, data, problems, relations, match }\n}\n\n// What a lookup found for a value: the one record's key, or why there is none: \"no customer has email “x”\", \"2\n// customers have email “x”\"\nconst foundOne = (context: ImportContext, finding: Finding) => {\n const keys = context.lookups.keysOf(finding.model.name, finding.field, finding.value)\n const named = `${fieldLabel(context.views[finding.model.name], finding.field).toLowerCase()} “${String(finding.value)}”`\n if (keys.length === 1) return { key: keys[0] }\n if (keys.length === 0) return { none: text('noneHas', { singular: singularOf(context.views, finding.model.name), named }) }\n return { several: text('severalHave', { count: keys.length, plural: pluralOf(context.views, finding.model.name), named }) }\n}\n\nconst isBlank = (row: SheetRow) => row.cells.every(isEmptyCell)\n\n/**\n * The rows of a chunk as writes: each mapped cell converted, related records and the records to update found (asked\n * for together), and the write each row makes, or the problems that keep it out. Rows with no value at all are left\n * out.\n */\nexport const prepareRows = async (rows: SheetRow[], plan: ImportPlan, context: ImportContext): Promise<PreparedRow[]> => {\n const { model, views } = context\n const converted = rows.filter((row) => !isBlank(row)).map((row) => ({ row, ...convertRow(row, plan, context) }))\n\n const wanted = new Map<string, { model: ResourceModel; field: string; values: unknown[] }>()\n for (const finding of converted.flatMap((entry) => [...entry.relations.map((relation) => relation.finding), ...(entry.match ? [entry.match] : [])])) {\n const id = `${finding.model.name}.${finding.field}`\n if (!wanted.has(id)) wanted.set(id, { model: finding.model, field: finding.field, values: [] })\n wanted.get(id)!.values.push(finding.value)\n }\n for (const { model: target, field, values } of wanted.values()) await context.lookups.load(target, field, values)\n\n return converted.map(({ row, values, data, problems, relations, match }) => {\n const written = { ...data }\n for (const { field, finding } of relations) {\n const found = foundOne(context, finding)\n if ('key' in found) written[field] = found.key\n else problems.push(`${fieldLabel(views[model.name], field)}: ${found.none ?? found.several}`)\n }\n // An update needs its record; a create-or-update creates one when none matches\n const existing = match && foundOne(context, match)\n if (existing?.several) problems.push(text('notOneRecord', { found: existing.several }))\n if (existing?.none && plan.mode === 'update') problems.push(text('nothingToUpdate', { found: existing.none }))\n const prepared = { line: row.line, cells: row.cells, values, problems }\n if (problems.length > 0) return prepared\n if (existing && 'key' in existing) return { ...prepared, op: { op: 'update', resource: model.name, key: existing.key as string | number, etag: '*', data: written } satisfies BatchOp }\n return { ...prepared, op: { op: 'create', resource: model.name, data: written } satisfies BatchOp }\n })\n}\n","import { isApiError, type BatchOp, type Client } from '@protobase/client'\nimport { fieldLabel } from './mapping'\nimport { prepareRows, type ImportContext, type ImportPlan, type PreparedRow } from './prepare-rows'\nimport { cellText, type SheetCell, type SheetRow } from './sheet-cell'\nimport type { SheetSource } from './sheet-source'\n\n/** How many data rows the mapping step shows under each column. */\nconst sampleRows = 5\n/** How many rows of the check the preview shows. */\nconst previewRows = 5\n/** Rows per batch write: each batch is one transaction. */\nexport const batchRows = 100\n\n/** The file's header row as text, and its first data rows. */\nexport type SheetHead = { headers: string[]; sample: SheetRow[] }\n\n/** The header and the first rows of a sheet, reading no further than its first chunk. */\nexport const readHead = async (source: SheetSource, sheet: string | undefined): Promise<SheetHead> => {\n const chunks = source.rows(sheet)\n const { value: first = [] } = await chunks.next()\n await chunks.return(undefined)\n const [header, ...rows] = first\n return { headers: (header?.cells ?? []).map(cellText), sample: rows.slice(0, sampleRows) }\n}\n\n// The data rows of a sheet, chunk by chunk, without its header row\nasync function* dataRows(source: SheetSource, sheet: string | undefined) {\n let header = true\n for await (const chunk of source.rows(sheet)) {\n yield header ? chunk.slice(1) : chunk\n header = false\n }\n}\n\n/** A row the import did not write, with the line it has in the file and why. */\nexport type FailedRow = { line: number; cells: SheetCell[]; problems: string[] }\n\n/** What the check found: how many rows would create or update a record, the rows with problems, and the first rows as they would be written. */\nexport type ImportCheck = { rows: number; creates: number; updates: number; problems: FailedRow[]; preview: PreparedRow[] }\n\n/** Reads the whole file and prepares every row as the import would, writing nothing; `onProgress` gets the rows read so far. */\nexport const checkImport = async (source: SheetSource, sheet: string | undefined, plan: ImportPlan, context: ImportContext, onProgress: (rows: number) => void, signal?: AbortSignal) => {\n const check: ImportCheck = { rows: 0, creates: 0, updates: 0, problems: [], preview: [] }\n for await (const chunk of dataRows(source, sheet)) {\n signal?.throwIfAborted()\n for (const row of await prepareRows(chunk, plan, context)) {\n check.rows++\n if (check.preview.length < previewRows) check.preview.push(row)\n if (row.op?.op === 'create') check.creates++\n else if (row.op?.op === 'update') check.updates++\n else check.problems.push({ line: row.line, cells: row.cells, problems: row.problems })\n }\n onProgress(check.rows)\n }\n return check\n}\n\n/** Where an import stands: what it wrote, skipped for problems and the server refused, and the rows it did not write. */\nexport type ImportProgress = { created: number; updated: number; skipped: number; failed: number; notWritten: FailedRow[] }\n\n// Why the server refused a write: its field errors under the fields' labels, else its message\nconst refusal = (error: Error, context: ImportContext) => {\n if (!isApiError(error)) return [error.message]\n const fields = error.errors.filter((entry) => entry.field)\n if (fields.length === 0) return [error.message]\n return fields.map((entry) => `${fieldLabel(context.views[context.model.name], entry.field!)}: ${entry.message}`)\n}\n\nexport type RunOptions = {\n client: Client\n /** Called after every batch, with the counts so far. */\n onProgress: (progress: ImportProgress) => void\n /** Asked before every batch: true stops the import there, keeping what earlier batches wrote. */\n cancelled: () => boolean\n}\n\n/**\n * Writes the file's rows in batches of `batchRows`, each batch one transaction through `POST :batchWrite`, with the\n * same validation and access as single writes. A row the server refuses is set aside with the reason, and the rest of\n * its batch is sent again, so every row that can be written is. Rows with problems are skipped. Answers `cancelled`\n * when stopped between batches; an error other than a refused row stops the import and is thrown.\n */\nexport const runImport = async (source: SheetSource, sheet: string | undefined, plan: ImportPlan, context: ImportContext, { client, onProgress, cancelled }: RunOptions) => {\n const progress: ImportProgress = { created: 0, updated: 0, skipped: 0, failed: 0, notWritten: [] }\n\n const write = async (rows: PreparedRow[]) => {\n const pending = [...rows]\n while (pending.length > 0) {\n const ops = pending.map((row) => row.op!) as BatchOp[]\n try {\n const { results } = await client.batchWrite(ops)\n for (const result of results) {\n if (result.op === 'create') progress.created++\n else if (result.op === 'update') progress.updated++\n }\n return\n } catch (error) {\n const index = isApiError(error) ? error.operation : undefined\n if (index === undefined || !pending[index]) throw error\n const [refused] = pending.splice(index, 1)\n progress.failed++\n progress.notWritten.push({ line: refused!.line, cells: refused!.cells, problems: refusal(error as Error, context) })\n }\n }\n }\n\n let queue: PreparedRow[] = []\n const flush = async (all: boolean) => {\n while (queue.length >= batchRows || (all && queue.length > 0)) {\n if (cancelled()) return false\n await write(queue.splice(0, batchRows))\n onProgress({ ...progress })\n }\n return true\n }\n\n for await (const chunk of dataRows(source, sheet)) {\n for (const row of await prepareRows(chunk, plan, context)) {\n if (row.op) queue.push(row)\n else {\n progress.skipped++\n progress.notWritten.push({ line: row.line, cells: row.cells, problems: row.problems })\n }\n }\n if (!(await flush(false))) return { ...progress, cancelled: true }\n }\n if (!(await flush(true))) return { ...progress, cancelled: true }\n return { ...progress, cancelled: false }\n}\n","import { Download } from 'lucide-react'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { saveFile } from '../../lib/save-file'\nimport { Button } from '../../primitives/button'\nimport { Spinner } from '../../primitives/spinner'\nimport { failedRowsCsv } from './failed-rows'\nimport { ImportCounts } from './import-counts'\nimport { fieldLabel, relationModel, type ColumnMapping } from './mapping'\nimport { batchRows, type FailedRow, type ImportCheck } from './run-import'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** How many rows with problems the check lists; the file of them holds every one. */\nconst listedProblems = 50\n\n/** Saves the rows with their problems as a CSV named after the imported file. */\nexport const downloadRows = (fileName: string | undefined, headers: string[], rows: FailedRow[]) =>\n saveFile(failedRowsCsv(headers, rows), text('notImportedFile', { name: (fileName ?? 'import').replace(/\\.[^.]+$/, '') }), 'text/csv')\n\n/** The rows with what keeps each from being imported, at most `listedProblems` of them. */\nexport const ProblemList = ({ rows }: { rows: FailedRow[] }) => (\n <ul aria-label={text('rowsNotImported')} className=\"flex flex-col gap-1 text-body\">\n {rows.slice(0, listedProblems).map((row) => (\n <li key={row.line}>\n <span className=\"font-medium\">{text('rowProblems', { line: row.line })}</span> {row.problems.join('; ')}\n </li>\n ))}\n {rows.length > listedProblems && <li className=\"text-muted-foreground\">{text('andMore', { count: (rows.length - listedProblems).toLocaleString(formatTag()) })}</li>}\n </ul>\n)\n\nexport const ImportChecking = ({ rows }: { rows: number }) => (\n <p className=\"flex items-center gap-2 text-muted-foreground\" role=\"status\">\n <Spinner className=\"size-3.5\" />\n {text('checkingRows', { count: rows.toLocaleString(formatTag()) })}\n </p>\n)\n\ntype ImportCheckStepProps = {\n check: ImportCheck\n model: ResourceModel\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n columns: ColumnMapping[]\n headers: string[]\n fileName?: string\n}\n\n/**\n * What the import would do, before it writes anything: how many rows create or update a record, the first rows as they\n * would be written, and every row with problems, which the import skips.\n */\nexport const ImportCheckStep = ({ check, model, resources, views, columns, headers, fileName }: ImportCheckStepProps) => {\n const view = views[model.name]\n const shown = columns.map((column) => model.fields[column.field]!)\n return (\n <div className=\"flex flex-col gap-4\">\n <ImportCounts\n label={text('check')}\n counts={[\n [text('rows'), check.rows],\n [text('toCreate'), check.creates],\n [text('toUpdate'), check.updates],\n [text('withProblems'), check.problems.length],\n ]}\n />\n {check.preview.length > 0 && (\n // A table as wide as its columns scrolls sideways inside the dialog, which scrolls down as a whole\n <div className=\"overflow-x-auto rounded-lg border\">\n <table aria-label={text('firstRows')} className=\"w-full text-left text-body\">\n <thead className=\"bg-muted text-muted-foreground\">\n <tr>\n <th className=\"px-2 py-1.5 font-medium\">{text('row')}</th>\n {shown.map((field) => (\n <th key={field.name} className=\"whitespace-nowrap px-2 py-1.5 font-medium\">\n {fieldLabel(view, field.name)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody className=\"divide-y\">\n {check.preview.map((row) => (\n <tr key={row.line} className={row.problems.length > 0 ? 'bg-danger-soft' : undefined}>\n <td className=\"px-2 py-1.5 tabular-nums text-muted-foreground\">{row.line}</td>\n {shown.map((field) => (\n <td key={field.name} className=\"max-w-48 truncate px-2 py-1.5\">\n {relationModel(field, resources) ? String(row.values[field.name] ?? '—') : field.name in row.values ? displayValue(field, row.values[field.name], view?.fields[field.name]) : ''}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n {check.problems.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-center justify-between gap-2\">\n <h3 className=\"font-medium\">{text('problemRows')}</h3>\n <Button size=\"sm\" onClick={() => downloadRows(fileName, headers, check.problems)}>\n <Download className=\"size-3.5\" />\n {text('download')}\n </Button>\n </div>\n <ProblemList rows={check.problems} />\n </div>\n )}\n <p className=\"text-xs text-muted-foreground\">{text('batches', { size: batchRows })}</p>\n </div>\n )\n}\n","// What an import's file input accepts: its extensions, with the media types a picker that filters by type needs.\n\nconst extensions = ['.xlsx', '.csv', '.json']\n\nconst mediaTypes = ['text/csv', 'application/json', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']\n\n/**\n * Android's picker filters by media type alone, turning each extension into the one type Android maps it to, so it\n * greys out a file whose provider labels it otherwise: a CSV as `text/comma-separated-values`, `application/csv`,\n * `text/x-csv`, `application/vnd.ms-excel` or `text/plain`, and any file a provider does not know as\n * `application/octet-stream`. The import reads a file by its name, so these are safe to offer there. Elsewhere the\n * picker matches extensions, and the generic types would offer every file.\n */\nconst androidMediaTypes = ['text/comma-separated-values', 'application/csv', 'text/x-csv', 'application/vnd.ms-excel', 'text/plain', 'application/octet-stream']\n\nconst isAndroid = (userAgent: string) => /\\bAndroid\\b/.test(userAgent)\n\n/** The `accept` of an import's file input on the device with this user agent: `.xlsx`, CSV and JSON files. */\nexport const importAccept = (userAgent: string) => [...extensions, ...mediaTypes, ...(isAndroid(userAgent) ? androidMediaTypes : [])].join(',')\n","import { useId, type ReactNode } from 'react'\nimport { cn } from '../../lib/cn'\n\nexport type ImportSelectOption = { value: string; label: string }\n\ntype ImportSelectProps = {\n label: string\n /** The select's name for assistive technology, when the visible label alone does not say which it is. */\n name?: string\n value: string\n options: ImportSelectOption[]\n onChange: (value: string) => void\n /** A line under the control. */\n help?: ReactNode\n className?: string\n}\n\n/** A labelled native select, as the field editors draw theirs. */\nexport const ImportSelect = ({ label, name, value, options, onChange, help, className }: ImportSelectProps) => {\n const id = useId()\n return (\n <div className={cn('flex min-w-0 flex-col gap-1.5', className)}>\n <label htmlFor={id} className=\"font-medium\">\n {label}\n </label>\n <select\n id={id}\n aria-label={name}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"h-8 w-full min-w-0 rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 max-sm:min-h-11\"\n >\n {options.map((option) => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n {help && <p className=\"text-xs text-muted-foreground\">{help}</p>}\n </div>\n )\n}\n","import { FileSpreadsheet } from 'lucide-react'\nimport { useId } from 'react'\nimport { Spinner } from '../../primitives/spinner'\nimport { importAccept } from './import-accept'\nimport { ImportSelect } from './import-select'\nimport { text } from './messages'\n\ntype ImportFileStepProps = {\n file?: File\n sheets: string[]\n sheet?: string\n reading: boolean\n onChoose: (file: File) => void\n onSheet: (sheet: string) => void\n}\n\n/** The file to import, an .xlsx workbook, a CSV or a JSON file, and the sheet to read from a workbook with several. */\nexport const ImportFileStep = ({ file, sheets, sheet, reading, onChoose, onSheet }: ImportFileStepProps) => {\n const id = useId()\n return (\n <div className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-1.5\">\n <label htmlFor={id} className=\"font-medium\">\n {text('file')}\n </label>\n <input\n id={id}\n type=\"file\"\n accept={importAccept(globalThis.navigator?.userAgent ?? '')}\n disabled={reading}\n onChange={(event) => {\n const chosen = event.target.files?.[0]\n if (chosen) onChoose(chosen)\n }}\n className=\"file:mr-3 file:h-8 file:rounded-md file:border file:border-border-strong file:bg-background file:px-3 file:font-medium file:text-foreground max-sm:file:min-h-11\"\n />\n <p className=\"text-xs text-muted-foreground\">{text('fileHint')}</p>\n </div>\n {reading && (\n <p className=\"flex items-center gap-2 text-muted-foreground\" role=\"status\">\n <Spinner className=\"size-3.5\" />\n {text('reading', { name: file?.name ?? text('theFile') })}\n </p>\n )}\n {!reading && sheets.length > 1 && (\n <div className=\"flex items-end gap-3\">\n <FileSpreadsheet className=\"mb-2 size-4 shrink-0 text-muted-foreground\" />\n <ImportSelect className=\"flex-1\" label={text('sheet')} value={sheet ?? ''} options={sheets.map((name) => ({ value: name, label: name }))} onChange={onSheet} />\n </div>\n )}\n </div>\n )\n}\n","import { Download } from 'lucide-react'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport { downloadRows, ProblemList } from './import-check-step'\nimport { ImportCounts } from './import-counts'\nimport type { ImportProgress } from './run-import'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\nconst count = (value: number) => value.toLocaleString(formatTag())\n\n/** The rows written so far out of those to write, as a bar. */\nexport const ImportProgressStep = ({ progress, total, cancelling }: { progress: ImportProgress; total: number; cancelling: boolean }) => {\n const done = progress.created + progress.updated + progress.failed\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-baseline justify-between gap-2 text-xs\">\n <span className=\"text-muted-foreground\">{cancelling ? text('stopping') : text('saving')}</span>\n <span className=\"tabular-nums\">\n {count(done)} / {count(total)}\n </span>\n </div>\n <div role=\"progressbar\" aria-label={text('rowsSaved')} aria-valuenow={done} aria-valuemin={0} aria-valuemax={total} className=\"h-2 overflow-hidden rounded-full bg-muted\">\n <div className=\"h-full rounded-full bg-primary transition-[width]\" style={{ width: `${total > 0 ? Math.min(100, (done / total) * 100) : 0}%` }} />\n </div>\n </div>\n )\n}\n\ntype ImportSummaryProps = {\n result: ImportProgress & { cancelled: boolean }\n /** The error that stopped the import before its end. */\n stopped?: unknown\n headers: string[]\n fileName?: string\n}\n\n/** What the import did: created, updated, skipped and failed rows, and the rows it did not write with the reasons, to download. */\nexport const ImportSummary = ({ result, stopped, headers, fileName }: ImportSummaryProps) => (\n <div className=\"flex flex-col gap-4\">\n {stopped !== undefined && <ErrorBanner title={text('stopped')} error={stopped} />}\n {result.cancelled && <p role=\"status\">{text('cancelled')}</p>}\n <ImportCounts\n label={text('summary')}\n counts={[\n [text('created'), result.created],\n [text('updated'), result.updated],\n [text('skipped'), result.skipped],\n [text('failed'), result.failed],\n ]}\n />\n {result.notWritten.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-center justify-between gap-2\">\n <h3 className=\"font-medium\">{text('rowsNotImported')}</h3>\n <Button size=\"sm\" onClick={() => downloadRows(fileName, headers, result.notWritten)}>\n <Download className=\"size-3.5\" />\n {text('download')}\n </Button>\n </div>\n <p className=\"text-xs text-muted-foreground\">{text('notWrittenHint')}</p>\n <ProblemList rows={[...result.notWritten].sort((a, b) => a.line - b.line)} />\n </div>\n )}\n </div>\n)\n","import type { Client } from '@protobase/client'\nimport { createWhere, printFilter, type ResourceModel } from '@protobase/schema'\n\nconst where = createWhere()\n// Values per request, so the filter stays short\nconst valuesPerRequest = 100\n\n/** The keys of the records whose field holds each value: none, one, or several when the value singles out no record. */\nexport type Found = Map<string, unknown[]>\n\n/** A value as the lookups compare it: the API answers numbers as numbers and the rest as text. */\nexport const lookupKey = (value: unknown) => String(value)\n\n/**\n * Finds records by the value of a field, for the relations of an import's rows and the records it updates: each value\n * is asked for once per import, a hundred at a time, and remembered.\n */\nexport const createLookups = (clientFor: (resource: string) => Client) => {\n const known = new Map<string, Found>()\n\n const foundOf = (resource: string, field: string) => {\n const id = `${resource}.${field}`\n if (!known.has(id)) known.set(id, new Map())\n return known.get(id)!\n }\n\n /** Asks the API for the values not asked for yet; the user reads only the records they may list. */\n const load = async (model: ResourceModel, field: string, values: unknown[]) => {\n const found = foundOf(model.name, field)\n const missing = [...new Map(values.filter((value) => !found.has(lookupKey(value))).map((value) => [lookupKey(value), value])).values()]\n const key = model.primaryKey[0]!\n for (let at = 0; at < missing.length; at += valuesPerRequest) {\n const asked = missing.slice(at, at + valuesPerRequest)\n for (const value of asked) found.set(lookupKey(value), [])\n const filter = printFilter(where.in(field, asked as never[]))\n let pageToken: string | undefined\n do {\n const page = await clientFor(model.name).list(model.name, { filter, fields: [...new Set([key, field])], pageSize: 1000, pageToken })\n for (const record of page.items as Record<string, unknown>[]) found.get(lookupKey(record[field]))?.push(record[key])\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n }\n }\n\n /** The keys of the records found by the value, once `load` asked for it. */\n const keysOf = (resource: string, field: string, value: unknown) => foundOf(resource, field).get(lookupKey(value)) ?? []\n\n return { load, keysOf }\n}\n\nexport type Lookups = ReturnType<typeof createLookups>\n","import type { ParseReply, ParseRequest } from './parse-messages'\nimport type { SheetRow } from './sheet-cell'\nimport { activeLocale } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** A chosen file as an import reads it: its sheet names, and its rows (the header first) in chunks. */\nexport type SheetSource = {\n sheets: () => Promise<string[]>\n rows: (sheet: string | undefined) => AsyncGenerator<SheetRow[]>\n}\n\n/** How many rows the worker sends at a time. */\nconst chunkRows = 500\n\n// A parse worker, with its replies taken one at a time\nconst startWorker = () => {\n const worker = new Worker(new URL('./parse-worker.ts', import.meta.url), { type: 'module' })\n const replies: ParseReply[] = []\n let waiting: ((reply: ParseReply) => void) | undefined\n worker.onmessage = (event: MessageEvent<ParseReply>) => {\n if (waiting) {\n const resolve = waiting\n waiting = undefined\n resolve(event.data)\n } else replies.push(event.data)\n }\n worker.onerror = (event) => {\n event.preventDefault()\n const failed: ParseReply = { type: 'error', message: text('unreadable') }\n if (waiting) waiting(failed)\n else replies.push(failed)\n }\n const send = (request: ParseRequest) => worker.postMessage(request)\n const receive = () => (replies.length > 0 ? Promise.resolve(replies.shift()!) : new Promise<ParseReply>((resolve) => (waiting = resolve)))\n return { send, receive, stop: () => worker.terminate() }\n}\n\n/** The file read by a Web Worker, so parsing never holds up the page; each read has a worker of its own. */\nexport const workerSheetSource = (file: File): SheetSource => ({\n sheets: async () => {\n const worker = startWorker()\n try {\n worker.send({ type: 'sheets', file, locale: activeLocale() })\n const reply = await worker.receive()\n if (reply.type === 'error') throw new Error(reply.message)\n if (reply.type !== 'sheets') throw new Error(`The parse worker answered ${reply.type} to a request for sheets`)\n return reply.sheets\n } finally {\n worker.stop()\n }\n },\n rows: async function* (sheet) {\n const worker = startWorker()\n try {\n worker.send({ type: 'read', file, sheet, chunk: chunkRows, locale: activeLocale() })\n for (;;) {\n const reply = await worker.receive()\n if (reply.type === 'error') throw new Error(reply.message)\n if (reply.type === 'end') return\n if (reply.type !== 'rows') throw new Error(`The parse worker answered ${reply.type} to a read`)\n yield reply.rows\n worker.send({ type: 'next' })\n }\n } finally {\n worker.stop()\n }\n },\n})\n\n/** Rows already in memory as a source, for tests and stories. */\nexport const memorySheetSource = (rows: SheetRow[], sheets: string[] = []): SheetSource => ({\n sheets: async () => sheets,\n rows: async function* () {\n for (let at = 0; at < rows.length; at += chunkRows) yield rows.slice(at, at + chunkRows)\n },\n})\n"],"ignoreList":[0],"mappings":"iyBASA,IAAMiC,EAAa,CACjB,KAAM,mBACN,KAAM,GACN,KAAM,CACJ,CACE,OACA,CACE,EAAG,iHACH,IAAK,QACP,CACF,EACA,CAAC,OAAQ,CAAE,EAAG,0BAA2B,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,EACxC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,EACzC,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,EACxC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,CAC3C,CACF,EACAA,EAAW,KACX,IAAMC,GAAkBpB,EAAiBmB,CAAU,wBCvB7CI,GAAY,GAAkB,WAAW,KAAKR,CAAI,EAAI,IAAIA,EAAK,QAAQ,KAAM,IAAI,EAAE,GAAKA,EAMjFS,IAAiB,EAAmB,IAAsB,CACrE,IAAMC,EAAQ,CAAC,GAAGC,CAAI,CAAC,CACpB,MAAM,EAAG,IAAMjC,EAAE,KAAOkC,EAAE,IAAI,CA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D,IAAMmN,EAAQ,MAAMP,EAAO,QAAQ,EACnC,GAAIO,EAAM,OAAS,QAAS,MAAU,MAAMA,EAAM,OAAO,EACzD,GAAIA,EAAM,OAAS,SAAU,MAAU,MAAM,6BAA6BA,EAAM,KAAK,yBAAyB,EAC9G,OAAOA,EAAM,MACf,QAAU,CACRP,EAAO,KAAK,CACd,CACF,EACA,KAAM,gBAAiB,EAAO,CAC5B,IAAMA,EAASD,EAAY,EAC3B,GAAI,CAEF,IADAC,EAAO,KAAK,CAAE,KAAM,OAAQ,OAAM,QAAO,MAAOF,GAAW,OAAQ1M,EAAa,CAAE,CAAC,IAC1E,CACP,IAAMmN,EAAQ,MAAMP,EAAO,QAAQ,EACnC,GAAIO,EAAM,OAAS,QAAS,MAAU,MAAMA,EAAM,OAAO,EACzD,GAAIA,EAAM,OAAS,MAAO,OAC1B,GAAIA,EAAM,OAAS,OAAQ,MAAU,MAAM,6BAA6BA,EAAM,KAAK,WAAW,EAC9F,MAAMA,EAAM,KACZP,EAAO,KAAK,CAAE,KAAM,MAAO,CAAC,CAC9B,CACF,QAAU,CACRA,EAAO,KAAK,CACd,CACF,CACF","debugId":"9e9dff00-ef8c-4520-905b-ddce7acd6fcd"}
|
|
1
|
+
{"version":3,"file":"sheet-source-NKu1Enl2.js","names":["message","normalized","text","message","useId","useId","n","a","t","__toESM","require_react","require_jsx_runtime","createLucideIcon","Download","createWhere","isApiError","formatTag","displayValue","printFilter","Button","activeLocale","parseNumberText","saveFile","Spinner","humanize","enumLabel","cn","ErrorBanner","isEmptyCell","text","isSheetDate","cellText","isSheetJson","__iconData","FileSpreadsheet","import_react","import_jsx_runtime","csvField","failedRowsCsv","lines","rows","b","headers","row","column","fields","ImportCounts","label","counts","name","value","fieldLabel","view","importableTypes","relationTarget","target","field","resources","importableFields","model","json","matchableTypes","matchFields","key","others","relationModel","requiredOnCreate","normalized$1","autoMapping","taken","header","candidate","unmappedRequired","mode","mapped","mapping","entry","ok","problem","quoted","cell","toNumberText","options","integerValue","text$1","whole","fraction","decimalValue","text$2","trueWords","falseWords","booleanValue","text$3","pad","calendarDate","at","year","month","day","timePattern","readWallTime","iso","local","order","date","hours","minutes","seconds","wallTimeOf","time","notDate","dateValue","timestampValue","normalized","enumValue","values","text$4","matches","hints","textValue","jsonValue","convertCell","singularOf","views","resource","pluralOf","convertRow","context","data","problems","relations","plan","by","matchBy","converted","match","foundOne","keys","finding","named","isBlank","prepareRows","wanted","relation","id","written","found","existing","prepared","sampleRows","previewRows","readHead","chunks","source","sheet","first","dataRows","chunk","checkImport","check","signal","onProgress","refusal","error","runImport","progress","write","pending","ops","client","result","results","index","refused","queue","flush","all","cancelled","listedProblems","downloadRows","fileName","ProblemList","ImportChecking","ImportCheckStep","shown","columns","extensions","mediaTypes","androidMediaTypes","isAndroid","userAgent","importAccept","ImportSelect","className","onChange","event","option","help","ImportFileStep","reading","chosen","onChoose","file","sheets","onSheet","count","ImportProgressStep","done","cancelling","total","ImportSummary","stopped","where","valuesPerRequest","lookupKey","createLookups","known","foundOf","missing","asked","filter","pageToken","page","clientFor","record","chunkRows","startWorker","worker","replies","waiting","resolve","failed","request","workerSheetSource","reply"],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/file-spreadsheet.mjs","../../../src/app/import/failed-rows.ts","../../../src/app/import/import-counts.tsx","../../../src/app/import/mapping.ts","../../../src/app/import/convert.ts","../../../src/app/import/prepare-rows.ts","../../../src/app/import/run-import.ts","../../../src/app/import/import-check-step.tsx","../../../src/app/import/import-accept.ts","../../../src/app/import/import-select.tsx","../../../src/app/import/import-file-step.tsx","../../../src/app/import/import-result-step.tsx","../../../src/app/import/lookups.ts","../../../src/app/import/sheet-source.ts"],"sourcesContent":["/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"file-spreadsheet\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\",\n key: \"1oefj6\"\n }\n ],\n [\"path\", { d: \"M14 2v5a1 1 0 0 0 1 1h5\", key: \"wfsgrz\" }],\n [\"path\", { d: \"M8 13h2\", key: \"yr2amv\" }],\n [\"path\", { d: \"M14 13h2\", key: \"un5t4a\" }],\n [\"path\", { d: \"M8 17h2\", key: \"2yhykz\" }],\n [\"path\", { d: \"M14 17h2\", key: \"10kma7\" }]\n ]\n};\n__iconData.node;\nconst FileSpreadsheet = createLucideIcon(__iconData);\n\nexport { __iconData, FileSpreadsheet as default };\n//# sourceMappingURL=file-spreadsheet.mjs.map\n","import type { FailedRow } from './run-import'\nimport { cellText } from './sheet-cell'\nimport { text as message } from './messages'\n\n// A CSV field, quoted when it holds a delimiter, a quote or a line break\nconst csvField = (text: string) => (/[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text)\n\n/**\n * The rows an import did not write as a CSV file to fix and import again: the file's own columns, then the row's line in\n * the file and why it was not written. Sorted by line, with a byte order mark so spreadsheet programs read it as UTF-8.\n */\nexport const failedRowsCsv = (headers: string[], rows: FailedRow[]) => {\n const lines = [...rows]\n .sort((a, b) => a.line - b.line)\n .map((row) => [...headers.map((_, column) => cellText(row.cells[column] ?? null)), String(row.line), row.problems.join('; ')])\n return `${[[...headers, message('line'), message('problems')], ...lines].map((fields) => fields.map(csvField).join(',')).join('\\r\\n')}\\r\\n`\n}\n","import { formatTag } from '../../locale/active-locale'\n\n/** Counts side by side, each under its label, such as the rows an import created and updated. */\nexport const ImportCounts = ({ label, counts }: { label: string; counts: Array<[label: string, value: number]> }) => (\n <dl aria-label={label} className=\"grid grid-cols-2 gap-3 sm:grid-cols-4\">\n {counts.map(([name, value]) => (\n <div key={name} className=\"rounded-lg border px-3 py-2\">\n <dt className=\"text-xs text-muted-foreground\">{name}</dt>\n <dd className=\"text-lg font-semibold tabular-nums\">{value.toLocaleString(formatTag())}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { FieldModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\n\n/** What an import does with each row: create a record, update the one it matches, or update it when there is one and create it when not. */\nexport type ImportMode = 'create' | 'update' | 'upsert'\n\n/** A column of the file and the field it fills; `matchBy` names the field of the related record a relation is found by. */\nexport type ColumnMapping = { column: number; field: string; matchBy?: string }\n\n/** How a field reads in the import: its view's label, as everywhere else in the app. */\nexport const fieldLabel = (view: ViewModel | undefined, name: string) => view?.fields[name]?.label ?? humanize(name)\n\n// Types whose values a cell can hold: not structured data or files\nconst importableTypes = new Set<FieldModel['type']>(['text', 'integer', 'bigint', 'decimal', 'boolean', 'date', 'timestamp', 'uuid', 'enum', 'relation', 'currency', 'country'])\n\n// A relation an import can fill: one whose target is a resource the app knows, with a key of one field\nconst relationTarget = (field: FieldModel, resources: Record<string, ResourceModel>) => {\n const target = field.relation ? resources[field.relation.resource] : undefined\n return target?.primaryKey.length === 1 ? target : undefined\n}\n\n/**\n * The fields an import may write: not read-only, not the tenant, and of a type a cell can hold; a JSON field too when\n * the file is JSON, whose values it takes as they are.\n */\nexport const importableFields = (model: ResourceModel, resources: Record<string, ResourceModel>, { json = false } = {}) =>\n Object.values(model.fields).filter((field) => {\n if (field.readOnly || field.name === model.tenant) return false\n if (field.type === 'json') return json\n if (!importableTypes.has(field.type)) return false\n return field.type !== 'relation' || relationTarget(field, resources) !== undefined\n })\n\n// Types a record can be found by, with an equality filter on the value\nconst matchableTypes = new Set<FieldModel['type']>(['text', 'integer', 'bigint', 'uuid', 'date', 'currency', 'country', 'enum'])\n\n/**\n * The fields records of `model` can be found by: its key when it is one field, then the filterable fields whose values\n * single records out, such as an email or an order number. The user says which is unique; a value that matches several\n * records is an error on its row.\n */\nexport const matchFields = (model: ResourceModel) => {\n const key = model.primaryKey.length === 1 ? [model.fields[model.primaryKey[0]!]!] : []\n const others = Object.values(model.fields).filter((field) => field.filterable && !field.sensitive && matchableTypes.has(field.type) && !model.primaryKey.includes(field.name))\n return [...key, ...others]\n}\n\n/** The resource a relation field points at, when an import can fill it. */\nexport const relationModel = (field: FieldModel, resources: Record<string, ResourceModel>) => relationTarget(field, resources)\n\n/** Whether a new record needs the field: it can be neither empty nor filled in by a default. */\nexport const requiredOnCreate = (field: FieldModel) => !field.nullable && !field.default\n\n// Lower case without spaces, underscores or dashes: \"Customer email\", \"customer_email\" and \"CustomerEmail\" are one\nconst normalized = (text: string) => text.toLowerCase().replace(/[\\s_-]+/g, '')\n\n/**\n * Each column whose header is a field's label or name, ignoring case and spacing, mapped to that field; a field takes\n * the first column that matches it, and a column that matches none is skipped.\n */\nexport const autoMapping = (headers: string[], fields: FieldModel[], view: ViewModel | undefined): ColumnMapping[] => {\n const taken = new Set<string>()\n return headers.flatMap((header, column) => {\n const text = normalized(header)\n if (text === '') return []\n const field = fields.find((candidate) => !taken.has(candidate.name) && (normalized(fieldLabel(view, candidate.name)) === text || normalized(candidate.name) === text))\n if (!field) return []\n taken.add(field.name)\n return [{ column, field: field.name }]\n })\n}\n\n/** The fields a new record needs that no column fills, which a create, or a create-or-update, must have. */\nexport const unmappedRequired = (mode: ImportMode, fields: FieldModel[], mapping: ColumnMapping[]) => {\n if (mode === 'update') return []\n const mapped = new Set(mapping.map((entry) => entry.field))\n return fields.filter((field) => requiredOnCreate(field) && !mapped.has(field.name))\n}\n","import { enumLabel, type FieldModel, type FieldViewModel } from '@protobase/schema'\nimport { parseNumberText, type DecimalSeparator } from '../../format/number-text'\nimport { cellText, isEmptyCell, isSheetDate, isSheetJson, type SheetCell } from './sheet-cell'\nimport { text as message } from './messages'\n\n/**\n * How the file writes what is ambiguous in text: the decimal separator of numbers (`1,234.5` or `1.234,5`), and whether\n * a date such as 03/04/2026 starts with the day or the month. ISO dates (2026-04-03) read the same either way.\n */\nexport type ConvertOptions = {\n decimal: DecimalSeparator\n dateOrder: 'dmy' | 'mdy'\n /** A true or false cell fills a text field as the file shows it (TRUE or FALSE), as in a table made from the file. */\n booleanText?: boolean\n}\n\nexport type Converted = { ok: true; value: unknown } | { ok: false; problem: string }\n\nconst ok = (value: unknown): Converted => ({ ok: true, value })\nconst problem = (text: string): Converted => ({ ok: false, problem: text })\nconst quoted = (cell: SheetCell) => `“${cellText(cell)}”`\n\nconst toNumberText = (cell: SheetCell, options: ConvertOptions) => {\n if (typeof cell === 'number') return String(cell)\n if (typeof cell === 'string') return parseNumberText(cell, options.decimal)\n return undefined\n}\n\nconst integerValue = (field: FieldModel, cell: SheetCell, options: ConvertOptions): Converted => {\n const text = toNumberText(cell, options)\n if (text === undefined) return problem(message('notNumber', { cell: quoted(cell) }))\n const [whole, fraction = ''] = text.split('.')\n if (/[1-9]/.test(fraction) || /e/i.test(text)) return problem(message('notWholeNumber', { cell: quoted(cell) }))\n if (field.type === 'bigint') return ok(String(BigInt(whole!)))\n const value = Number(whole)\n return Number.isSafeInteger(value) ? ok(value) : problem(message('tooLarge', { cell: quoted(cell) }))\n}\n\nconst decimalValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const text = toNumberText(cell, options)\n return text === undefined ? problem(message('notNumber', { cell: quoted(cell) })) : ok(text)\n}\n\nconst trueWords = new Set(['true', 'yes', '1'])\nconst falseWords = new Set(['false', 'no', '0'])\n\nconst booleanValue = (cell: SheetCell): Converted => {\n if (typeof cell === 'boolean') return ok(cell)\n const text = typeof cell === 'string' || typeof cell === 'number' ? String(cell).trim().toLowerCase() : ''\n if (trueWords.has(text)) return ok(true)\n if (falseWords.has(text)) return ok(false)\n return problem(message('notBoolean', { cell: quoted(cell) }))\n}\n\nconst pad = (value: number) => String(value).padStart(2, '0')\n\n// A calendar date that exists, as YYYY-MM-DD\nconst calendarDate = (year: number, month: number, day: number) => {\n const at = new Date(Date.UTC(year, month - 1, day))\n if (at.getUTCFullYear() !== year || at.getUTCMonth() !== month - 1 || at.getUTCDate() !== day) return undefined\n return `${year}-${pad(month)}-${pad(day)}`\n}\n\ntype WallTime = { date: string; time?: string; zone?: string }\n\nconst timePattern = '(\\\\d{1,2}):(\\\\d{2})(?::(\\\\d{2})(?:\\\\.\\\\d+)?)?'\n\n// A date and time written as text: ISO (2026-04-03, 2026-04-03T14:30:00+02:00) or day and month in the file's order\n// (03/04/2026 14:30), with a four-digit year\nconst readWallTime = (text: string, order: ConvertOptions['dateOrder']): WallTime | undefined => {\n const iso = new RegExp(`^(\\\\d{4})[-/](\\\\d{1,2})[-/](\\\\d{1,2})(?:[T ]${timePattern}(Z|[+-]\\\\d{2}:?\\\\d{2})?)?$`).exec(text.trim())\n const local = new RegExp(`^(\\\\d{1,2})[./-](\\\\d{1,2})[./-](\\\\d{4})(?: ${timePattern})?$`).exec(text.trim())\n if (!iso && !local) return undefined\n const [year, month, day] = iso ? [iso[1], iso[2], iso[3]].map(Number) : order === 'dmy' ? [local![3], local![2], local![1]].map(Number) : [local![3], local![1], local![2]].map(Number)\n const date = calendarDate(year!, month!, day!)\n if (!date) return undefined\n const [hours, minutes, seconds = '0'] = (iso ? iso.slice(4, 7) : local!.slice(4, 7)) as [string | undefined, string | undefined, string | undefined]\n if (hours === undefined) return { date }\n if (Number(hours) > 23 || Number(minutes) > 59 || Number(seconds) > 59) return undefined\n return { date, time: `${pad(Number(hours))}:${minutes}:${pad(Number(seconds))}`, zone: iso?.[7] }\n}\n\nconst wallTimeOf = (cell: SheetCell, options: ConvertOptions): WallTime | undefined => {\n if (isSheetDate(cell)) {\n const [date, time] = cell.date.split('T')\n return { date: date!, time }\n }\n return typeof cell === 'string' ? readWallTime(cell, options.dateOrder) : undefined\n}\n\nconst notDate = (cell: SheetCell, options: ConvertOptions) =>\n problem(message('notDate', { cell: quoted(cell), dayFirst: options.dateOrder === 'dmy' }))\n\nconst dateValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const at = wallTimeOf(cell, options)\n if (!at) return notDate(cell, options)\n if (at.time && at.time !== '00:00:00') return problem(message('hasTime', { cell: quoted(cell) }))\n return ok(at.date)\n}\n\n// A time without a zone is the browser's local time, as the person reading the sheet sees it\nconst timestampValue = (cell: SheetCell, options: ConvertOptions): Converted => {\n const at = wallTimeOf(cell, options)\n if (!at) return notDate(cell, options)\n if (at.zone) return ok(new Date(`${at.date}T${at.time}${at.zone === 'Z' ? 'Z' : at.zone.replace(/^([+-]\\d{2})(\\d{2})$/, '$1:$2')}`).toISOString())\n const [year, month, day] = at.date.split('-').map(Number)\n const [hours, minutes, seconds] = (at.time ?? '00:00:00').split(':').map(Number)\n return ok(new Date(year!, month! - 1, day!, hours, minutes, seconds).toISOString())\n}\n\nconst normalized = (text: string) => text.trim().toLowerCase().replace(/\\s+/g, ' ')\n\nconst enumValue = (field: FieldModel, hints: FieldViewModel | undefined, cell: SheetCell): Converted => {\n const values = field.enumValues ?? []\n const text = normalized(cellText(cell))\n const matches = values.filter((value) => normalized(value) === text || normalized(enumLabel(value, hints?.valueLabels)) === text)\n if (matches.length === 1) return ok(matches[0])\n if (matches.length > 1) return problem(message('severalValues', { cell: quoted(cell), values: matches.map((value) => enumLabel(value, hints?.valueLabels)).join(', ') }))\n return problem(message('notOneOf', { cell: quoted(cell), values: values.map((value) => enumLabel(value, hints?.valueLabels)).join(', ') }))\n}\n\nconst textValue = (cell: SheetCell, options: ConvertOptions): Converted =>\n typeof cell === 'boolean' && !options.booleanText ? problem(message('notText', { cell: quoted(cell) })) : ok(cellText(cell))\n\n// A JSON file's value as it is: a nested object or array, or a string, number or boolean\nconst jsonValue = (cell: SheetCell): Converted => (isSheetJson(cell) ? ok(cell.json) : ok(cell))\n\n/**\n * The value a cell gives a field, as the API takes it, or the problem that keeps it from being one: never a guess, and an\n * empty cell is null, never a default. A relation's cell is the value of the field its records are found by, so it\n * converts as that field (`convertCell(targetField, ...)`).\n */\nexport const convertCell = (field: FieldModel, hints: FieldViewModel | undefined, cell: SheetCell, options: ConvertOptions): Converted => {\n if (isEmptyCell(cell)) return field.nullable ? ok(null) : problem(message('emptyRequired'))\n if (field.type === 'json') return jsonValue(cell)\n if (isSheetJson(cell)) return problem(message('nestedValue', { cell: quoted(cell) }))\n switch (field.type) {\n case 'integer':\n case 'bigint':\n return integerValue(field, cell, options)\n case 'decimal':\n return decimalValue(cell, options)\n case 'boolean':\n return booleanValue(cell)\n case 'date':\n return dateValue(cell, options)\n case 'timestamp':\n return timestampValue(cell, options)\n case 'enum':\n return enumValue(field, hints, cell)\n case 'text':\n case 'uuid':\n case 'currency':\n case 'country':\n return textValue(cell, options)\n default:\n throw new Error(`Not implemented: importing ${field.type} fields, which importableFields leaves out`)\n }\n}\n","import type { BatchOp } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { humanize } from '../../live/naming'\nimport { convertCell, type ConvertOptions } from './convert'\nimport type { Lookups } from './lookups'\nimport { fieldLabel, relationModel, type ColumnMapping, type ImportMode } from './mapping'\nimport { cellText, isEmptyCell, type SheetCell, type SheetRow } from './sheet-cell'\nimport { text } from './messages'\n\n/** What an import does: its mode, which column fills which field, the column records are found by, and how the file writes numbers and dates. */\nexport type ImportPlan = {\n mode: ImportMode\n columns: ColumnMapping[]\n /** For an update or create-or-update: the column whose value finds the record, by the field it holds. */\n match?: { column: number; field: string }\n options: ConvertOptions\n}\n\n/** The app's models, and the lookups that find related and updated records. */\nexport type ImportContext = {\n model: ResourceModel\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n lookups: Lookups\n}\n\n/**\n * A row as the import will write it: the write, or the problems that keep it from being written. `values` are the\n * converted values by field, a relation's as the file names the record, for the preview.\n */\nexport type PreparedRow = { line: number; cells: SheetCell[]; values: Record<string, unknown>; problems: string[]; op?: BatchOp }\n\nconst singularOf = (views: Record<string, ViewModel>, resource: string) => views[resource]?.names?.singular ?? humanize(resource)\nconst pluralOf = (views: Record<string, ViewModel>, resource: string) => views[resource]?.names?.plural ?? humanize(resource)\n\ntype Finding = { model: ResourceModel; field: string; value: unknown }\n\n// A row's converted values and the records it needs found, before any lookup\nconst convertRow = (row: SheetRow, plan: ImportPlan, context: ImportContext) => {\n const { model, resources, views } = context\n const view = views[model.name]\n const values: Record<string, unknown> = {}\n const data: Record<string, unknown> = {}\n const problems: string[] = []\n const relations: Array<{ field: string; finding: Finding }> = []\n for (const { column, field: name, matchBy } of plan.columns) {\n const field = model.fields[name]!\n const cell = row.cells[column] ?? null\n const label = fieldLabel(view, name)\n const target = relationModel(field, resources)\n if (target && !isEmptyCell(cell)) {\n const by = matchBy ?? target.primaryKey[0]!\n const converted = convertCell(target.fields[by]!, views[target.name]?.fields[by], cell, plan.options)\n if (!converted.ok) problems.push(`${label}: ${converted.problem}`)\n else relations.push({ field: name, finding: { model: target, field: by, value: converted.value } })\n values[name] = cellText(cell)\n continue\n }\n const converted = convertCell(field, view?.fields[name], cell, plan.options)\n if (!converted.ok) problems.push(`${label}: ${converted.problem}`)\n else data[name] = values[name] = converted.value\n }\n let match: Finding | undefined\n if (plan.match && plan.mode !== 'create') {\n const field = model.fields[plan.match.field]!\n const converted = convertCell({ ...field, nullable: false }, view?.fields[field.name], row.cells[plan.match.column] ?? null, plan.options)\n if (!converted.ok) problems.push(`${fieldLabel(view, field.name)}: ${converted.problem}`)\n else match = { model, field: field.name, value: converted.value }\n }\n return { values, data, problems, relations, match }\n}\n\n// What a lookup found for a value: the one record's key, or why there is none: \"no customer has email “x”\", \"2\n// customers have email “x”\"\nconst foundOne = (context: ImportContext, finding: Finding) => {\n const keys = context.lookups.keysOf(finding.model.name, finding.field, finding.value)\n const named = `${fieldLabel(context.views[finding.model.name], finding.field).toLowerCase()} “${String(finding.value)}”`\n if (keys.length === 1) return { key: keys[0] }\n if (keys.length === 0) return { none: text('noneHas', { singular: singularOf(context.views, finding.model.name), named }) }\n return { several: text('severalHave', { count: keys.length, plural: pluralOf(context.views, finding.model.name), named }) }\n}\n\nconst isBlank = (row: SheetRow) => row.cells.every(isEmptyCell)\n\n/**\n * The rows of a chunk as writes: each mapped cell converted, related records and the records to update found (asked\n * for together), and the write each row makes, or the problems that keep it out. Rows with no value at all are left\n * out.\n */\nexport const prepareRows = async (rows: SheetRow[], plan: ImportPlan, context: ImportContext): Promise<PreparedRow[]> => {\n const { model, views } = context\n const converted = rows.filter((row) => !isBlank(row)).map((row) => ({ row, ...convertRow(row, plan, context) }))\n\n const wanted = new Map<string, { model: ResourceModel; field: string; values: unknown[] }>()\n for (const finding of converted.flatMap((entry) => [...entry.relations.map((relation) => relation.finding), ...(entry.match ? [entry.match] : [])])) {\n const id = `${finding.model.name}.${finding.field}`\n if (!wanted.has(id)) wanted.set(id, { model: finding.model, field: finding.field, values: [] })\n wanted.get(id)!.values.push(finding.value)\n }\n for (const { model: target, field, values } of wanted.values()) await context.lookups.load(target, field, values)\n\n return converted.map(({ row, values, data, problems, relations, match }) => {\n const written = { ...data }\n for (const { field, finding } of relations) {\n const found = foundOne(context, finding)\n if ('key' in found) written[field] = found.key\n else problems.push(`${fieldLabel(views[model.name], field)}: ${found.none ?? found.several}`)\n }\n // An update needs its record; a create-or-update creates one when none matches\n const existing = match && foundOne(context, match)\n if (existing?.several) problems.push(text('notOneRecord', { found: existing.several }))\n if (existing?.none && plan.mode === 'update') problems.push(text('nothingToUpdate', { found: existing.none }))\n const prepared = { line: row.line, cells: row.cells, values, problems }\n if (problems.length > 0) return prepared\n if (existing && 'key' in existing) return { ...prepared, op: { op: 'update', resource: model.name, key: existing.key as string | number, etag: '*', data: written } satisfies BatchOp }\n return { ...prepared, op: { op: 'create', resource: model.name, data: written } satisfies BatchOp }\n })\n}\n","import { isApiError, type BatchOp, type Client } from '@protobase/client'\nimport { fieldLabel } from './mapping'\nimport { prepareRows, type ImportContext, type ImportPlan, type PreparedRow } from './prepare-rows'\nimport { cellText, type SheetCell, type SheetRow } from './sheet-cell'\nimport type { SheetSource } from './sheet-source'\n\n/** How many data rows the mapping step shows under each column. */\nconst sampleRows = 5\n/** How many rows of the check the preview shows. */\nconst previewRows = 5\n/** Rows per batch write: each batch is one transaction. */\nexport const batchRows = 100\n\n/** The file's header row as text, and its first data rows. */\nexport type SheetHead = { headers: string[]; sample: SheetRow[] }\n\n/** The header and the first rows of a sheet, reading no further than its first chunk. */\nexport const readHead = async (source: SheetSource, sheet: string | undefined): Promise<SheetHead> => {\n const chunks = source.rows(sheet)\n const { value: first = [] } = await chunks.next()\n await chunks.return(undefined)\n const [header, ...rows] = first\n return { headers: (header?.cells ?? []).map(cellText), sample: rows.slice(0, sampleRows) }\n}\n\n// The data rows of a sheet, chunk by chunk, without its header row\nasync function* dataRows(source: SheetSource, sheet: string | undefined) {\n let header = true\n for await (const chunk of source.rows(sheet)) {\n yield header ? chunk.slice(1) : chunk\n header = false\n }\n}\n\n/** A row the import did not write, with the line it has in the file and why. */\nexport type FailedRow = { line: number; cells: SheetCell[]; problems: string[] }\n\n/** What the check found: how many rows would create or update a record, the rows with problems, and the first rows as they would be written. */\nexport type ImportCheck = { rows: number; creates: number; updates: number; problems: FailedRow[]; preview: PreparedRow[] }\n\n/** Reads the whole file and prepares every row as the import would, writing nothing; `onProgress` gets the rows read so far. */\nexport const checkImport = async (source: SheetSource, sheet: string | undefined, plan: ImportPlan, context: ImportContext, onProgress: (rows: number) => void, signal?: AbortSignal) => {\n const check: ImportCheck = { rows: 0, creates: 0, updates: 0, problems: [], preview: [] }\n for await (const chunk of dataRows(source, sheet)) {\n signal?.throwIfAborted()\n for (const row of await prepareRows(chunk, plan, context)) {\n check.rows++\n if (check.preview.length < previewRows) check.preview.push(row)\n if (row.op?.op === 'create') check.creates++\n else if (row.op?.op === 'update') check.updates++\n else check.problems.push({ line: row.line, cells: row.cells, problems: row.problems })\n }\n onProgress(check.rows)\n }\n return check\n}\n\n/** Where an import stands: what it wrote, skipped for problems and the server refused, and the rows it did not write. */\nexport type ImportProgress = { created: number; updated: number; skipped: number; failed: number; notWritten: FailedRow[] }\n\n// Why the server refused a write: its field errors under the fields' labels, else its message\nconst refusal = (error: Error, context: ImportContext) => {\n if (!isApiError(error)) return [error.message]\n const fields = error.errors.filter((entry) => entry.field)\n if (fields.length === 0) return [error.message]\n return fields.map((entry) => `${fieldLabel(context.views[context.model.name], entry.field!)}: ${entry.message}`)\n}\n\nexport type RunOptions = {\n client: Client\n /** Called after every batch, with the counts so far. */\n onProgress: (progress: ImportProgress) => void\n /** Asked before every batch: true stops the import there, keeping what earlier batches wrote. */\n cancelled: () => boolean\n}\n\n/**\n * Writes the file's rows in batches of `batchRows`, each batch one transaction through `POST :batchWrite`, with the\n * same validation and access as single writes. A row the server refuses is set aside with the reason, and the rest of\n * its batch is sent again, so every row that can be written is. Rows with problems are skipped. Answers `cancelled`\n * when stopped between batches; an error other than a refused row stops the import and is thrown.\n */\nexport const runImport = async (source: SheetSource, sheet: string | undefined, plan: ImportPlan, context: ImportContext, { client, onProgress, cancelled }: RunOptions) => {\n const progress: ImportProgress = { created: 0, updated: 0, skipped: 0, failed: 0, notWritten: [] }\n\n const write = async (rows: PreparedRow[]) => {\n const pending = [...rows]\n while (pending.length > 0) {\n const ops = pending.map((row) => row.op!) as BatchOp[]\n try {\n const { results } = await client.batchWrite(ops)\n for (const result of results) {\n if (result.op === 'create') progress.created++\n else if (result.op === 'update') progress.updated++\n }\n return\n } catch (error) {\n const index = isApiError(error) ? error.operation : undefined\n if (index === undefined || !pending[index]) throw error\n const [refused] = pending.splice(index, 1)\n progress.failed++\n progress.notWritten.push({ line: refused!.line, cells: refused!.cells, problems: refusal(error as Error, context) })\n }\n }\n }\n\n let queue: PreparedRow[] = []\n const flush = async (all: boolean) => {\n while (queue.length >= batchRows || (all && queue.length > 0)) {\n if (cancelled()) return false\n await write(queue.splice(0, batchRows))\n onProgress({ ...progress })\n }\n return true\n }\n\n for await (const chunk of dataRows(source, sheet)) {\n for (const row of await prepareRows(chunk, plan, context)) {\n if (row.op) queue.push(row)\n else {\n progress.skipped++\n progress.notWritten.push({ line: row.line, cells: row.cells, problems: row.problems })\n }\n }\n if (!(await flush(false))) return { ...progress, cancelled: true }\n }\n if (!(await flush(true))) return { ...progress, cancelled: true }\n return { ...progress, cancelled: false }\n}\n","import { Download } from 'lucide-react'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { saveFile } from '../../lib/save-file'\nimport { Button } from '../../primitives/button'\nimport { Spinner } from '../../primitives/spinner'\nimport { failedRowsCsv } from './failed-rows'\nimport { ImportCounts } from './import-counts'\nimport { fieldLabel, relationModel, type ColumnMapping } from './mapping'\nimport { batchRows, type FailedRow, type ImportCheck } from './run-import'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** How many rows with problems the check lists; the file of them holds every one. */\nconst listedProblems = 50\n\n/** Saves the rows with their problems as a CSV named after the imported file. */\nexport const downloadRows = (fileName: string | undefined, headers: string[], rows: FailedRow[]) =>\n saveFile(failedRowsCsv(headers, rows), text('notImportedFile', { name: (fileName ?? 'import').replace(/\\.[^.]+$/, '') }), 'text/csv')\n\n/** The rows with what keeps each from being imported, at most `listedProblems` of them. */\nexport const ProblemList = ({ rows }: { rows: FailedRow[] }) => (\n <ul aria-label={text('rowsNotImported')} className=\"flex flex-col gap-1 text-body\">\n {rows.slice(0, listedProblems).map((row) => (\n <li key={row.line}>\n <span className=\"font-medium\">{text('rowProblems', { line: row.line })}</span> {row.problems.join('; ')}\n </li>\n ))}\n {rows.length > listedProblems && <li className=\"text-muted-foreground\">{text('andMore', { count: (rows.length - listedProblems).toLocaleString(formatTag()) })}</li>}\n </ul>\n)\n\nexport const ImportChecking = ({ rows }: { rows: number }) => (\n <p className=\"flex items-center gap-2 text-muted-foreground\" role=\"status\">\n <Spinner className=\"size-3.5\" />\n {text('checkingRows', { count: rows.toLocaleString(formatTag()) })}\n </p>\n)\n\ntype ImportCheckStepProps = {\n check: ImportCheck\n model: ResourceModel\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n columns: ColumnMapping[]\n headers: string[]\n fileName?: string\n}\n\n/**\n * What the import would do, before it writes anything: how many rows create or update a record, the first rows as they\n * would be written, and every row with problems, which the import skips.\n */\nexport const ImportCheckStep = ({ check, model, resources, views, columns, headers, fileName }: ImportCheckStepProps) => {\n const view = views[model.name]\n const shown = columns.map((column) => model.fields[column.field]!)\n return (\n <div className=\"flex flex-col gap-4\">\n <ImportCounts\n label={text('check')}\n counts={[\n [text('rows'), check.rows],\n [text('toCreate'), check.creates],\n [text('toUpdate'), check.updates],\n [text('withProblems'), check.problems.length],\n ]}\n />\n {check.preview.length > 0 && (\n // A table as wide as its columns scrolls sideways inside the dialog, which scrolls down as a whole\n <div className=\"overflow-x-auto rounded-lg border\">\n <table aria-label={text('firstRows')} className=\"w-full text-left text-body\">\n <thead className=\"bg-muted text-muted-foreground\">\n <tr>\n <th className=\"px-2 py-1.5 font-medium\">{text('row')}</th>\n {shown.map((field) => (\n <th key={field.name} className=\"whitespace-nowrap px-2 py-1.5 font-medium\">\n {fieldLabel(view, field.name)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody className=\"divide-y\">\n {check.preview.map((row) => (\n <tr key={row.line} className={row.problems.length > 0 ? 'bg-danger-soft' : undefined}>\n <td className=\"px-2 py-1.5 tabular-nums text-muted-foreground\">{row.line}</td>\n {shown.map((field) => (\n <td key={field.name} className=\"max-w-48 truncate px-2 py-1.5\">\n {relationModel(field, resources) ? String(row.values[field.name] ?? '—') : field.name in row.values ? displayValue(field, row.values[field.name], view?.fields[field.name]) : ''}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n {check.problems.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-center justify-between gap-2\">\n <h3 className=\"font-medium\">{text('problemRows')}</h3>\n <Button size=\"sm\" onClick={() => downloadRows(fileName, headers, check.problems)}>\n <Download className=\"size-3.5\" />\n {text('download')}\n </Button>\n </div>\n <ProblemList rows={check.problems} />\n </div>\n )}\n <p className=\"text-xs text-muted-foreground\">{text('batches', { size: batchRows })}</p>\n </div>\n )\n}\n","// What an import's file input accepts: its extensions, with the media types a picker that filters by type needs.\n\nconst extensions = ['.xlsx', '.csv', '.json']\n\nconst mediaTypes = ['text/csv', 'application/json', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']\n\n/**\n * Android's picker filters by media type alone, turning each extension into the one type Android maps it to, so it\n * greys out a file whose provider labels it otherwise: a CSV as `text/comma-separated-values`, `application/csv`,\n * `text/x-csv`, `application/vnd.ms-excel` or `text/plain`, and any file a provider does not know as\n * `application/octet-stream`. The import reads a file by its name, so these are safe to offer there. Elsewhere the\n * picker matches extensions, and the generic types would offer every file.\n */\nconst androidMediaTypes = ['text/comma-separated-values', 'application/csv', 'text/x-csv', 'application/vnd.ms-excel', 'text/plain', 'application/octet-stream']\n\nconst isAndroid = (userAgent: string) => /\\bAndroid\\b/.test(userAgent)\n\n/** The `accept` of an import's file input on the device with this user agent: `.xlsx`, CSV and JSON files. */\nexport const importAccept = (userAgent: string) => [...extensions, ...mediaTypes, ...(isAndroid(userAgent) ? androidMediaTypes : [])].join(',')\n","import { useId, type ReactNode } from 'react'\nimport { cn } from '../../lib/cn'\n\nexport type ImportSelectOption = { value: string; label: string }\n\ntype ImportSelectProps = {\n label: string\n /** The select's name for assistive technology, when the visible label alone does not say which it is. */\n name?: string\n value: string\n options: ImportSelectOption[]\n onChange: (value: string) => void\n /** A line under the control. */\n help?: ReactNode\n className?: string\n}\n\n/** A labelled native select, as the field editors draw theirs. */\nexport const ImportSelect = ({ label, name, value, options, onChange, help, className }: ImportSelectProps) => {\n const id = useId()\n return (\n <div className={cn('flex min-w-0 flex-col gap-1.5', className)}>\n <label htmlFor={id} className=\"font-medium\">\n {label}\n </label>\n <select\n id={id}\n aria-label={name}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n className=\"h-8 w-full min-w-0 rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 max-sm:min-h-11\"\n >\n {options.map((option) => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n {help && <p className=\"text-xs text-muted-foreground\">{help}</p>}\n </div>\n )\n}\n","import { FileSpreadsheet } from 'lucide-react'\nimport { useId } from 'react'\nimport { Spinner } from '../../primitives/spinner'\nimport { importAccept } from './import-accept'\nimport { ImportSelect } from './import-select'\nimport { text } from './messages'\n\ntype ImportFileStepProps = {\n file?: File\n sheets: string[]\n sheet?: string\n reading: boolean\n onChoose: (file: File) => void\n onSheet: (sheet: string) => void\n}\n\n/** The file to import, an .xlsx workbook, a CSV or a JSON file, and the sheet to read from a workbook with several. */\nexport const ImportFileStep = ({ file, sheets, sheet, reading, onChoose, onSheet }: ImportFileStepProps) => {\n const id = useId()\n return (\n <div className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-1.5\">\n <label htmlFor={id} className=\"font-medium\">\n {text('file')}\n </label>\n <input\n id={id}\n type=\"file\"\n accept={importAccept(globalThis.navigator?.userAgent ?? '')}\n disabled={reading}\n onChange={(event) => {\n const chosen = event.target.files?.[0]\n if (chosen) onChoose(chosen)\n }}\n className=\"file:mr-3 file:h-8 file:rounded-md file:border file:border-border-strong file:bg-background file:px-3 file:font-medium file:text-foreground max-sm:file:min-h-11\"\n />\n <p className=\"text-xs text-muted-foreground\">{text('fileHint')}</p>\n </div>\n {reading && (\n <p className=\"flex items-center gap-2 text-muted-foreground\" role=\"status\">\n <Spinner className=\"size-3.5\" />\n {text('reading', { name: file?.name ?? text('theFile') })}\n </p>\n )}\n {!reading && sheets.length > 1 && (\n <div className=\"flex items-end gap-3\">\n <FileSpreadsheet className=\"mb-2 size-4 shrink-0 text-muted-foreground\" />\n <ImportSelect className=\"flex-1\" label={text('sheet')} value={sheet ?? ''} options={sheets.map((name) => ({ value: name, label: name }))} onChange={onSheet} />\n </div>\n )}\n </div>\n )\n}\n","import { Download } from 'lucide-react'\nimport { Button } from '../../primitives/button'\nimport { ErrorBanner } from '../error-banner'\nimport { downloadRows, ProblemList } from './import-check-step'\nimport { ImportCounts } from './import-counts'\nimport type { ImportProgress } from './run-import'\nimport { formatTag } from '../../locale/active-locale'\nimport { text } from './messages'\n\nconst count = (value: number) => value.toLocaleString(formatTag())\n\n/** The rows written so far out of those to write, as a bar. */\nexport const ImportProgressStep = ({ progress, total, cancelling }: { progress: ImportProgress; total: number; cancelling: boolean }) => {\n const done = progress.created + progress.updated + progress.failed\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-baseline justify-between gap-2 text-xs\">\n <span className=\"text-muted-foreground\">{cancelling ? text('stopping') : text('saving')}</span>\n <span className=\"tabular-nums\">\n {count(done)} / {count(total)}\n </span>\n </div>\n <div role=\"progressbar\" aria-label={text('rowsSaved')} aria-valuenow={done} aria-valuemin={0} aria-valuemax={total} className=\"h-2 overflow-hidden rounded-full bg-muted\">\n <div className=\"h-full rounded-full bg-primary transition-[width]\" style={{ width: `${total > 0 ? Math.min(100, (done / total) * 100) : 0}%` }} />\n </div>\n </div>\n )\n}\n\ntype ImportSummaryProps = {\n result: ImportProgress & { cancelled: boolean }\n /** The error that stopped the import before its end. */\n stopped?: unknown\n headers: string[]\n fileName?: string\n}\n\n/** What the import did: created, updated, skipped and failed rows, and the rows it did not write with the reasons, to download. */\nexport const ImportSummary = ({ result, stopped, headers, fileName }: ImportSummaryProps) => (\n <div className=\"flex flex-col gap-4\">\n {stopped !== undefined && <ErrorBanner title={text('stopped')} error={stopped} />}\n {result.cancelled && <p role=\"status\">{text('cancelled')}</p>}\n <ImportCounts\n label={text('summary')}\n counts={[\n [text('created'), result.created],\n [text('updated'), result.updated],\n [text('skipped'), result.skipped],\n [text('failed'), result.failed],\n ]}\n />\n {result.notWritten.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-center justify-between gap-2\">\n <h3 className=\"font-medium\">{text('rowsNotImported')}</h3>\n <Button size=\"sm\" onClick={() => downloadRows(fileName, headers, result.notWritten)}>\n <Download className=\"size-3.5\" />\n {text('download')}\n </Button>\n </div>\n <p className=\"text-xs text-muted-foreground\">{text('notWrittenHint')}</p>\n <ProblemList rows={[...result.notWritten].sort((a, b) => a.line - b.line)} />\n </div>\n )}\n </div>\n)\n","import type { Client } from '@protobase/client'\nimport { createWhere, printFilter, type ResourceModel } from '@protobase/schema'\n\nconst where = createWhere()\n// Values per request, so the filter stays short\nconst valuesPerRequest = 100\n\n/** The keys of the records whose field holds each value: none, one, or several when the value singles out no record. */\nexport type Found = Map<string, unknown[]>\n\n/** A value as the lookups compare it: the API answers numbers as numbers and the rest as text. */\nexport const lookupKey = (value: unknown) => String(value)\n\n/**\n * Finds records by the value of a field, for the relations of an import's rows and the records it updates: each value\n * is asked for once per import, a hundred at a time, and remembered.\n */\nexport const createLookups = (clientFor: (resource: string) => Client) => {\n const known = new Map<string, Found>()\n\n const foundOf = (resource: string, field: string) => {\n const id = `${resource}.${field}`\n if (!known.has(id)) known.set(id, new Map())\n return known.get(id)!\n }\n\n /** Asks the API for the values not asked for yet; the user reads only the records they may list. */\n const load = async (model: ResourceModel, field: string, values: unknown[]) => {\n const found = foundOf(model.name, field)\n const missing = [...new Map(values.filter((value) => !found.has(lookupKey(value))).map((value) => [lookupKey(value), value])).values()]\n const key = model.primaryKey[0]!\n for (let at = 0; at < missing.length; at += valuesPerRequest) {\n const asked = missing.slice(at, at + valuesPerRequest)\n for (const value of asked) found.set(lookupKey(value), [])\n const filter = printFilter(where.in(field, asked as never[]))\n let pageToken: string | undefined\n do {\n const page = await clientFor(model.name).list(model.name, { filter, fields: [...new Set([key, field])], pageSize: 1000, pageToken })\n for (const record of page.items as Record<string, unknown>[]) found.get(lookupKey(record[field]))?.push(record[key])\n pageToken = page.nextPageToken || undefined\n } while (pageToken)\n }\n }\n\n /** The keys of the records found by the value, once `load` asked for it. */\n const keysOf = (resource: string, field: string, value: unknown) => foundOf(resource, field).get(lookupKey(value)) ?? []\n\n return { load, keysOf }\n}\n\nexport type Lookups = ReturnType<typeof createLookups>\n","import type { ParseReply, ParseRequest } from './parse-messages'\nimport type { SheetRow } from './sheet-cell'\nimport { activeLocale } from '../../locale/active-locale'\nimport { text } from './messages'\n\n/** A chosen file as an import reads it: its sheet names, and its rows (the header first) in chunks. */\nexport type SheetSource = {\n sheets: () => Promise<string[]>\n rows: (sheet: string | undefined) => AsyncGenerator<SheetRow[]>\n}\n\n/** How many rows the worker sends at a time. */\nconst chunkRows = 500\n\n// A parse worker, with its replies taken one at a time\nconst startWorker = () => {\n const worker = new Worker(new URL('./parse-worker.ts', import.meta.url), { type: 'module' })\n const replies: ParseReply[] = []\n let waiting: ((reply: ParseReply) => void) | undefined\n worker.onmessage = (event: MessageEvent<ParseReply>) => {\n if (waiting) {\n const resolve = waiting\n waiting = undefined\n resolve(event.data)\n } else replies.push(event.data)\n }\n worker.onerror = (event) => {\n event.preventDefault()\n const failed: ParseReply = { type: 'error', message: text('unreadable') }\n if (waiting) waiting(failed)\n else replies.push(failed)\n }\n const send = (request: ParseRequest) => worker.postMessage(request)\n const receive = () => (replies.length > 0 ? Promise.resolve(replies.shift()!) : new Promise<ParseReply>((resolve) => (waiting = resolve)))\n return { send, receive, stop: () => worker.terminate() }\n}\n\n/** The file read by a Web Worker, so parsing never holds up the page; each read has a worker of its own. */\nexport const workerSheetSource = (file: File): SheetSource => ({\n sheets: async () => {\n const worker = startWorker()\n try {\n worker.send({ type: 'sheets', file, locale: activeLocale() })\n const reply = await worker.receive()\n if (reply.type === 'error') throw new Error(reply.message)\n if (reply.type !== 'sheets') throw new Error(`The parse worker answered ${reply.type} to a request for sheets`)\n return reply.sheets\n } finally {\n worker.stop()\n }\n },\n rows: async function* (sheet) {\n const worker = startWorker()\n try {\n worker.send({ type: 'read', file, sheet, chunk: chunkRows, locale: activeLocale() })\n for (;;) {\n const reply = await worker.receive()\n if (reply.type === 'error') throw new Error(reply.message)\n if (reply.type === 'end') return\n if (reply.type !== 'rows') throw new Error(`The parse worker answered ${reply.type} to a read`)\n yield reply.rows\n worker.send({ type: 'next' })\n }\n } finally {\n worker.stop()\n }\n },\n})\n\n/** Rows already in memory as a source, for tests and stories. */\nexport const memorySheetSource = (rows: SheetRow[], sheets: string[] = []): SheetSource => ({\n sheets: async () => sheets,\n rows: async function* () {\n for (let at = 0; at < rows.length; at += chunkRows) yield rows.slice(at, at + chunkRows)\n },\n})\n"],"ignoreList":[0],"mappings":"iyBASA,IAAMiC,EAAa,CACjB,KAAM,mBACN,KAAM,GACN,KAAM,CACJ,CACE,OACA,CACE,EAAG,iHACH,IAAK,QACP,CACF,EACA,CAAC,OAAQ,CAAE,EAAG,0BAA2B,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,EACxC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,EACzC,CAAC,OAAQ,CAAE,EAAG,UAAW,IAAK,QAAS,CAAC,EACxC,CAAC,OAAQ,CAAE,EAAG,WAAY,IAAK,QAAS,CAAC,CAC3C,CACF,EACAA,EAAW,KACX,IAAMC,GAAkBtB,EAAiBqB,CAAU,wBCvB7CI,GAAY,GAAkB,WAAW,KAAKR,CAAI,EAAI,IAAIA,EAAK,QAAQ,KAAM,IAAI,EAAE,GAAKA,EAMjFS,IAAiB,EAAmB,IAAsB,CACrE,IAAMC,EAAQ,CAAC,GAAGC,CAAI,CAAC,CACpB,MAAM,EAAG,IAAMjC,EAAE,KAAOkC,EAAE,IAAI,CAAC,CAC/B,IAAK,GAAQ,CAAC,GAAGC,EAAQ,KAAK,EAAG,IAAWX,EAASY,EAAI,MAAMC,IAAW,IAAI,CAAC,EAAG,OAAOD,EAAI,IAAI,EAAGA,EAAI,SAAS,KAAK,IAAI,CAAC,CAAC,EAC/H,MAAO,IAAI,CAAC,CAAC,GAAGD,EAAS1C,EAAQ,MAAM,EAAGA,EAAQ,UAAU,CAAC,EAAG,GAAGuC,CAAK,CAAC,CAAC,IAAK,GAAWM,EAAO,IAAIR,EAAQ,CA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,OAAM,QAAO,MAAOF,GAAW,OAAQ7M,EAAa,CAAE,CAAC,IAC1E,CACP,IAAMsN,EAAQ,MAAMP,EAAO,QAAQ,EACnC,GAAIO,EAAM,OAAS,QAAS,MAAU,MAAMA,EAAM,OAAO,EACzD,GAAIA,EAAM,OAAS,MAAO,OAC1B,GAAIA,EAAM,OAAS,OAAQ,MAAU,MAAM,6BAA6BA,EAAM,KAAK,WAAW,EAC9F,MAAMA,EAAM,KACZP,EAAO,KAAK,CAAE,KAAM,MAAO,CAAC,CAC9B,CACF,QAAU,CACRA,EAAO,KAAK,CACd,CACF,CACF","debugId":"0d2aed44-9e5d-4aaf-b208-23d9f622ae5e"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sign-in-policy-page-CUiU8ZIN.js","names":["useState","useState","_Fragment","n","a","t","__toESM","require_react","require_jsx_runtime","cn","formatDateTime","SectionError","useAuth","AuthError","AccountSection","Badge","Spinner","authMessage","formatTag","Button","text","PageHeader","import_react","onOff","optionalRequiredOff","policyRows","ruleLabel","label","row","method","option","rule","import_jsx_runtime","RuleChoice","value","onChange","rowNote","mail","draft","policy","effective","rowsFor","operator","platformProviders","SignInPolicyForm","setDraft","state","rows","changed","event","onSave","note","error","notice","busy","stateOf","entry","now","StaffSignInLog","signIns","StaffSignIns","setSignIns","setError","session","failure","SignInPolicyPage","setState","setBusy","setNotice","save"],"sources":["../../../src/account/sign-in-policy-labels.ts","../../../src/account/sign-in-policy-form.tsx","../../../src/account/staff-sign-in-log.tsx","../../../src/account/sign-in-policy-page.tsx"],"sourcesContent":["import type { SignInPolicy, SignInRule, StaffAccessRule } from '@protobase/client'\nimport { text } from './messages'\n\nexport type PolicyMethod = keyof SignInPolicy\n\n/** A rule any row takes; each row offers only its own. */\nexport type PolicyRule = SignInRule | StaffAccessRule\n\nexport type PolicyRow = { method: PolicyMethod; label: string; description: string; rules: Array<{ value: PolicyRule; label: string }> }\n\nconst onOff = () => [\n { value: 'allowed', label: text('on') },\n { value: 'forbidden', label: text('off') },\n] satisfies PolicyRow['rules']\n\nconst optionalRequiredOff = () => [\n { value: 'allowed', label: text('optional') },\n { value: 'required', label: text('required') },\n { value: 'forbidden', label: text('off') },\n] satisfies PolicyRow['rules']\n\n/** The rows of the sign-in policy page, in order, with the rules each method takes and their words. */\nexport const policyRows = (): PolicyRow[] => [\n { method: 'password', label: text('password'), description: text('passwordDescription'), rules: onOff() },\n { method: 'emailCode', label: text('emailedSignInCode'), description: text('emailedSignInCodeDescription'), rules: onOff() },\n {\n method: 'passkey',\n label: text('passkeys'),\n description: text('passkeysPolicyDescription'),\n rules: optionalRequiredOff(),\n },\n {\n method: 'twoFactor',\n label: text('twoFactor'),\n description: text('twoFactorPolicyDescription'),\n rules: optionalRequiredOff(),\n },\n {\n method: 'staffAccess',\n label: text('staffAccess'),\n description: text('staffAccessDescription'),\n rules: [\n { value: 'allowed', label: text('on') },\n { value: 'notify', label: text('emailThePerson') },\n { value: 'forbidden', label: text('off') },\n ],\n },\n {\n method: 'platformSignIn',\n label: text('platformSignIn'),\n description: text('platformSignInDescription'),\n rules: onOff(),\n },\n]\n\n/** The word for `rule` in `method`'s row, for example \"Optional\" for an allowed passkey. Every rule the server stores has one. */\nexport const ruleLabel = (method: PolicyMethod, rule: PolicyRule) => {\n const label = policyRows().find((row) => row.method === method)?.rules.find((option) => option.value === rule)?.label\n if (label === undefined) throw new Error(`No label for the ${rule} rule of ${method}`)\n return label\n}\n","import { useState } from 'react'\nimport type { SignInPolicy, SignInPolicyState } from '@protobase/client'\nimport { formatDateTime } from '../format'\nimport { formatTag } from '../locale/active-locale'\nimport { cn } from '../lib/cn'\nimport { Button } from '../primitives/button'\nimport { policyRows, ruleLabel, type PolicyRow, type PolicyRule } from './sign-in-policy-labels'\nimport { text } from './messages'\n\nexport type SignInPolicyFormProps = {\n /** The saved policy, how it applies, and whether mail is on. */\n state: SignInPolicyState\n /** Called with the edited policy; the page shows `error` when the server refuses it. */\n onSave: (policy: SignInPolicy) => void\n busy?: boolean\n error?: string\n /** Shown after a save went through. */\n notice?: string\n}\n\nconst RuleChoice = ({ row, value, onChange }: { row: PolicyRow; value: PolicyRule; onChange: (rule: PolicyRule) => void }) => (\n <span role=\"radiogroup\" aria-label={row.label} className=\"inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5\">\n {row.rules.map((option) => (\n <button\n key={option.value}\n type=\"button\"\n role=\"radio\"\n aria-checked={option.value === value}\n onClick={() => onChange(option.value)}\n className={cn('rounded px-3 text-body font-medium transition-colors', option.value === value ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground')}\n >\n {option.label}\n </button>\n ))}\n </span>\n)\n\n// What the row says when the policy applies differently than it reads, or needs something the server lacks.\nconst rowNote = ({ method }: PolicyRow, draft: SignInPolicy, { mail, effective, policy }: SignInPolicyState) => {\n if (method === 'emailCode' && !mail) return text('codeNeedsMail')\n if (method === 'password' && !mail && draft.password === 'forbidden') return text('passwordStaysOn')\n if (method === 'staffAccess' && !mail && draft.staffAccess === 'notify') return text('staffNeedsMail')\n if (method === 'platformSignIn' && draft.platformSignIn === 'allowed' && draft.passkey === 'required') {\n return text('platformOff')\n }\n if (draft[method] === policy[method] && effective[method] !== policy[method]) return text('appliesAs', { rule: ruleLabel(method, effective[method]) })\n return undefined\n}\n\n// The rows that apply to this app: staff access with an operator provider, sign-in through the platform with its providers.\nconst rowsFor = ({ operator, platformProviders = [] }: SignInPolicyState) =>\n policyRows().flatMap((row) => {\n if (row.method === 'staffAccess' && !operator) return []\n if (row.method === 'platformSignIn') {\n return platformProviders.length > 0 ? [{ ...row, label: text('platformSignInWith', { provider: new Intl.ListFormat(formatTag(), { type: 'conjunction' }).format(platformProviders) }) }] : []\n }\n return [row]\n })\n\n/**\n * The admin's sign-in policy: for each way to sign in, whether people may use it, must set it up, or cannot use it;\n * when the app has an operator provider, whether its staff may sign in as people; and when the platform adds a sign-in\n * provider, whether people may use it.\n */\nexport const SignInPolicyForm = ({ state, onSave, busy, error, notice }: SignInPolicyFormProps) => {\n const [draft, setDraft] = useState(state.policy)\n const rows = rowsFor(state)\n const changed = rows.some(({ method }) => draft[method] !== state.policy[method])\n\n return (\n <form\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n onSave(draft)\n }}\n >\n <ul className=\"divide-y rounded-lg border bg-background\">\n {rows.map((row) => {\n const note = rowNote(row, draft, state)\n return (\n <li key={row.method} className=\"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between\">\n <div className=\"min-w-0\">\n <h2 className=\"font-semibold\">{row.label}</h2>\n <p className=\"mt-0.5 text-muted-foreground\">{row.description}</p>\n {note && <p className=\"mt-1.5 text-xs font-medium text-warning-text\">{note}</p>}\n </div>\n <RuleChoice row={row} value={draft[row.method]} onChange={(rule) => setDraft({ ...draft, [row.method]: rule } as SignInPolicy)} />\n </li>\n )\n })}\n </ul>\n {error && (\n <p role=\"alert\" className=\"rounded-md bg-danger-soft px-3 py-2 text-body font-medium text-danger-text\">\n {error}\n </p>\n )}\n {notice && !changed && (\n <p role=\"status\" className=\"rounded-md bg-success-soft px-3 py-2 text-body font-medium text-success-text\">\n {notice}\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <p className=\"text-xs text-muted-foreground\">{state.savedAt ? (state.savedBy ? text('lastSavedBy', { name: state.savedBy, time: formatDateTime(Date.parse(state.savedAt)) }) : text('lastSaved', { time: formatDateTime(Date.parse(state.savedAt)) })) : text('neverChanged')}</p>\n <div className=\"flex gap-2\">\n {changed && <Button onClick={() => setDraft(state.policy)}>{text('reset')}</Button>}\n <Button variant=\"primary\" type=\"submit\" loading={busy} disabled={!changed}>\n {text('save')}\n </Button>\n </div>\n </div>\n </form>\n )\n}\n","import type { StaffSignIn } from '@protobase/client'\nimport { formatDateTime } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { AccountSection, SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type StaffSignInLogProps = {\n /** Newest first; `undefined` while loading. */\n signIns?: StaffSignIn[]\n /** The operator provider's name, for the description. */\n operator: string\n error?: string\n /** Now in milliseconds, to tell running sessions from expired ones; stories pin it. */\n now?: number\n}\n\nconst stateOf = (entry: StaffSignIn, now: number) =>\n entry.endedAt ? (\n <Badge tone=\"neutral\">{text('stopped', { time: formatDateTime(Date.parse(entry.endedAt)) })}</Badge>\n ) : Date.parse(entry.expiresAt) <= now ? (\n <Badge tone=\"neutral\">{text('ended', { time: formatDateTime(Date.parse(entry.expiresAt)) })}</Badge>\n ) : (\n <Badge tone=\"amber\">{text('signedInUntil', { time: formatDateTime(Date.parse(entry.expiresAt)) })}</Badge>\n )\n\n/** The app's log of staff sign-ins, for admins: who signed in as whom, why, and when. */\nexport const StaffSignInLog = ({ signIns, operator, error, now = Date.now() }: StaffSignInLogProps) => (\n <AccountSection title={text('staffSignIns')} description={text('staffSignInsDescription', { operator })}>\n <SectionError message={error} />\n {signIns && signIns.length === 0 && <p className=\"text-muted-foreground\">{text('noStaffSignIns')}</p>}\n {signIns && signIns.length > 0 && (\n <ul className=\"divide-y rounded-md border\">\n {signIns.map((entry) => (\n <li key={entry.id} className=\"flex flex-col gap-1.5 p-3\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"font-medium break-all\">{entry.staffName ? `${entry.staffName} (${entry.staff})` : entry.staff}</span>\n <span className=\"text-muted-foreground\">{text('as')}</span>\n <span className=\"font-medium break-all\">{entry.user}</span>\n </div>\n <p className=\"break-words\">{entry.reason}</p>\n <div className=\"flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <span>{formatDateTime(Date.parse(entry.startedAt))}</span>\n {stateOf(entry, now)}\n </div>\n </li>\n ))}\n </ul>\n )}\n </AccountSection>\n)\n","import { useEffect, useState } from 'react'\nimport { AuthError, type SignInPolicy, type SignInPolicyState, type StaffSignIn } from '@protobase/client'\nimport { PageHeader } from '../app-shell'\nimport { authMessage } from '../auth/auth-messages'\nimport { useAuth } from '../auth/auth-provider'\nimport { Spinner } from '../primitives/spinner'\nimport { SignInPolicyForm } from './sign-in-policy-form'\nimport { StaffSignInLog } from './staff-sign-in-log'\nimport { text } from './messages'\n\nconst StaffSignIns = ({ operator }: { operator: string }) => {\n const { session } = useAuth()\n const [signIns, setSignIns] = useState<StaffSignIn[]>()\n const [error, setError] = useState<string>()\n useEffect(() => {\n void session.staff.log().then(setSignIns, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadStaffSignIns')))\n }, [session])\n return <StaffSignInLog operator={operator} signIns={signIns} error={error} />\n}\n\n/**\n * The admin page for the sign-in policy; the server refuses a policy that would lock people out, and the page says why.\n * With an operator provider, the log of staff sign-ins follows the policy.\n */\nexport const SignInPolicyPage = () => {\n const { session } = useAuth()\n const [state, setState] = useState<SignInPolicyState>()\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [notice, setNotice] = useState<string>()\n\n useEffect(() => {\n void session.signInPolicy.read().then(setState, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadPolicy')))\n }, [session])\n\n const save = async (policy: SignInPolicy) => {\n setBusy(true)\n setError(undefined)\n setNotice(undefined)\n try {\n setState(await session.signInPolicy.save(policy))\n setNotice(text('policySaved'))\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <div className=\"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6\">\n <PageHeader title={text('signInPolicy')} subtitle={text('policySubtitle')} />\n {state ? (\n <>\n <SignInPolicyForm key={state.savedAt ?? 'default'} state={state} busy={busy} error={error} notice={notice} onSave={(policy) => void save(policy)} />\n {state.operator && <StaffSignIns operator={state.operator} />}\n </>\n ) : error ? (\n <p role=\"alert\" className=\"text-danger-text\">\n {error}\n </p>\n ) : (\n <div className=\"flex items-center gap-2 text-muted-foreground\">\n <Spinner /> {text('loading')}\n </div>\n )}\n </div>\n )\n}\n"],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AO,IAAyB,CAC3CF,EAAQ,EAAI,EACZL,EAAS,IAAA,EAAS,EAClBM,EAAU,IAAA,EAAS,EACnB,GAAI,CACFF,EAAS,MAAMH,EAAQ,aAAa,KAAKxB,CAAM,CAAC,EAChD6B,EAAUhD,EAAK,aAAa,CAAC,CAC/B,OAAS4C,EAAS,CAChB,GAAI,EAAEA,aAAmBnD,GAAY,MAAMmD,EAC3CF,EAAS7C,EAAY+C,CAAO,CAAC,CAC/B,CACAG,EAAQ,EAAK,CACf,EAEA,OACE,EAAAnC,EAAA,KAAA,CAAC,MAAD,CAAK,UAAU,iEAAf,SAAA,EACE,EAAAA,EAAA,IAAA,CAACX,EAAD,CAAY,MAAOD,EAAK,cAAc,EAAG,SAAUA,EAAK,gBAAgB,CAAI,CAAA,EAC3E0B,GACC,EAAAd,EAAA,KAAA,CAAA9B,EAAAA,SAAA,CAAA,SAAA,EACE,EAAA8B,EAAA,IAAA,CAACY,EAAD,CAA0D,QAAa,OAAa,QAAe,SAAQ,OAAS,GAAW,KAAKyB,EAAK9B,CAAM,CAAI,EAA5HO,EAAM,SAAW,SAA2G,EAClJA,EAAM,WAAY,EAAAd,EAAA,IAAA,CAAC4B,EAAD,CAAc,SAAUd,EAAM,QAAW,CAAA,CAC5D,CAAA,CAAA,EACAM,GACF,EAAApB,EAAA,IAAA,CAAC,IAAD,CAAG,KAAK,QAAQ,UAAU,mBACvB,SAAAoB,CACA,CAAA,GAEH,EAAApB,EAAA,KAAA,CAAC,MAAD,CAAK,UAAU,gDAAf,SAAA,EACE,EAAAA,EAAA,IAAA,CAAChB,EAAD,CAAU,CAAA,EAAC,IAAEI,EAAK,SAAS,CACxB,CAEJ,CAAA,CAAA,GAET","debugId":"94894f19-20d1-4ef5-8aaf-2ab700c58138"}
|
|
1
|
+
{"version":3,"file":"sign-in-policy-page-DINzAtyt.js","names":["useState","useState","_Fragment","n","a","t","__toESM","require_react","require_jsx_runtime","AccountSection","text","AuthError","formatTag","formatDateTime","SectionError","Button","authMessage","Spinner","Badge","cn","useAuth","PageHeader","import_react","onOff","optionalRequiredOff","policyRows","ruleLabel","label","row","method","option","rule","import_jsx_runtime","RuleChoice","value","onChange","rowNote","mail","draft","policy","effective","rowsFor","operator","platformProviders","SignInPolicyForm","setDraft","state","rows","changed","event","onSave","note","error","notice","busy","stateOf","entry","now","StaffSignInLog","signIns","StaffSignIns","setSignIns","setError","session","failure","SignInPolicyPage","setState","setBusy","setNotice","save"],"sources":["../../../src/account/sign-in-policy-labels.ts","../../../src/account/sign-in-policy-form.tsx","../../../src/account/staff-sign-in-log.tsx","../../../src/account/sign-in-policy-page.tsx"],"sourcesContent":["import type { SignInPolicy, SignInRule, StaffAccessRule } from '@protobase/client'\nimport { text } from './messages'\n\nexport type PolicyMethod = keyof SignInPolicy\n\n/** A rule any row takes; each row offers only its own. */\nexport type PolicyRule = SignInRule | StaffAccessRule\n\nexport type PolicyRow = { method: PolicyMethod; label: string; description: string; rules: Array<{ value: PolicyRule; label: string }> }\n\nconst onOff = () => [\n { value: 'allowed', label: text('on') },\n { value: 'forbidden', label: text('off') },\n] satisfies PolicyRow['rules']\n\nconst optionalRequiredOff = () => [\n { value: 'allowed', label: text('optional') },\n { value: 'required', label: text('required') },\n { value: 'forbidden', label: text('off') },\n] satisfies PolicyRow['rules']\n\n/** The rows of the sign-in policy page, in order, with the rules each method takes and their words. */\nexport const policyRows = (): PolicyRow[] => [\n { method: 'password', label: text('password'), description: text('passwordDescription'), rules: onOff() },\n { method: 'emailCode', label: text('emailedSignInCode'), description: text('emailedSignInCodeDescription'), rules: onOff() },\n {\n method: 'passkey',\n label: text('passkeys'),\n description: text('passkeysPolicyDescription'),\n rules: optionalRequiredOff(),\n },\n {\n method: 'twoFactor',\n label: text('twoFactor'),\n description: text('twoFactorPolicyDescription'),\n rules: optionalRequiredOff(),\n },\n {\n method: 'staffAccess',\n label: text('staffAccess'),\n description: text('staffAccessDescription'),\n rules: [\n { value: 'allowed', label: text('on') },\n { value: 'notify', label: text('emailThePerson') },\n { value: 'forbidden', label: text('off') },\n ],\n },\n {\n method: 'platformSignIn',\n label: text('platformSignIn'),\n description: text('platformSignInDescription'),\n rules: onOff(),\n },\n]\n\n/** The word for `rule` in `method`'s row, for example \"Optional\" for an allowed passkey. Every rule the server stores has one. */\nexport const ruleLabel = (method: PolicyMethod, rule: PolicyRule) => {\n const label = policyRows().find((row) => row.method === method)?.rules.find((option) => option.value === rule)?.label\n if (label === undefined) throw new Error(`No label for the ${rule} rule of ${method}`)\n return label\n}\n","import { useState } from 'react'\nimport type { SignInPolicy, SignInPolicyState } from '@protobase/client'\nimport { formatDateTime } from '../format'\nimport { formatTag } from '../locale/active-locale'\nimport { cn } from '../lib/cn'\nimport { Button } from '../primitives/button'\nimport { policyRows, ruleLabel, type PolicyRow, type PolicyRule } from './sign-in-policy-labels'\nimport { text } from './messages'\n\nexport type SignInPolicyFormProps = {\n /** The saved policy, how it applies, and whether mail is on. */\n state: SignInPolicyState\n /** Called with the edited policy; the page shows `error` when the server refuses it. */\n onSave: (policy: SignInPolicy) => void\n busy?: boolean\n error?: string\n /** Shown after a save went through. */\n notice?: string\n}\n\nconst RuleChoice = ({ row, value, onChange }: { row: PolicyRow; value: PolicyRule; onChange: (rule: PolicyRule) => void }) => (\n <span role=\"radiogroup\" aria-label={row.label} className=\"inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5\">\n {row.rules.map((option) => (\n <button\n key={option.value}\n type=\"button\"\n role=\"radio\"\n aria-checked={option.value === value}\n onClick={() => onChange(option.value)}\n className={cn('rounded px-3 text-body font-medium transition-colors', option.value === value ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground')}\n >\n {option.label}\n </button>\n ))}\n </span>\n)\n\n// What the row says when the policy applies differently than it reads, or needs something the server lacks.\nconst rowNote = ({ method }: PolicyRow, draft: SignInPolicy, { mail, effective, policy }: SignInPolicyState) => {\n if (method === 'emailCode' && !mail) return text('codeNeedsMail')\n if (method === 'password' && !mail && draft.password === 'forbidden') return text('passwordStaysOn')\n if (method === 'staffAccess' && !mail && draft.staffAccess === 'notify') return text('staffNeedsMail')\n if (method === 'platformSignIn' && draft.platformSignIn === 'allowed' && draft.passkey === 'required') {\n return text('platformOff')\n }\n if (draft[method] === policy[method] && effective[method] !== policy[method]) return text('appliesAs', { rule: ruleLabel(method, effective[method]) })\n return undefined\n}\n\n// The rows that apply to this app: staff access with an operator provider, sign-in through the platform with its providers.\nconst rowsFor = ({ operator, platformProviders = [] }: SignInPolicyState) =>\n policyRows().flatMap((row) => {\n if (row.method === 'staffAccess' && !operator) return []\n if (row.method === 'platformSignIn') {\n return platformProviders.length > 0 ? [{ ...row, label: text('platformSignInWith', { provider: new Intl.ListFormat(formatTag(), { type: 'conjunction' }).format(platformProviders) }) }] : []\n }\n return [row]\n })\n\n/**\n * The admin's sign-in policy: for each way to sign in, whether people may use it, must set it up, or cannot use it;\n * when the app has an operator provider, whether its staff may sign in as people; and when the platform adds a sign-in\n * provider, whether people may use it.\n */\nexport const SignInPolicyForm = ({ state, onSave, busy, error, notice }: SignInPolicyFormProps) => {\n const [draft, setDraft] = useState(state.policy)\n const rows = rowsFor(state)\n const changed = rows.some(({ method }) => draft[method] !== state.policy[method])\n\n return (\n <form\n className=\"flex flex-col gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n onSave(draft)\n }}\n >\n <ul className=\"divide-y rounded-lg border bg-background\">\n {rows.map((row) => {\n const note = rowNote(row, draft, state)\n return (\n <li key={row.method} className=\"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between\">\n <div className=\"min-w-0\">\n <h2 className=\"font-semibold\">{row.label}</h2>\n <p className=\"mt-0.5 text-muted-foreground\">{row.description}</p>\n {note && <p className=\"mt-1.5 text-xs font-medium text-warning-text\">{note}</p>}\n </div>\n <RuleChoice row={row} value={draft[row.method]} onChange={(rule) => setDraft({ ...draft, [row.method]: rule } as SignInPolicy)} />\n </li>\n )\n })}\n </ul>\n {error && (\n <p role=\"alert\" className=\"rounded-md bg-danger-soft px-3 py-2 text-body font-medium text-danger-text\">\n {error}\n </p>\n )}\n {notice && !changed && (\n <p role=\"status\" className=\"rounded-md bg-success-soft px-3 py-2 text-body font-medium text-success-text\">\n {notice}\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <p className=\"text-xs text-muted-foreground\">{state.savedAt ? (state.savedBy ? text('lastSavedBy', { name: state.savedBy, time: formatDateTime(Date.parse(state.savedAt)) }) : text('lastSaved', { time: formatDateTime(Date.parse(state.savedAt)) })) : text('neverChanged')}</p>\n <div className=\"flex gap-2\">\n {changed && <Button onClick={() => setDraft(state.policy)}>{text('reset')}</Button>}\n <Button variant=\"primary\" type=\"submit\" loading={busy} disabled={!changed}>\n {text('save')}\n </Button>\n </div>\n </div>\n </form>\n )\n}\n","import type { StaffSignIn } from '@protobase/client'\nimport { formatDateTime } from '../format'\nimport { Badge } from '../primitives/badge'\nimport { AccountSection, SectionError } from './account-section'\nimport { text } from './messages'\n\nexport type StaffSignInLogProps = {\n /** Newest first; `undefined` while loading. */\n signIns?: StaffSignIn[]\n /** The operator provider's name, for the description. */\n operator: string\n error?: string\n /** Now in milliseconds, to tell running sessions from expired ones; stories pin it. */\n now?: number\n}\n\nconst stateOf = (entry: StaffSignIn, now: number) =>\n entry.endedAt ? (\n <Badge tone=\"neutral\">{text('stopped', { time: formatDateTime(Date.parse(entry.endedAt)) })}</Badge>\n ) : Date.parse(entry.expiresAt) <= now ? (\n <Badge tone=\"neutral\">{text('ended', { time: formatDateTime(Date.parse(entry.expiresAt)) })}</Badge>\n ) : (\n <Badge tone=\"amber\">{text('signedInUntil', { time: formatDateTime(Date.parse(entry.expiresAt)) })}</Badge>\n )\n\n/** The app's log of staff sign-ins, for admins: who signed in as whom, why, and when. */\nexport const StaffSignInLog = ({ signIns, operator, error, now = Date.now() }: StaffSignInLogProps) => (\n <AccountSection title={text('staffSignIns')} description={text('staffSignInsDescription', { operator })}>\n <SectionError message={error} />\n {signIns && signIns.length === 0 && <p className=\"text-muted-foreground\">{text('noStaffSignIns')}</p>}\n {signIns && signIns.length > 0 && (\n <ul className=\"divide-y rounded-md border\">\n {signIns.map((entry) => (\n <li key={entry.id} className=\"flex flex-col gap-1.5 p-3\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"font-medium break-all\">{entry.staffName ? `${entry.staffName} (${entry.staff})` : entry.staff}</span>\n <span className=\"text-muted-foreground\">{text('as')}</span>\n <span className=\"font-medium break-all\">{entry.user}</span>\n </div>\n <p className=\"break-words\">{entry.reason}</p>\n <div className=\"flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <span>{formatDateTime(Date.parse(entry.startedAt))}</span>\n {stateOf(entry, now)}\n </div>\n </li>\n ))}\n </ul>\n )}\n </AccountSection>\n)\n","import { useEffect, useState } from 'react'\nimport { AuthError, type SignInPolicy, type SignInPolicyState, type StaffSignIn } from '@protobase/client'\nimport { PageHeader } from '../app-shell'\nimport { authMessage } from '../auth/auth-messages'\nimport { useAuth } from '../auth/auth-provider'\nimport { Spinner } from '../primitives/spinner'\nimport { SignInPolicyForm } from './sign-in-policy-form'\nimport { StaffSignInLog } from './staff-sign-in-log'\nimport { text } from './messages'\n\nconst StaffSignIns = ({ operator }: { operator: string }) => {\n const { session } = useAuth()\n const [signIns, setSignIns] = useState<StaffSignIn[]>()\n const [error, setError] = useState<string>()\n useEffect(() => {\n void session.staff.log().then(setSignIns, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadStaffSignIns')))\n }, [session])\n return <StaffSignInLog operator={operator} signIns={signIns} error={error} />\n}\n\n/**\n * The admin page for the sign-in policy; the server refuses a policy that would lock people out, and the page says why.\n * With an operator provider, the log of staff sign-ins follows the policy.\n */\nexport const SignInPolicyPage = () => {\n const { session } = useAuth()\n const [state, setState] = useState<SignInPolicyState>()\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string>()\n const [notice, setNotice] = useState<string>()\n\n useEffect(() => {\n void session.signInPolicy.read().then(setState, (failure: unknown) => setError(failure instanceof AuthError ? authMessage(failure) : text('couldNotReadPolicy')))\n }, [session])\n\n const save = async (policy: SignInPolicy) => {\n setBusy(true)\n setError(undefined)\n setNotice(undefined)\n try {\n setState(await session.signInPolicy.save(policy))\n setNotice(text('policySaved'))\n } catch (failure) {\n if (!(failure instanceof AuthError)) throw failure\n setError(authMessage(failure))\n }\n setBusy(false)\n }\n\n return (\n <div className=\"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6\">\n <PageHeader title={text('signInPolicy')} subtitle={text('policySubtitle')} />\n {state ? (\n <>\n <SignInPolicyForm key={state.savedAt ?? 'default'} state={state} busy={busy} error={error} notice={notice} onSave={(policy) => void save(policy)} />\n {state.operator && <StaffSignIns operator={state.operator} />}\n </>\n ) : error ? (\n <p role=\"alert\" className=\"text-danger-text\">\n {error}\n </p>\n ) : (\n <div className=\"flex items-center gap-2 text-muted-foreground\">\n <Spinner /> {text('loading')}\n </div>\n )}\n </div>\n )\n}\n"],"mappings":"qvBAUMuB,MAAc,CAClB,CAAE,MAAO,UAAW,MAAOb,EAAK,IAAI,CAAE,EACtC,CAAE,MAAO,YAAa,MAAOA,EAAK,KAAK,CAAE,CAC3C,EAEMc,MAA4B,CAChC,CAAE,MAAO,UAAW,MAAOd,EAAK,UAAU,CAAE,EAC5C,CAAE,MAAO,WAAY,MAAOA,EAAK,UAAU,CAAE,EAC7C,CAAE,MAAO,YAAa,MAAOA,EAAK,KAAK,CAAE,CAC3C,EAGae,MAAgC,CAC3C,CAAE,OAAQ,WAAY,MAAOf,EAAK,UAAU,EAAG,YAAaA,EAAK,qBAAqB,EAAG,MAAOa,EAAM,CAAE,EACxG,CAAE,OAAQ,YAAa,MAAOb,EAAK,mBAAmB,EAAG,YAAaA,EAAK,8BAA8B,EAAG,MAAOa,EAAM,CAAE,EAC3H,CACE,OAAQ,UACR,MAAOb,EAAK,UAAU,EACtB,YAAaA,EAAK,2BAA2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CAA0D,QAAa,OAAa,QAAe,SAAQ,OAAS,GAAW,KAAKyB,EAAK9B,CAAM,CAAI,EAA5HO,EAAM,SAAW,SAA2G,EAClJA,EAAM,WAAY,EAAAd,EAAA,IAAA,CAAC4B,EAAD,CAAc,SAAUd,EAAM,QAAW,CAAA,CAC5D,CAAA,CAAA,EACAM,GACF,EAAApB,EAAA,IAAA,CAAC,IAAD,CAAG,KAAK,QAAQ,UAAU,mBACvB,SAAAoB,CACA,CAAA,GAEH,EAAApB,EAAA,KAAA,CAAC,MAAD,CAAK,UAAU,gDAAf,SAAA,EACE,EAAAA,EAAA,IAAA,CAACf,EAAD,CAAU,CAAA,EAAC,IAAEP,EAAK,SAAS,CACxB,CAEJ,CAAA,CAAA,GAET","debugId":"c837302d-cadc-458d-b6e4-ffddf85e0eb3"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-block-queries-DUvYFyeX.js","names":["useMemo","n","a","t","__toESM","require_react","elementAt","fillProps","listPagesQuery","columnName","aggregateQuery","useProjectUi","useIsXs","threadSort","listLabels","phoneSpecs","useAdminMeta","defaultOrderBy","usePageParamValues","countQuery","useClient","useScopeStack","listPageQuery","usePageParamsGiven","propsOf","firstRecordQuery","embeddedFields","rootRecordOf","useQueryClient","recordRowRead","chartAggregate","embeddedRowsQuery","liveFirstPageQuery","import_react","blockQuery","options","queryClient","blockPages","byType","node","model","resource","reader","read","key","select","view","readFields","columns","sort","resources","params","views","client","orderBy","limit","filter","calls","labels","sender","time","conditionCount","blockQueries","plan","tree","queries","StartBlockQueries","fieldTypes","xs","given","root","started","query"],"sources":["../../../src/app/pages/block-query.ts","../../../src/app/pages/blocks/chart-query.ts","../../../src/app/pages/blocks/record-cards-query.ts","../../../src/app/pages/blocks/record-row-query.ts","../../../src/app/pages/blocks/table-query.ts","../../../src/app/pages/blocks/thread-query.ts","../../../src/app/pages/block-queries.ts","../../../src/app/pages/start-block-queries.tsx"],"sourcesContent":["import type { FetchInfiniteQueryOptions, FetchQueryOptions, QueryClient, QueryKey } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { LayoutNode, PlanRead } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport type { FieldWidget } from '../field-types/field-widget'\n\n// A block that reads by itself, with labels, photos, totals or pages its planned read does not hold, still has its read\n// start as the page opens: the page starts the block's own query, the same key and request, so the block finds it in\n// the cache, or running, once it draws, and nothing is read twice.\n\n/** What a block's query is made with beside its element: the API, the query cache, the app's models and the screen. */\nexport type BlockReader = {\n client: Client\n queryClient: QueryClient\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n fieldTypes: Readonly<Record<string, FieldWidget>> | undefined\n /** Whether the screen is a phone's, as `useIsXs` says. */\n xs: boolean\n /** The page's parameters, as `usePageParamValues` gives them, which a `{{@params.name}}` reads. */\n params: Readonly<Record<string, string>>\n /** What the page's address holds, as `usePageParams` gives it as `given`, such as the key a `select` chose. */\n given: Readonly<Record<string, string>>\n /** The record page's own record around a block tree, which a `{{@root.name}}` reads; none on a composed page. */\n root?: Record<string, unknown>\n}\n\n/** What a page's planned reads are made with: a block's reader without the address, which only a `select`'s row reads. */\nexport type PlanReader = Omit<BlockReader, 'given'>\n\n/** A block's own query, started ahead of its block: its key, and how it starts, as one query or as a list's first page. */\nexport type BlockQuery = { queryKey: QueryKey; start: (queryClient: QueryClient) => Promise<void> }\n\n/** The queries a block makes for its planned read `read`, its element's `{{path}}`s filled from the page's parameters. */\nexport type BlockQueries = (node: LayoutNode, read: PlanRead, reader: BlockReader) => BlockQuery[]\n\n/** A query a block reads with `useQuery`. */\nexport const blockQuery = <T>(options: FetchQueryOptions<T>): BlockQuery => ({ queryKey: options.queryKey, start: (queryClient) => queryClient.prefetchQuery(options) })\n\n/** A query a block reads with `useInfiniteQuery`: its first page. */\nexport const blockPages = <T, P>(options: FetchInfiniteQueryOptions<T, Error, T, QueryKey, P>): BlockQuery => ({\n queryKey: options.queryKey,\n start: (queryClient) => queryClient.prefetchInfiniteQuery(options),\n})\n","import type { ChartProps } from '@protobase/layout'\nimport { chartAggregate } from '../../charts/chart-params'\nimport { aggregateQuery } from '../../../data/use-aggregates'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/** A `Chart`'s `:aggregate`, as `ChartView` reads it. */\nexport const chartQueries: BlockQueries = (node, _read, { client, resources, views }) => {\n const { resource, groupBy, splitBy, sum, average, filter, granularity, range, limit } = propsOf<ChartProps>(node)\n const model = resources[resource]\n const params = model && chartAggregate({ model, groupBy, splitBy, sum, average, filter, granularity, range, limit }, resources, views)\n return model && params ? [blockQuery(aggregateQuery(client, model.name, params))] : []\n}\n","import type { RecordCardsProps } from '@protobase/layout'\nimport { defaultOrderBy } from '../../list-order'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { countQuery, listPageQuery } from '../use-layout-data'\nimport { propsOf } from './block-props'\n\n/** A `RecordCards`' first page and how many records match in all, as `RelatedCards` reads them. */\nexport const recordCardsQueries: BlockQueries = (node, _read, { client, resources, views }) => {\n const { resource, filter = '', sort = '', limit = 10 } = propsOf<RecordCardsProps>(node)\n const model = resources[resource]\n if (!model) return []\n const orderBy = sort || defaultOrderBy(model, views[model.name])\n return [blockQuery(listPageQuery(client, model, { filter, sort: orderBy, pageSize: limit })), blockQuery(countQuery(client, model, filter))]\n}\n","import type { RecordRowProps } from '@protobase/layout'\nimport { liveFirstPageQuery } from '../../../live/use-live-rows'\nimport { recordRowRead } from '../../record-row/record-row-read'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/**\n * A `RecordRow`'s first page, as `RecordRowBody` reads it; the rows of a view with `listOf` or `searchesOf`, which read\n * the user's saved records or searches first, read as they draw.\n */\nexport const recordRowQueries: BlockQueries = (node, _read, { client, queryClient, resources, views }) => {\n const { resource, filter = '', sort = '' } = propsOf<RecordRowProps>(node)\n const model = resources[resource]\n if (!model) return []\n const view = views[model.name]\n if (view?.searchesOf || view?.listOf !== undefined) return []\n return [blockQuery(liveFirstPageQuery({ queryClient, client, resources, views, model, ...recordRowRead(model, view, { filter, sort }) }))]\n}\n","import { columnName, type TableProps } from '@protobase/layout'\nimport { embeddedFields } from '../../embedded-list/embedded-fields'\nimport { embeddedRowsQuery } from '../../embedded-list/use-embedded-rows'\nimport { defaultOrderBy } from '../../list-order'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { firstRecordQuery } from '../use-layout-data'\nimport { propsOf } from './block-props'\nimport { phoneSpecs } from './table-phone-columns'\n\n/**\n * A `Table`'s rows as `EmbeddedList` reads them, with their labels, photos and total, and with `select` the chosen\n * row as `ChosenRecord` reads it; a table of the list around it has no read of its own.\n */\nexport const tableQueries: BlockQueries = (node, read, reader) => {\n const { resource, filter = '', sort = '', columns, button, bulk = false, limit = 10, select } = propsOf<TableProps>(node)\n const model = resource === undefined ? undefined : reader.resources[resource]\n if (!model) return []\n if (read.part === 'chosen') {\n // The key `SelectTable` reads: the address's, not a SelectInput's value\n const key = select === undefined ? undefined : reader.given[select]\n return key ? [blockQuery(firstRecordQuery(reader.client, model, { key }))] : []\n }\n const view = reader.views[model.name]\n const { fields, read: readFields } = embeddedFields({ ...reader, model, view, columns: columns?.map(columnName), button, bulk, phoneColumns: phoneSpecs(columns) })\n return [blockQuery(embeddedRowsQuery(reader, { model, filter, orderBy: sort || defaultOrderBy(model, view), limit, fields, read: readFields }))]\n}\n","import { threadSort, type ThreadProps } from '@protobase/layout'\nimport { listPagesQuery } from '../../../data/use-list'\nimport { listLabels } from '../../../live/relation-labels'\nimport { blockPages, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/** A `Thread`'s latest messages, their senders named, and its `calls` part the latest tool calls, as `MessageThread` reads them. */\nexport const threadQueries: BlockQueries = (node, read, { client, resources, views }) => {\n const { resource, filter, sender, time, calls, limit = 50 } = propsOf<ThreadProps>(node)\n if (read.part === 'calls') {\n const model = calls && resources[calls.resource]\n return model ? [blockPages(listPagesQuery(client, model.name, { filter: calls.filter, orderBy: threadSort(calls.time), pageSize: limit }))] : []\n }\n const model = resources[resource]\n if (!model) return []\n const labels = listLabels(resources, views, model, sender === undefined ? [] : [sender])\n return [blockPages(listPagesQuery(client, model.name, { filter, orderBy: threadSort(time), pageSize: limit, labels }))]\n}\n","import { elementAt, fillProps, type LayoutNode, type ReadPlan } from '@protobase/layout'\nimport { blockQuery, type BlockQueries, type BlockQuery, type BlockReader } from './block-query'\nimport { chartQueries } from './blocks/chart-query'\nimport { recordCardsQueries } from './blocks/record-cards-query'\nimport { recordRowQueries } from './blocks/record-row-query'\nimport { tableQueries } from './blocks/table-query'\nimport { threadQueries } from './blocks/thread-query'\nimport { countQuery } from './use-layout-data'\n\n/** The blocks that read by themselves, by type, each with the queries it makes. */\nconst byType: Record<string, BlockQueries> = {\n Table: tableQueries,\n Chart: chartQueries,\n RecordCards: recordCardsQueries,\n RecordRow: recordRowQueries,\n Thread: threadQueries,\n}\n\n// A `<resource>.count` a condition names counts all of the resource's records the reader may see, as `useStackConditions` reads it\nconst conditionCount: BlockQueries = (_node, read, { client, resources }) => {\n const model = resources[read.resource]\n return model ? [blockQuery(countQuery(client, model))] : []\n}\n\n/**\n * The queries of the blocks that read by themselves, started as the page opens with the queries of its planned reads,\n * whatever a condition says. A block inside the records of another (a read that splits) draws from the page's planned\n * reads instead, which `planQueries` starts.\n */\nexport const blockQueries = (reader: BlockReader, tree: LayoutNode, plan: ReadPlan | undefined): BlockQuery[] =>\n (plan?.reads ?? []).flatMap((read) => {\n const node = elementAt(tree, read.block)\n if (!node || node.custom) return []\n if (read.part === 'condition') return conditionCount(node, read, reader)\n if (read.split) return []\n const queries = byType[node.type]\n return queries ? queries(fillProps(node, { stack: [], params: reader.params, ...(reader.root && { root: reader.root }) }), read, reader) : []\n })\n","import { useQueryClient } from '@tanstack/react-query'\nimport { useEffect, useMemo } from 'react'\nimport type { LayoutNode, ReadPlan } from '@protobase/layout'\nimport { useClient } from '../../data/api-provider'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { useAdminMeta } from '../meta-gate'\nimport { blockQueries } from './block-queries'\nimport { usePageParamsGiven, usePageParamValues } from './page-params'\nimport { useProjectUi } from './project-ui'\nimport { rootRecordOf, useScopeStack } from './record-scope'\n\n/**\n * Starts the queries of the blocks of `plan` that read by themselves as the page opens, beside its planned reads; each\n * block then finds its own query running or answered once it draws. It draws nothing.\n */\nexport const StartBlockQueries = ({ tree, plan }: { tree: LayoutNode; plan: ReadPlan | undefined }) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const { resources, views } = useAdminMeta()\n const fieldTypes = useProjectUi().fields\n const xs = useIsXs()\n const params = usePageParamValues()\n const given = usePageParamsGiven()\n const root = rootRecordOf(useScopeStack())\n const started = useMemo(() => blockQueries({ client, queryClient, resources, views, fieldTypes, xs, params, given, ...(root && { root }) }, tree, plan), [client, queryClient, resources, views, fieldTypes, xs, params, given, root, tree, plan])\n useEffect(() => {\n for (const query of started) void query.start(queryClient)\n }, [started, queryClient])\n return null\n}\n"],"mappings":"y6BAqCakC,EAAiB,IAA+C,CAAE,SAAUC,EAAQ,SAAU,MAAQ,GAAgBC,EAAY,cAAcD,CAAO,CAAE,GAGzJE,EAAoB,IAA8E,CAC7G,SAAUF,EAAQ,SAClB,MAAQ,GAAgBC,EAAY,sBAAsBD,CAAO,CACnE,GMjCMG,EAAuC,CAC3C,OFEyC,EAAM,EAAM,IAAW,CAChE,GAAM,CAAE,WAAU,SAAS,GAAI,OAAO,GAAI,UAAS,SAAQ,OAAO,GAAO,QAAQ,GAAI,UAAWd,EAAoBe,CAAI,EAClHC,EAAQC,IAAa,IAAA,GAAY,IAAA,GAAYC,EAAO,UAAUD,GACpE,GAAI,CAACD,EAAO,MAAO,CAAC,EACpB,GAAIG,EAAK,OAAS,SAAU,CAE1B,IAAMC,EAAMC,IAAW,IAAA,GAAY,IAAA,GAAYH,EAAO,MAAMG,GAC5D,OAAOD,EAAM,CAACV,EAAWT,EAAiBiB,EA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4d34-bccb-36bdb95e2d9e"}
|
|
1
|
+
{"version":3,"file":"start-block-queries-Bc743CdL.js","names":["useMemo","n","a","t","__toESM","require_react","aggregateQuery","useIsXs","threadSort","useProjectUi","listPagesQuery","elementAt","columnName","listLabels","defaultOrderBy","propsOf","countQuery","useScopeStack","firstRecordQuery","phoneSpecs","usePageParamsGiven","fillProps","rootRecordOf","useClient","usePageParamValues","embeddedFields","listPageQuery","useAdminMeta","useQueryClient","recordRowRead","chartAggregate","embeddedRowsQuery","liveFirstPageQuery","import_react","blockQuery","options","queryClient","blockPages","byType","node","model","resource","reader","read","key","select","view","readFields","columns","sort","resources","params","views","client","orderBy","limit","filter","calls","labels","sender","time","conditionCount","blockQueries","plan","tree","queries","StartBlockQueries","fieldTypes","xs","given","root","started","query"],"sources":["../../../src/app/pages/block-query.ts","../../../src/app/pages/blocks/chart-query.ts","../../../src/app/pages/blocks/record-cards-query.ts","../../../src/app/pages/blocks/record-row-query.ts","../../../src/app/pages/blocks/table-query.ts","../../../src/app/pages/blocks/thread-query.ts","../../../src/app/pages/block-queries.ts","../../../src/app/pages/start-block-queries.tsx"],"sourcesContent":["import type { FetchInfiniteQueryOptions, FetchQueryOptions, QueryClient, QueryKey } from '@tanstack/react-query'\nimport type { Client } from '@protobase/client'\nimport type { LayoutNode, PlanRead } from '@protobase/layout'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport type { FieldWidget } from '../field-types/field-widget'\n\n// A block that reads by itself, with labels, photos, totals or pages its planned read does not hold, still has its read\n// start as the page opens: the page starts the block's own query, the same key and request, so the block finds it in\n// the cache, or running, once it draws, and nothing is read twice.\n\n/** What a block's query is made with beside its element: the API, the query cache, the app's models and the screen. */\nexport type BlockReader = {\n client: Client\n queryClient: QueryClient\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n fieldTypes: Readonly<Record<string, FieldWidget>> | undefined\n /** Whether the screen is a phone's, as `useIsXs` says. */\n xs: boolean\n /** The page's parameters, as `usePageParamValues` gives them, which a `{{@params.name}}` reads. */\n params: Readonly<Record<string, string>>\n /** What the page's address holds, as `usePageParams` gives it as `given`, such as the key a `select` chose. */\n given: Readonly<Record<string, string>>\n /** The record page's own record around a block tree, which a `{{@root.name}}` reads; none on a composed page. */\n root?: Record<string, unknown>\n}\n\n/** What a page's planned reads are made with: a block's reader without the address, which only a `select`'s row reads. */\nexport type PlanReader = Omit<BlockReader, 'given'>\n\n/** A block's own query, started ahead of its block: its key, and how it starts, as one query or as a list's first page. */\nexport type BlockQuery = { queryKey: QueryKey; start: (queryClient: QueryClient) => Promise<void> }\n\n/** The queries a block makes for its planned read `read`, its element's `{{path}}`s filled from the page's parameters. */\nexport type BlockQueries = (node: LayoutNode, read: PlanRead, reader: BlockReader) => BlockQuery[]\n\n/** A query a block reads with `useQuery`. */\nexport const blockQuery = <T>(options: FetchQueryOptions<T>): BlockQuery => ({ queryKey: options.queryKey, start: (queryClient) => queryClient.prefetchQuery(options) })\n\n/** A query a block reads with `useInfiniteQuery`: its first page. */\nexport const blockPages = <T, P>(options: FetchInfiniteQueryOptions<T, Error, T, QueryKey, P>): BlockQuery => ({\n queryKey: options.queryKey,\n start: (queryClient) => queryClient.prefetchInfiniteQuery(options),\n})\n","import type { ChartProps } from '@protobase/layout'\nimport { chartAggregate } from '../../charts/chart-params'\nimport { aggregateQuery } from '../../../data/use-aggregates'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/** A `Chart`'s `:aggregate`, as `ChartView` reads it. */\nexport const chartQueries: BlockQueries = (node, _read, { client, resources, views }) => {\n const { resource, groupBy, splitBy, sum, average, filter, granularity, range, limit } = propsOf<ChartProps>(node)\n const model = resources[resource]\n const params = model && chartAggregate({ model, groupBy, splitBy, sum, average, filter, granularity, range, limit }, resources, views)\n return model && params ? [blockQuery(aggregateQuery(client, model.name, params))] : []\n}\n","import type { RecordCardsProps } from '@protobase/layout'\nimport { defaultOrderBy } from '../../list-order'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { countQuery, listPageQuery } from '../use-layout-data'\nimport { propsOf } from './block-props'\n\n/** A `RecordCards`' first page and how many records match in all, as `RelatedCards` reads them. */\nexport const recordCardsQueries: BlockQueries = (node, _read, { client, resources, views }) => {\n const { resource, filter = '', sort = '', limit = 10 } = propsOf<RecordCardsProps>(node)\n const model = resources[resource]\n if (!model) return []\n const orderBy = sort || defaultOrderBy(model, views[model.name])\n return [blockQuery(listPageQuery(client, model, { filter, sort: orderBy, pageSize: limit })), blockQuery(countQuery(client, model, filter))]\n}\n","import type { RecordRowProps } from '@protobase/layout'\nimport { liveFirstPageQuery } from '../../../live/use-live-rows'\nimport { recordRowRead } from '../../record-row/record-row-read'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/**\n * A `RecordRow`'s first page, as `RecordRowBody` reads it; the rows of a view with `listOf` or `searchesOf`, which read\n * the user's saved records or searches first, read as they draw.\n */\nexport const recordRowQueries: BlockQueries = (node, _read, { client, queryClient, resources, views }) => {\n const { resource, filter = '', sort = '' } = propsOf<RecordRowProps>(node)\n const model = resources[resource]\n if (!model) return []\n const view = views[model.name]\n if (view?.searchesOf || view?.listOf !== undefined) return []\n return [blockQuery(liveFirstPageQuery({ queryClient, client, resources, views, model, ...recordRowRead(model, view, { filter, sort }) }))]\n}\n","import { columnName, type TableProps } from '@protobase/layout'\nimport { embeddedFields } from '../../embedded-list/embedded-fields'\nimport { embeddedRowsQuery } from '../../embedded-list/use-embedded-rows'\nimport { defaultOrderBy } from '../../list-order'\nimport { blockQuery, type BlockQueries } from '../block-query'\nimport { firstRecordQuery } from '../use-layout-data'\nimport { propsOf } from './block-props'\nimport { phoneSpecs } from './table-phone-columns'\n\n/**\n * A `Table`'s rows as `EmbeddedList` reads them, with their labels, photos and total, and with `select` the chosen\n * row as `ChosenRecord` reads it; a table of the list around it has no read of its own.\n */\nexport const tableQueries: BlockQueries = (node, read, reader) => {\n const { resource, filter = '', sort = '', columns, button, bulk = false, limit = 10, select } = propsOf<TableProps>(node)\n const model = resource === undefined ? undefined : reader.resources[resource]\n if (!model) return []\n if (read.part === 'chosen') {\n // The key `SelectTable` reads: the address's, not a SelectInput's value\n const key = select === undefined ? undefined : reader.given[select]\n return key ? [blockQuery(firstRecordQuery(reader.client, model, { key }))] : []\n }\n const view = reader.views[model.name]\n const { fields, read: readFields } = embeddedFields({ ...reader, model, view, columns: columns?.map(columnName), button, bulk, phoneColumns: phoneSpecs(columns) })\n return [blockQuery(embeddedRowsQuery(reader, { model, filter, orderBy: sort || defaultOrderBy(model, view), limit, fields, read: readFields }))]\n}\n","import { threadSort, type ThreadProps } from '@protobase/layout'\nimport { listPagesQuery } from '../../../data/use-list'\nimport { listLabels } from '../../../live/relation-labels'\nimport { blockPages, type BlockQueries } from '../block-query'\nimport { propsOf } from './block-props'\n\n/** A `Thread`'s latest messages, their senders named, and its `calls` part the latest tool calls, as `MessageThread` reads them. */\nexport const threadQueries: BlockQueries = (node, read, { client, resources, views }) => {\n const { resource, filter, sender, time, calls, limit = 50 } = propsOf<ThreadProps>(node)\n if (read.part === 'calls') {\n const model = calls && resources[calls.resource]\n return model ? [blockPages(listPagesQuery(client, model.name, { filter: calls.filter, orderBy: threadSort(calls.time), pageSize: limit }))] : []\n }\n const model = resources[resource]\n if (!model) return []\n const labels = listLabels(resources, views, model, sender === undefined ? [] : [sender])\n return [blockPages(listPagesQuery(client, model.name, { filter, orderBy: threadSort(time), pageSize: limit, labels }))]\n}\n","import { elementAt, fillProps, type LayoutNode, type ReadPlan } from '@protobase/layout'\nimport { blockQuery, type BlockQueries, type BlockQuery, type BlockReader } from './block-query'\nimport { chartQueries } from './blocks/chart-query'\nimport { recordCardsQueries } from './blocks/record-cards-query'\nimport { recordRowQueries } from './blocks/record-row-query'\nimport { tableQueries } from './blocks/table-query'\nimport { threadQueries } from './blocks/thread-query'\nimport { countQuery } from './use-layout-data'\n\n/** The blocks that read by themselves, by type, each with the queries it makes. */\nconst byType: Record<string, BlockQueries> = {\n Table: tableQueries,\n Chart: chartQueries,\n RecordCards: recordCardsQueries,\n RecordRow: recordRowQueries,\n Thread: threadQueries,\n}\n\n// A `<resource>.count` a condition names counts all of the resource's records the reader may see, as `useStackConditions` reads it\nconst conditionCount: BlockQueries = (_node, read, { client, resources }) => {\n const model = resources[read.resource]\n return model ? [blockQuery(countQuery(client, model))] : []\n}\n\n/**\n * The queries of the blocks that read by themselves, started as the page opens with the queries of its planned reads,\n * whatever a condition says. A block inside the records of another (a read that splits) draws from the page's planned\n * reads instead, which `planQueries` starts.\n */\nexport const blockQueries = (reader: BlockReader, tree: LayoutNode, plan: ReadPlan | undefined): BlockQuery[] =>\n (plan?.reads ?? []).flatMap((read) => {\n const node = elementAt(tree, read.block)\n if (!node || node.custom) return []\n if (read.part === 'condition') return conditionCount(node, read, reader)\n if (read.split) return []\n const queries = byType[node.type]\n return queries ? queries(fillProps(node, { stack: [], params: reader.params, ...(reader.root && { root: reader.root }) }), read, reader) : []\n })\n","import { useQueryClient } from '@tanstack/react-query'\nimport { useEffect, useMemo } from 'react'\nimport type { LayoutNode, ReadPlan } from '@protobase/layout'\nimport { useClient } from '../../data/api-provider'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { useAdminMeta } from '../meta-gate'\nimport { blockQueries } from './block-queries'\nimport { usePageParamsGiven, usePageParamValues } from './page-params'\nimport { useProjectUi } from './project-ui'\nimport { rootRecordOf, useScopeStack } from './record-scope'\n\n/**\n * Starts the queries of the blocks of `plan` that read by themselves as the page opens, beside its planned reads; each\n * block then finds its own query running or answered once it draws. It draws nothing.\n */\nexport const StartBlockQueries = ({ tree, plan }: { tree: LayoutNode; plan: ReadPlan | undefined }) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const { resources, views } = useAdminMeta()\n const fieldTypes = useProjectUi().fields\n const xs = useIsXs()\n const params = usePageParamValues()\n const given = usePageParamsGiven()\n const root = rootRecordOf(useScopeStack())\n const started = useMemo(() => blockQueries({ client, queryClient, resources, views, fieldTypes, xs, params, given, ...(root && { root }) }, tree, plan), [client, queryClient, resources, views, fieldTypes, xs, params, given, root, tree, plan])\n useEffect(() => {\n for (const query of started) void query.start(queryClient)\n }, [started, queryClient])\n return null\n}\n"],"mappings":"y6BAqCakC,EAAiB,IAA+C,CAAE,SAAUC,EAAQ,SAAU,MAAQ,GAAgBC,EAAY,cAAcD,CAAO,CAAE,GAGzJE,EAAoB,IAA8E,CAC7G,SAAUF,EAAQ,SAClB,MAAQ,GAAgBC,EAAY,sBAAsBD,CAAO,CACnE,GMjCMG,EAAuC,CAC3C,OFEyC,EAAM,EAAM,IAAW,CAChE,GAAM,CAAE,WAAU,SAAS,GAAI,OAAO,GAAI,UAAS,SAAQ,OAAO,GAAO,QAAQ,GAAI,UAAWvB,EAAoBwB,CAAI,EAClHC,EAAQC,IAAa,IAAA,GAAY,IAAA,GAAYC,EAAO,UAAUD,GACpE,GAAI,CAACD,EAAO,MAAO,CAAC,EACpB,GAAIG,EAAK,OAAS,SAAU,CAE1B,IAAMC,EAAMC,IAAW,IAAA,GAAY,IAAA,GAAYH,EAAO,MAAMG,GAC5D,OAAOD,EAAM,CAACV,EAAWhB,EAAiBwB,EAAO,OAAQF,EAAO,CAAE,KAAI,CAAC,CAAC,CAAC,EAAI,CAAC,CAChF,CACA,IAAMM,EAAOJ,EAAO,MAAMF,EAAM,MAC1B,CAAE,SAAQ,KAAMO,GAAetB,EAAe,CAAE,GAAGiB,EAAQ,QAAO,OAAM,QAASM,GAAS,IAAIpC,CAAU,EAAG,SAAQ,OAAM,aAAcO,EAAW6B,CAAO,CAAE,CAAC,EAClK,MAAO,CAACd,EAAWH,EAAkBW,EAAQ,CAAE,QAAO,SAAQ,QAASO,GAAQnC,EAAe0B,EAAOM,CAAI,EAAG,QAAO,SAAQ,KAAMC,CAAW,CAAC,CAAC,CAAC,CACjJ,EEbE,OLLyC,EAAM,EAAO,CAAE,SAAQ,YAAW,WAAY,CACvF,GAAM,CAAE,WAAU,UAAS,UAAS,M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