@protobase/ui 0.112.1 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/account/messages.d.ts +2 -2
  2. package/dist/app/app.js +4 -3
  3. package/dist/app/charts/messages.d.ts +2 -2
  4. package/dist/app/comments/messages.d.ts +2 -2
  5. package/dist/app/confirm-sign-in-messages.d.ts +2 -2
  6. package/dist/app/create/messages.d.ts +2 -2
  7. package/dist/app/custom-section.d.ts +1 -1
  8. package/dist/app/delete/messages.d.ts +2 -2
  9. package/dist/app/displays/list-cards.d.ts +1 -1
  10. package/dist/app/displays/messages.d.ts +2 -2
  11. package/dist/app/embedded-list/messages.d.ts +2 -2
  12. package/dist/app/export/messages.d.ts +2 -2
  13. package/dist/app/field-messages.d.ts +2 -2
  14. package/dist/app/field-types/custom-step-container/messages.d.ts +2 -2
  15. package/dist/app/field-types/json/messages.d.ts +2 -2
  16. package/dist/app/field-types/runner-install/messages.d.ts +2 -2
  17. package/dist/app/field-types/widget-part.d.ts +1 -1
  18. package/dist/app/field-types/workflow/messages.d.ts +2 -2
  19. package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
  20. package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
  21. package/dist/app/field-types/workflow-status/messages.d.ts +2 -2
  22. package/dist/app/file-viewers/messages.d.ts +2 -2
  23. package/dist/app/focus/messages.d.ts +2 -2
  24. package/dist/app/gallery/messages.d.ts +2 -2
  25. package/dist/app/hand-order/messages.d.ts +2 -2
  26. package/dist/app/history/messages.d.ts +2 -2
  27. package/dist/app/hold-start-for-first-loads.d.ts +12 -0
  28. package/dist/app/hold-start-for-first-loads.js +43 -0
  29. package/dist/app/import/messages.d.ts +2 -2
  30. package/dist/app/index.html +17 -0
  31. package/dist/app/list-edit/messages.d.ts +2 -2
  32. package/dist/app/list-messages.d.ts +2 -2
  33. package/dist/app/messages.d.ts +2 -2
  34. package/dist/app/meta-gate-messages.d.ts +2 -2
  35. package/dist/app/new-version/messages.d.ts +2 -2
  36. package/dist/app/pages/custom-boundary.d.ts +1 -1
  37. package/dist/app/pages/custom-chosen.d.ts +1 -1
  38. package/dist/app/pages/messages.d.ts +2 -2
  39. package/dist/app/record-chart/messages.d.ts +2 -2
  40. package/dist/app/record-messages.d.ts +2 -2
  41. package/dist/app/record-mode/shown-layout.d.ts +1 -1
  42. package/dist/app/record-row/messages.d.ts +2 -2
  43. package/dist/app/related-cards/messages.d.ts +2 -2
  44. package/dist/app/runtime/messages.d.ts +2 -2
  45. package/dist/app/saved/messages.d.ts +2 -2
  46. package/dist/app/saved/saved-list.d.ts +1 -1
  47. package/dist/app/search/messages.d.ts +2 -2
  48. package/dist/app/searches/messages.d.ts +2 -2
  49. package/dist/app/splash-hold.d.ts +1 -0
  50. package/dist/app/splash-hold.js +1 -1
  51. package/dist/app/start-screen.d.ts +9 -0
  52. package/dist/app/start-screen.js +10 -1
  53. package/dist/app-shell/messages.d.ts +2 -2
  54. package/dist/assistant-dock/messages.d.ts +2 -2
  55. package/dist/auth/messages.d.ts +2 -2
  56. package/dist/calls/messages.d.ts +2 -2
  57. package/dist/chat/messages.d.ts +2 -2
  58. package/dist/compact-table/messages.d.ts +2 -2
  59. package/dist/data-grid/column-spec.d.ts +1 -1
  60. package/dist/data-grid/messages.d.ts +2 -2
  61. package/dist/filter-panel/messages.d.ts +2 -2
  62. package/dist/focus-page/messages.d.ts +2 -2
  63. package/dist/format/messages.d.ts +2 -2
  64. package/dist/forms/messages.d.ts +2 -2
  65. package/dist/inline-child-table/messages.d.ts +2 -2
  66. package/dist/invitations/messages.d.ts +2 -2
  67. package/dist/live/messages.d.ts +2 -2
  68. package/dist/mailbox/messages.d.ts +2 -2
  69. package/dist/mentions/messages.d.ts +2 -2
  70. package/dist/mocks/customers.d.ts +1 -1
  71. package/dist/mocks/invoices.d.ts +1 -1
  72. package/dist/mocks/orders.d.ts +3 -3
  73. package/dist/notifications/bell/messages.d.ts +2 -2
  74. package/dist/organizations/messages.d.ts +2 -2
  75. package/dist/package.js +1 -1
  76. package/dist/plugins/before-sign-in.d.ts +1 -1
  77. package/dist/primitives/messages.d.ts +2 -2
  78. package/dist/record-view/messages.d.ts +2 -2
  79. package/dist/shell/assets/app-DG30qs8Q.js +16 -0
  80. package/dist/shell/assets/{graph-view-Dky1whXD.js → graph-view-BcbWbnHO.js} +2 -2
  81. package/dist/shell/assets/{html-viewer-lp3H6iV2.js → html-viewer-tGtSpy9M.js} +2 -2
  82. package/dist/shell/assets/{in-place-form-B-GQA4qE.js → in-place-form-B0EkP4B1.js} +2 -2
  83. package/dist/shell/assets/{index-VlTh9QjU.js → index-CZ013UoE.js} +2 -2
  84. package/dist/shell/assets/{maplibre-DjGuR3NM.js → maplibre-Y7X50Jfk.js} +2 -2
  85. package/dist/shell/assets/{markdown-content-C_I33tF1.js → markdown-content-DHKbAJjx.js} +2 -2
  86. package/dist/shell/assets/{record-map-0rx4A_p3.js → record-map-nGRmsk6x.js} +2 -2
  87. package/dist/shell/assets/{records-map-8Od0n3e7.js → records-map-D2flyaz3.js} +2 -2
  88. package/dist/shell/assets/{run-trace-view-5Xia2z2X.js → run-trace-view-DfrAPeum.js} +2 -2
  89. package/dist/shell/assets/{search-picker-BeTUduFk.js → search-picker-CJcJetBh.js} +2 -2
  90. package/dist/shell/assets/{shared-protobase-ui-vMThpYOB.js → shared-protobase-ui-CVwqj5Cp.js} +2 -2
  91. package/dist/shell/assets/{step-catalog-Aw0TBmFO.js → step-catalog-ZvQOXfSh.js} +2 -2
  92. package/dist/shell/assets/{step-panel-BbMJ5sl9.js → step-panel-B1yHz7OC.js} +2 -2
  93. package/dist/shell/assets/{use-app-address-D50fN1nP.js → use-app-address-B6k3dkV0.js} +2 -2
  94. package/dist/shell/assets/{use-sibling-page-CaUyRcwf.js → use-sibling-page-CiuiG-Tz.js} +2 -2
  95. package/dist/shell/assets/{workflow-canvas-vb0Tlov2.js → workflow-canvas-DMP7SDWX.js} +2 -2
  96. package/dist/shell/assets/{workflow-graph-editor-_fE7qonR.js → workflow-graph-editor-xpV8_qEl.js} +2 -2
  97. package/dist/shell/assets/{workflow-workbench-C_m8akk8.js → workflow-workbench-Djdd_ODh.js} +2 -2
  98. package/dist/shell/index.html +8 -5
  99. package/dist/shell/protobase.shell.json +2 -2
  100. package/dist/shell/protobase.sw.js +2 -2
  101. package/dist/shell-source-maps/assets/app-DG30qs8Q.js.map +1 -0
  102. package/dist/shell-source-maps/assets/{graph-view-Dky1whXD.js.map → graph-view-BcbWbnHO.js.map} +1 -1
  103. package/dist/shell-source-maps/assets/{html-viewer-lp3H6iV2.js.map → html-viewer-tGtSpy9M.js.map} +1 -1
  104. package/dist/shell-source-maps/assets/{in-place-form-B-GQA4qE.js.map → in-place-form-B0EkP4B1.js.map} +1 -1
  105. package/dist/shell-source-maps/assets/{index-VlTh9QjU.js.map → index-CZ013UoE.js.map} +1 -1
  106. package/dist/shell-source-maps/assets/{maplibre-DjGuR3NM.js.map → maplibre-Y7X50Jfk.js.map} +1 -1
  107. package/dist/shell-source-maps/assets/{markdown-content-C_I33tF1.js.map → markdown-content-DHKbAJjx.js.map} +1 -1
  108. package/dist/shell-source-maps/assets/{record-map-0rx4A_p3.js.map → record-map-nGRmsk6x.js.map} +1 -1
  109. package/dist/shell-source-maps/assets/{records-map-8Od0n3e7.js.map → records-map-D2flyaz3.js.map} +1 -1
  110. package/dist/shell-source-maps/assets/{run-trace-view-5Xia2z2X.js.map → run-trace-view-DfrAPeum.js.map} +1 -1
  111. package/dist/shell-source-maps/assets/{search-picker-BeTUduFk.js.map → search-picker-CJcJetBh.js.map} +1 -1
  112. package/dist/shell-source-maps/assets/{shared-protobase-ui-vMThpYOB.js.map → shared-protobase-ui-CVwqj5Cp.js.map} +1 -1
  113. package/dist/shell-source-maps/assets/{step-catalog-Aw0TBmFO.js.map → step-catalog-ZvQOXfSh.js.map} +1 -1
  114. package/dist/shell-source-maps/assets/{step-panel-BbMJ5sl9.js.map → step-panel-B1yHz7OC.js.map} +1 -1
  115. package/dist/shell-source-maps/assets/{use-app-address-D50fN1nP.js.map → use-app-address-B6k3dkV0.js.map} +1 -1
  116. package/dist/shell-source-maps/assets/{use-sibling-page-CaUyRcwf.js.map → use-sibling-page-CiuiG-Tz.js.map} +1 -1
  117. package/dist/shell-source-maps/assets/{workflow-canvas-vb0Tlov2.js.map → workflow-canvas-DMP7SDWX.js.map} +1 -1
  118. package/dist/shell-source-maps/assets/{workflow-graph-editor-_fE7qonR.js.map → workflow-graph-editor-xpV8_qEl.js.map} +1 -1
  119. package/dist/shell-source-maps/assets/{workflow-workbench-C_m8akk8.js.map → workflow-workbench-Djdd_ODh.js.map} +1 -1
  120. package/dist/status/messages.d.ts +2 -2
  121. package/dist/users/messages.d.ts +2 -2
  122. package/package.json +5 -5
  123. package/dist/shell/assets/app-4qlxuQdl.js +0 -16
  124. package/dist/shell-source-maps/assets/app-4qlxuQdl.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-app-address-D50fN1nP.js","names":["parse","check","parse","check","field","isObject","isObject","createContext","useContext","useMemo","createContext","useContext","useState","useRef","useCallback","useMemo","appText","_Fragment","useMemo","Fragment","createContext","useContext","text","createContext","useContext","text","useContext","useMemo","text","useSyncExternalStore","useMemo","useCallback","n","a","t","__toESM","require_react","require_jsx_runtime","guarded","parseFilter$1","parseOrderBy$1","checkOrderBy$1","checkFilter$1","useQueries","IntlMessageFormat","useQueryClient","printFilter","functions","parseOptions","schemaOf","Spinner","isApiError","Button","lift","encodeKey","ClientProvider","useSourceClients","useClient","keys","hrefField","text$3","RouteLink","embeddedFilterFields","isLayoutNode","enumLabel","revealLate","addressPlaceholders","filterField","recordKey","resourceField","textPlaceholders","displayValue","activeLocale","messages","setAppLocale","catalogues","humanize","MetaContext","Dialog","useMeta","cn","filterError","distance","row","b","i","next","j","cost","suggest","lower","name","scored","candidates","candidate","findField","model","field","resolveField","path","ctx","usable","f","capability","close","method","unsupported","l","message","hint","span","fieldOf","node","valueOf","left","literalOf","wordOf","isSubfilter","arg","pageOf","orderBy","limit","pageToken","extra","args","lowerRelated","target","rest","usage","bad","subfilter","page","related","filter","lowerCall","first","second","string","values","v","all","items","item","value","parseFilter","parsed","source","limits","lowering","ast","errors","daysIn","month","year","isValidDate","match","text","day","isValidTimestamp","hour","minute","offsetHour","offsetMinute","problem","int64Min","int64Max","uuid","numericText","expected","what","checkInteger","number","checkBigint","checkDecimal","checkValue","equality","ordered","compareOps","type","isOpaque","relatedRefused","operatorError","isWildcard","op","checkCompare","allowed","checkHas","checkIn","literal","checkText","checkNode","checkAgainstModel","checkFilter","traversal","generic","lowercaseDirections","before","space","word","parseOrderBy","checkOrderBy","checked","parseDurationText","field$1","filterValue","group","kind","createWhere","compare","offset","duration","low","high","where","refMark","ref","isRef","createRefs","known","make","fieldRef","isFieldRef","isObject$2","markFieldRefs","entry","unmarkFieldRefs","fieldRefsIn","naming","label","icon","tableDisplay","customComponent","component","displays","o","fields","column","displayName","displayErrors","names","list","display","index","other","approximateErrors","error","approximate","exact","radius","defaultRadius","area","boardErrors","datesErrors","start","end","unfilterable","displayFields","viewOfList","view","named","_list","_chart","_help","_nav","_lists","_names","_name","parts","nameErrors","withSamples","quote","filterErrors","embedded","orderErrors","addressErrors","placeholders","to","placeholderError","recordFilter","filterFromRecord","pages","models","createPages","isObject$1","shape","rowButtonChoices","button","rowButtonTarget","href","choice","rowButtonChoiceFields","rowButtonFields","missing","part","choiceErrors","check","rowButtonErrors","followableRowButton","kept","labelCandidates","namesRecords","labelFieldOf","recordTitleField","recordTitle","record","fallback","listColumnNames","resource","import_react","import_jsx_runtime","GuardedParamsContext","GuardedParams","outer","useGuardedParams","leavesPage","from","after","guards","guard","pendingLink","followLink","go","link","storageKey","isPlace","read","raw","storage","createPagePlaces","places","top","oldest","patience","restoreScroll","placed","place","observer","stop","moved","timer","RouterContext","useRouter","browserUrl","pathOf","url","historyState","historyIndex","newEntry","historyEntry","state","noStorage","Router","memory","initialUrl","setPage","losesInput","current","position","undoing","proceeding","leaveAfterUndo","reloading","pending","setPending","rememberScroll","persist","hidden","onPop","delta","replace","previous","full","keepScroll","navigate","basePath","options","back","registerGuard","token","reload","reloadConfirmed","holdsChanges","leave","children","Link","useNavigationGuard","params","active","warn","event","addressWords","listWords","mapText","inRange","readMap","latitude","longitude","zoom","periodText","isDay","date","readPeriod","scale","scales","listQuery","query","address","recordQuery","title","appPath","valuesQuery","decodeSegments","pathname","readVersion","filterLayout","readAppPath","pathAndQuery","segments","open","tab","standard","call","version","run","panel","file","layout","map","calendar","timeline","savedSearch","nameOf","routedClient","sourceOf","own","key","body","patch","etag","action","input","apis","ops","proof","handlers","runId","held","runner","recorded","scopes","lastScope","building","inScope","scope","build","scopeOf","markScope","keepScope","copy","durationPattern","Now","checkDuration","Condition","join","side","right","isRecorded","placeholder","member","valueText","term","comparisons","comparisonNames","recorder","fieldRecorder","advice","describe","isPlainObject","prototype","staticValue","normalizeChildren","child","isBlock","recordChildBlocks","conditionArrows","builtProps","built","props","prop","condition","builtChildren","recordPropBlocks","fallbackBlocks","builtRecordProp","one","only","createNode","written","ownFallback","taken","given","recordProp","perRecord","defineBlock","block","reads","resolveFieldPath","steps","argumentTypes","tagType","walk","element","elements","found","option","messageParts","language","compiled","formatMessage","texts","id","format","tags","formatText","formatted","tag","chunks","isTrans","withinSource","drawn","_outside","plain","keptLayoutItem","inner","columns","narrowed","followable","keptAction","withinSourceView","sourceMeta","listed","meta","resources","scoped","allowEverything","sourceTimeoutMs","combine","results","result","useSourceMetas","queryClient","sources","queryKey","clientOf","data","withSources","ready","sourceStatusOf","status","AppLocale","locale","AppTexts","useAppTexts","isObject","transText","ownPropTexts","withPropTexts","namespace","text$2","translated","hints","prefix","shown","tableKey","translatedView","at","withTranslatedViews","createSplashHold","holds","started","settle","hide","released","SplashHoldContext","SplashHoldProvider","HoldSplash","splash","text$1","useAdminMeta","Notice","WithSources","declared","merged","routing","byResource","resourceClient","TranslatedMeta","MetaGate","usePermissions","useMediaQuery","onChange","useIsDesktop","useIsXs","photosKey","listPhotos","withPhotos","photos","rows","filledFields","boardColumns","boardRank","columnFilter","by","boardCard","refusalReason","reasons","displaysOf","configuredDisplay","preferred","defaultDisplay","configured","xs","rowsDisplay","phoneRows","badge","footer","isPhoneRows","listDefaultDisplay","shownListDisplay","shownDisplay","wanted","defaultIcons","displayChoices","listDisplayChoices","choices","cardFields","filledMeta","filledAmount","amount","filledCode","code","rawCode","amountParts","unsuffixed","suffix","mapCards","cards","shownFields","card","image","subtitle","flags","actionFields","linkTextFields","loadedFields","sortFields","isLabelled","displayRow","labels","\"$photos\"","defaultOrderBy","sort","parseSort","columnId","direction","sortToOrderBy","listedResource","views","listOf","listDefaults","currentAddress","defaults","changedList","change","differs","useAppAddress","backTo","pageNames","listTo","set","below","AppLink"],"sources":["../../../../schema/src/filter/errors.ts","../../../../schema/src/filter/check-field.ts","../../../../schema/src/filter/lower.ts","../../../../schema/src/filter/parse.ts","../../../../schema/src/filter/datetime.ts","../../../../schema/src/filter/check-value.ts","../../../../schema/src/filter/operators.ts","../../../../schema/src/filter/related.ts","../../../../schema/src/filter/check-model.ts","../../../../schema/src/filter/check.ts","../../../../schema/src/filter/order-by.ts","../../../../schema/src/filter/duration.ts","../../../../schema/src/filter/where.ts","../../../../schema/src/refs.ts","../../../../schema/src/field-ref.ts","../../../../schema/src/view-displays.ts","../../../../schema/src/named-list.ts","../../../../schema/src/address-errors.ts","../../../../schema/src/row-button.ts","../../../../schema/src/record-title.ts","../../../../schema/src/list-columns.ts","../../../src/app/guarded-params.tsx","../../../src/app/leaves-page.ts","../../../src/app/pending-link.ts","../../../src/app/page-places.ts","../../../src/app/restore-scroll.ts","../../../src/app/router.tsx","../../../../schema/src/app-address.ts","../../../../client/src/routed-client.ts","../../../../layout/src/typed/record.ts","../../../../layout/src/create-node.ts","../../../../layout/src/field-path.ts","../../../../layout/src/translations.ts","../../../../client/src/source-meta.ts","../../../src/data/meta-data.ts","../../../src/data/use-source-metas.ts","../../../src/data/with-sources.ts","../../../src/locale/app-locale.tsx","../../../src/app/pages/app-texts.ts","../../../src/app/built-in-views/translated-views.ts","../../../src/app/splash-hold.tsx","../../../src/app/meta-gate-messages.ts","../../../src/app/meta-gate.tsx","../../../src/lib/use-media-query.ts","../../../src/live/row-photos.ts","../../../src/app/filled-fields.ts","../../../src/app/displays/messages.ts","../../../src/app/displays/board-columns.ts","../../../src/app/displays/list-displays.ts","../../../src/app/list-order.ts","../../../src/app/current-address.ts","../../../src/app/use-app-address.tsx"],"sourcesContent":["import type { FilterError, FilterErrorCode, Span } from '../model'\n\nexport const filterError = (\n code: FilterErrorCode,\n message: string,\n hint: string,\n span: Span,\n): FilterError => ({ code, message, hint, span })\n\nexport const joinSpans = (a: Span, b: Span): Span => ({ start: a.start, end: b.end })\n\nconst distance = (a: string, b: string) => {\n let row = Array.from({ length: b.length + 1 }, (_, i) => i)\n for (let i = 1; i <= a.length; i++) {\n const next = [i]\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + cost)\n }\n row = next\n }\n return row[b.length]!\n}\n\nexport const suggest = (name: string, candidates: string[]) => {\n const lower = name.toLowerCase()\n const scored = candidates\n .map((candidate) => ({ candidate, score: distance(lower, candidate.toLowerCase()) }))\n .sort((a, b) => a.score - b.score)[0]\n return scored && scored.score <= Math.max(2, Math.floor(name.length / 3)) ? scored.candidate : undefined\n}\n","import type { FieldModel, FieldPath, FilterError, ResourceModel } from '../model'\nimport { filterError, suggest } from './errors'\n\nexport type CheckContext = { model: ResourceModel; errors: FilterError[] }\n\nexport const findField = (model: ResourceModel, name: string) =>\n Object.hasOwn(model.fields, name)\n ? model.fields[name]\n : Object.values(model.fields).find((field) => field.aliases.includes(name))\n\nexport const resolveField = (\n ctx: CheckContext,\n path: FieldPath,\n capability: 'filterable' | 'sortable',\n): FieldModel | undefined => {\n if (path.path.length > 1) {\n ctx.errors.push(\n filterError(\n 'unsupported-traversal',\n `Traversal into \"${path.path.join('.')}\" is not supported yet`,\n 'Filter on fields of this resource only',\n path.span,\n ),\n )\n return undefined\n }\n const name = path.path[0]!\n const field = findField(ctx.model, name)\n if (!field) {\n const usable = Object.values(ctx.model.fields).filter((f) => f[capability]).map((f) => f.name)\n const close = suggest(name, usable)\n ctx.errors.push(\n filterError(\n 'unknown-field',\n `Unknown field \"${name}\"`,\n close ? `Did you mean \"${close}\"?` : `Available fields: ${usable.join(', ')}`,\n path.span,\n ),\n )\n return undefined\n }\n if (!field[capability]) {\n const method = capability === 'filterable' ? 'filterable' : 'sortable'\n ctx.errors.push(\n filterError(\n capability === 'filterable' ? 'not-filterable' : 'not-sortable',\n `Field \"${field.name}\" is not ${method}`,\n `Mark it with .${method}() in data.ts`,\n path.span,\n ),\n )\n return undefined\n }\n return field\n}\n","import type { Arg, Call, Expr as Generic, Operand } from 'aip-parsers/filter'\nimport type { FieldPath, FilterError, FilterExpr, FilterValue, Literal, Span } from '../model'\nimport { filterError } from './errors'\nimport { functions } from './profile'\n\nexport type Lowering = { errors: FilterError[] }\n\nconst unsupported = (l: Lowering, message: string, hint: string, span: Span) => {\n l.errors.push(filterError('unsupported', message, hint, span))\n return undefined\n}\n\nconst fieldOf = (l: Lowering, node: Operand): FieldPath | undefined =>\n node.kind === 'member'\n ? { kind: 'field', path: node.path, span: node.span }\n : unsupported(l, 'Only fields can be compared', 'Put a field name on the left, for example total > 100', node.span)\n\n// Bare words on the right are text; now() with an optional duration offset is a NowValue.\nconst valueOf = (l: Lowering, node: Operand): FilterValue | undefined => {\n switch (node.kind) {\n case 'member':\n return { kind: 'string', value: node.path.join('.'), span: node.span }\n case 'call':\n if (node.name === 'now' && node.args.length === 0) return { kind: 'now', span: node.span }\n return unsupported(l, `${node.name}() cannot be used as a value`, 'Only now() is a value function', node.span)\n case 'binary': {\n const left = node.left\n const isNow = left.kind === 'call' && left.name === 'now' && left.args.length === 0\n if (isNow && node.right.kind === 'duration') {\n return { kind: 'now', offset: { sign: node.op, duration: node.right }, span: node.span }\n }\n return unsupported(l, 'Arithmetic is only supported as now() +/- duration', 'Write now() - 30d', node.span)\n }\n default:\n return node\n }\n}\n\nconst literalOf = (l: Lowering, node: Arg): Literal | undefined => {\n const value = 'kind' in node && ['member', 'call', 'binary'].includes(node.kind) ? undefined : (node as Literal)\n if (value) return value\n if (node.kind === 'member') return { kind: 'string', value: node.path.join('.'), span: node.span }\n return unsupported(l, 'Expected a literal value', 'Use strings, numbers, true/false, durations or timestamps', node.span)\n}\n\nconst wordOf = (node: Operand) => {\n switch (node.kind) {\n case 'member':\n return node.path.join('.')\n case 'string':\n case 'timestamp':\n return node.kind === 'string' ? node.value : node.value\n case 'number':\n return node.raw\n case 'boolean':\n return String(node.value)\n case 'duration':\n return `${node.amount}${node.unit}`\n default:\n return ''\n }\n}\n\n// The subfilter is a group in parentheses, or a function call alone in them, as `related(...)` is when it nests. A bare\n// value would lower to nothing and drop the whole filter without an error.\nconst isSubfilter = (arg: Arg): arg is Generic => ['sequence', 'and', 'or', 'not', 'compare', 'has', 'present', 'global', 'call'].includes(arg.kind)\n\n// After the optional subfilter come the parent read's page, in a list's order: `\"order_by\"`, a positive whole `limit`\n// and `\"page_token\"`, each needing the one before it.\nconst pageOf = (args: Arg[]) => {\n const [orderBy, limit, pageToken, ...extra] = args\n if (extra.length > 0) return undefined\n if (orderBy && orderBy.kind !== 'string') return undefined\n if (limit && (limit.kind !== 'number' || !Number.isSafeInteger(limit.value) || limit.value < 1)) return undefined\n if (pageToken && pageToken.kind !== 'string') return undefined\n return {\n ...(orderBy?.kind === 'string' && { orderBy: orderBy.value }),\n ...(limit?.kind === 'number' && { limit: limit.value }),\n ...(pageToken?.kind === 'string' && { pageToken: pageToken.value }),\n }\n}\n\nconst lowerRelated = (l: Lowering, node: Call, field: FieldPath | undefined, bad: (usage: string) => undefined): FilterExpr | undefined => {\n const [, target, ...rest] = node.args\n const usage = 'related(field, resource.field, (filter), \"order_by\", limit, \"page_token\"), each after the field optional'\n if (!field || target?.kind !== 'member' || target.path.length !== 2) return bad(usage)\n const subfilter = rest[0] && isSubfilter(rest[0]) ? rest[0] : undefined\n const page = pageOf(subfilter ? rest.slice(1) : rest)\n if (!page) return bad(usage)\n const related = { kind: 'related', field, resource: target.path[0]!, key: target.path[1]!, ...page, span: node.span } as const\n if (!subfilter) return related\n const filter = lower(l, subfilter)\n return filter && { ...related, filter }\n}\n\nconst lowerCall = (l: Lowering, node: Call): FilterExpr | undefined => {\n const [first, second, ...rest] = node.args\n const field = first?.kind === 'member' ? fieldOf(l, first) : undefined\n const string = (arg: Arg | undefined) => (arg?.kind === 'string' ? arg.value : undefined)\n const bad = (usage: string) => {\n l.errors.push(filterError('invalid-arguments', `Invalid arguments to ${node.name}()`, `Usage: ${usage}`, node.span))\n return undefined\n }\n switch (node.name) {\n case 'in': {\n const values = node.args.slice(1).map((arg) => literalOf(l, arg))\n if (!field || values.length === 0) return bad('in(field, value1, value2, ...)')\n return values.every((v) => v) ? { kind: 'in', field, values: values as Literal[], span: node.span } : undefined\n }\n case 'search':\n return string(first) !== undefined && !second ? { kind: 'search', text: string(first)!, span: node.span } : bad('search(\"text\")')\n case 'similar':\n return field && string(second) !== undefined && rest.length === 0 ? { kind: 'similar', field, text: string(second)!, span: node.span } : bad('similar(field, \"text\")')\n case 'regex':\n return field && string(second) !== undefined && rest.length === 0 ? { kind: 'regex', field, pattern: string(second)!, span: node.span } : bad('regex(field, \"pattern\")')\n case 'isNull':\n return field && !second ? { kind: 'isNull', field, span: node.span } : bad('isNull(field)')\n case 'related':\n return lowerRelated(l, node, field, bad)\n default:\n l.errors.push(filterError('unknown-function', `Unknown function \"${node.name}\"`, `Available functions: ${Object.keys(functions).join(', ')}`, node.span))\n return undefined\n }\n}\n\nconst all = (items: (FilterExpr | undefined)[]) => (items.every((item) => item) ? (items as FilterExpr[]) : undefined)\n\n/** Lowers a generic AIP-160 expression to Protobase's filter shape; unsupported constructs become errors. */\nexport const lower = (l: Lowering, node: Generic): FilterExpr | undefined => {\n switch (node.kind) {\n case 'sequence':\n case 'and':\n case 'or': {\n const args = all(node.args.map((arg) => lower(l, arg)))\n return args && { kind: node.kind === 'or' ? 'or' : 'and', args, span: node.span }\n }\n case 'not': {\n const arg = lower(l, node.arg)\n return arg && { kind: 'not', arg, span: node.span }\n }\n case 'compare': {\n const field = fieldOf(l, node.left)\n const value = valueOf(l, node.right)\n return field && value && { kind: 'compare', op: node.op, field, value, span: node.span }\n }\n case 'has': {\n const field = fieldOf(l, node.left)\n const value = literalOf(l, node.right)\n return field && value && { kind: 'has', field, value, span: node.span }\n }\n case 'present': {\n const field = fieldOf(l, node.left)\n return field && { kind: 'present', field, span: node.span }\n }\n case 'global':\n return { kind: 'search', text: wordOf(node.value), span: node.span }\n case 'call':\n return lowerCall(l, node)\n }\n}\n","import { parseFilter as parse, type ParseOptions } from 'aip-parsers/filter'\nimport type { FilterError, FilterExpr } from '../model'\nimport { lower } from './lower'\nimport { parseOptions } from './profile'\n\n/** What `parseFilter` gives: the filter, `undefined` for empty text, or the errors in the order they occur in the text. */\nexport type FilterParse =\n | {\n /** The text parsed. */\n ok: true\n /** The filter, or `undefined` when the text is empty. */\n ast: FilterExpr | undefined\n /** None. */\n errors: []\n }\n | {\n /** The text did not parse. */\n ok: false\n /** As much of the filter as parsed. */\n ast: FilterExpr | undefined\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/** Bounds on filter text: its length in characters and how deeply its expressions nest. */\nexport type FilterLimits = Pick<ParseOptions, 'maxLength' | 'maxDepth'>\n\n/**\n * Parses filter text, AIP-160 as the API takes it, into a filter, collecting every error. `maxLength` defaults to\n * 10,000 characters and `maxDepth` to 64. Check the result against a resource with `checkFilter` before running it.\n *\n * @example\n * ```ts\n * const parsed = parseFilter('status = \"paid\" AND total > 100')\n * if (parsed.ok && parsed.ast) printFilter(parsed.ast) // 'status = \"paid\" AND total > 100'\n * ```\n */\nexport const parseFilter = (source: string, limits: FilterLimits = {}): FilterParse => {\n const parsed = parse(source, { ...parseOptions, ...limits })\n const lowering = { errors: [] as FilterError[] }\n const ast = parsed.ast && lower(lowering, parsed.ast)\n const errors = [...parsed.errors, ...lowering.errors].sort((a, b) => a.span.start - b.span.start)\n return errors.length === 0 ? { ok: true, ast, errors: [] } : { ok: false, ast, errors }\n}\n","const daysIn = (year: number, month: number) => {\n if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28\n return [4, 6, 9, 11].includes(month) ? 30 : 31\n}\n\nexport const isValidDate = (text: string) => {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return false\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n return month >= 1 && month <= 12 && day >= 1 && day <= daysIn(year, month)\n}\n\nexport const isValidTimestamp = (text: string) => {\n const match =\n /^(\\d{4}-\\d{2}-\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:[Zz]|[+-](\\d{2}):(\\d{2}))$/.exec(text)\n if (!match) return false\n const [hour, minute, second] = [Number(match[2]), Number(match[3]), Number(match[4])]\n const [offsetHour, offsetMinute] = [Number(match[5] ?? 0), Number(match[6] ?? 0)]\n return (\n isValidDate(match[1]!) &&\n hour <= 23 &&\n minute <= 59 &&\n second <= 59 &&\n offsetHour <= 23 &&\n offsetMinute <= 59\n )\n}\n","import type { FieldModel, FilterValue } from '../model'\nimport { isValidDate, isValidTimestamp } from './datetime'\n\nexport type Problem = { message: string; hint: string }\n\nconst problem = (message: string, hint: string): Problem => ({ message, hint })\n\nconst int64Min = -(2n ** 63n)\nconst int64Max = 2n ** 63n - 1n\nconst uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// Numbers may be written as number literals or quoted strings; precision lives in the text.\nconst numericText = (value: FilterValue) =>\n value.kind === 'number' ? value.raw : value.kind === 'string' ? value.value : undefined\n\nconst expected = (what: string, hint = `Write ${what} values like the examples in the docs`) =>\n problem(`Expected ${what}`, hint)\n\nconst checkInteger = (value: FilterValue) => {\n const text = numericText(value)\n const number = text === undefined ? NaN : Number(text)\n if (text === undefined || text.trim() === '' || !Number.isSafeInteger(number)) {\n return expected('a whole number', 'Use an integer such as 42, or a bigint field for larger values')\n }\n}\n\nconst checkBigint = (value: FilterValue) => {\n const text = numericText(value)\n if (text === undefined || !/^-?\\d+$/.test(text) || BigInt(text) < int64Min || BigInt(text) > int64Max) {\n return expected('a 64-bit integer', 'Use plain digits such as 9007199254740993 (no exponent or fraction)')\n }\n}\n\nconst checkDecimal = (value: FilterValue) => {\n const text = numericText(value)\n if (text === undefined || !/^-?\\d+(\\.\\d+)?$/.test(text)) {\n return expected('a decimal number', 'Use plain digits such as 100.50, or quote it: \"100.50\" (no exponent)')\n }\n}\n\nexport const checkValue = (field: FieldModel, value: FilterValue): Problem | undefined => {\n if (value.kind === 'now') {\n if (field.type === 'date' || field.type === 'timestamp') return undefined\n return problem('now() only works with date and timestamp fields', `Field \"${field.name}\" is ${field.type}`)\n }\n switch (field.type) {\n case 'text':\n if (value.kind !== 'string') return expected('a quoted string', 'Wrap the text in double quotes')\n return undefined\n case 'integer':\n return checkInteger(value)\n case 'bigint':\n return checkBigint(value)\n case 'decimal':\n return checkDecimal(value)\n case 'boolean':\n return value.kind === 'boolean' ? undefined : expected('true or false')\n case 'date':\n if (value.kind === 'string' && isValidDate(value.value)) return undefined\n return expected('a date', 'Quote a calendar date: \"2012-04-21\"')\n case 'timestamp':\n if (value.kind === 'timestamp' || (value.kind === 'string' && isValidTimestamp(value.value))) return undefined\n return expected('an RFC-3339 timestamp', 'Use 2012-04-21T11:30:00Z, or now() - 7d')\n case 'uuid':\n if (value.kind === 'string' && uuid.test(value.value)) return undefined\n return expected('a uuid', 'Quote a uuid like \"0b5a4f0e-6f2a-4a3c-9d4e-1f2a3b4c5d6e\"')\n case 'enum':\n if (value.kind === 'string' && field.enumValues?.includes(value.value)) return undefined\n return problem('Invalid enum value', `Allowed values: ${(field.enumValues ?? []).join(', ')}`)\n case 'currency':\n if (value.kind === 'string' && /^[A-Z]{3}$/.test(value.value)) return undefined\n return expected('an ISO 4217 currency code', 'Use three capital letters, for example \"EUR\"')\n case 'country':\n if (value.kind === 'string' && /^[A-Z]{2}$/.test(value.value)) return undefined\n return expected('an ISO 3166-1 country code', 'Use two capital letters, for example \"NL\"')\n case 'relation':\n if (value.kind === 'string' || (value.kind === 'number' && Number.isSafeInteger(value.value))) return undefined\n return expected('a record key', 'Use the related record key: 42 or \"abc\"')\n case 'json':\n case 'file':\n return problem(`${field.type} fields cannot be compared`, 'Use field:value on json fields, or isNull(field)')\n }\n}\n","import type { CompareOp, FieldType } from '../model'\n\nconst equality: CompareOp[] = ['=', '!=']\nconst ordered: CompareOp[] = ['=', '!=', '<', '<=', '>', '>=']\n\nexport const compareOps = (type: FieldType): CompareOp[] => {\n switch (type) {\n case 'text':\n case 'integer':\n case 'bigint':\n case 'decimal':\n case 'date':\n case 'timestamp':\n return ordered\n case 'json':\n case 'file':\n return []\n default:\n return equality\n }\n}\n\nexport const isOpaque = (type: FieldType) => type === 'json' || type === 'file'\n","import type { FieldModel, FilterError, FilterExpr, RelatedFilter, ResourceModel, Span } from '../model'\nimport { filterError } from './errors'\n\n/** How deep `related()` nests inside the subfilters of a filter. */\nexport const maxRelatedDepth = 2\n/** How many `related()` terms one filter holds, those in its subfilters included. */\nexport const maxRelatedTerms = 3\n\n/** Everything but a list-style read refuses `related()`, which only the database can answer; so does any place but a term ANDed at the top. */\nexport const relatedRefused = (span: Span) =>\n filterError('unsupported-traversal', \"related() only works in a list's filter, ANDed with the rest\", 'Put it at the top of the filter or of a subfilter, joined with AND', span)\n\n/** The resource whose records the field holds keys of: a relation's to a single key, or the resource's own for its single key. */\nexport const relatedTarget = (model: ResourceModel, field: FieldModel) => {\n if (field.relation) return field.relation.columns.length === 1 ? field.relation.resource : undefined\n return model.primaryKey.length === 1 && model.primaryKey[0] === field.name ? model.name : undefined\n}\n\nconst conjuncts = (node: FilterExpr): FilterExpr[] => (node.kind === 'and' ? node.args.flatMap(conjuncts) : [node])\n\n/** Takes the `related()` terms ANDed at the top of a filter out of it, leaving the rest as it was written when there are none. */\nexport const splitRelated = (ast: FilterExpr) => {\n const parts = conjuncts(ast)\n const terms = parts.filter((part): part is RelatedFilter => part.kind === 'related')\n if (terms.length === 0) return { terms, rest: ast }\n const others = parts.filter((part) => part.kind !== 'related')\n const rest: FilterExpr | undefined = others.length < 2 ? others[0] : { kind: 'and', args: others, span: ast.span }\n return { terms, rest }\n}\n\nconst nested = (node: FilterExpr, inGroup: boolean, depth: number): Array<{ term: RelatedFilter; inGroup: boolean; depth: number }> => {\n switch (node.kind) {\n case 'and':\n return node.args.flatMap((arg) => nested(arg, inGroup, depth))\n case 'or':\n return node.args.flatMap((arg) => nested(arg, true, depth))\n case 'not':\n return nested(node.arg, true, depth)\n case 'related':\n return [{ term: node, inGroup, depth }, ...(node.filter ? nested(node.filter, false, depth + 1) : [])]\n default:\n return []\n }\n}\n\n/** What is wrong with where the `related()` terms of a filter stand and how many there are, whatever they name. */\nexport const relatedErrors = (ast: FilterExpr): FilterError[] => {\n const terms = nested(ast, false, 1)\n const misplaced = terms.filter(({ inGroup }) => inGroup).map(({ term }) => relatedRefused(term.span))\n const deep = terms.filter(({ depth }) => depth > maxRelatedDepth).map(({ term }) =>\n filterError('too-deep', `related() nests at most ${maxRelatedDepth} levels deep`, 'Read the deeper level first, or filter a resource closer to it', term.span))\n const many = terms.length > maxRelatedTerms\n ? [filterError('unsupported', `A filter holds at most ${maxRelatedTerms} related() terms`, 'Narrow it with fewer terms', terms[maxRelatedTerms]!.term.span)]\n : []\n return [...misplaced, ...deep, ...many]\n}\n","import type {\n CheckedFilter, CompareOp, FieldModel, FieldPath, FilterError, FilterExpr, FilterValue, Literal, ResourceModel, Span,\n} from '../model'\nimport { checkValue } from './check-value'\nimport { resolveField, type CheckContext } from './check-field'\nimport { filterError } from './errors'\nimport { compareOps, isOpaque } from './operators'\nimport { relatedRefused } from './related'\n\nconst value = (ctx: CheckContext, field: FieldModel, node: FilterValue) => {\n const problem = checkValue(field, node)\n if (problem) ctx.errors.push(filterError('invalid-value', problem.message, problem.hint, node.span))\n return !problem\n}\n\nconst operatorError = (ctx: CheckContext, message: string, hint: string, span: Span) => {\n ctx.errors.push(filterError('operator-not-allowed', message, hint, span))\n}\n\nconst isWildcard = (op: CompareOp, node: FilterValue) =>\n (op === '=' || op === '!=') && node.kind === 'string' && node.value.includes('*')\n\nconst checkCompare = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'compare' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n const allowed = compareOps(field.type)\n if (!allowed.includes(node.op)) {\n operatorError(\n ctx,\n `Operator \"${node.op}\" is not supported for ${field.type} fields`,\n allowed.length ? `Supported: ${allowed.join(' ')}` : 'Use field:value on json fields, or isNull(field)',\n node.span,\n )\n return undefined\n }\n if (isWildcard(node.op, node.value) && field.type !== 'text') {\n ctx.errors.push(\n filterError('wildcard-not-allowed', `Wildcards are only supported on text fields, not ${field.type}`, 'Remove the \"*\" or filter a text field', node.value.span),\n )\n return undefined\n }\n if (!isWildcard(node.op, node.value) && !value(ctx, field, node.value)) return undefined\n return { ...node, field }\n}\n\nconst checkHas = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'has' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n if (field.type !== 'json') {\n operatorError(ctx, `\":\" is only supported on json fields, not ${field.type}`, `Use = on ${field.type} fields, or field:* to test for a value`, node.span)\n return undefined\n }\n return { ...node, field }\n}\n\nconst checkIn = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'in' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n if (isOpaque(field.type)) {\n operatorError(ctx, `in() is not supported for ${field.type} fields`, 'Use field:value on json fields', node.span)\n return undefined\n }\n const valid = node.values.map((literal: Literal) => value(ctx, field, literal))\n return valid.every(Boolean) ? { ...node, field } : undefined\n}\n\nconst checkText = (ctx: CheckContext, name: string, path: FieldPath) => {\n const field = resolveField(ctx, path, 'filterable')\n if (field && field.type !== 'text') {\n operatorError(ctx, `${name}() only works on text fields, not ${field.type}`, `Field \"${field.name}\" is ${field.type}`, path.span)\n return undefined\n }\n return field\n}\n\nconst checkNode = (ctx: CheckContext, node: FilterExpr): CheckedFilter | undefined => {\n switch (node.kind) {\n case 'and':\n case 'or': {\n const args = node.args.map((arg) => checkNode(ctx, arg))\n return args.every((arg) => arg) ? { ...node, args: args as CheckedFilter[] } : undefined\n }\n case 'not': {\n const arg = checkNode(ctx, node.arg)\n return arg && { ...node, arg }\n }\n case 'compare':\n return checkCompare(ctx, node)\n case 'has':\n return checkHas(ctx, node)\n case 'in':\n return checkIn(ctx, node)\n case 'search':\n if (ctx.model.search?.length) return node\n ctx.errors.push(filterError('no-search-fields', 'This resource has no search fields', 'Declare them with .search((r) => [r.title]) in data.ts', node.span))\n return undefined\n case 'present':\n case 'isNull': {\n const field = resolveField(ctx, node.field, 'filterable')\n return field && { ...node, field }\n }\n case 'similar':\n case 'regex': {\n const field = checkText(ctx, node.kind, node.field)\n return field && { ...node, field }\n }\n case 'related':\n ctx.errors.push(relatedRefused(node.span))\n return undefined\n }\n}\n\nexport const checkAgainstModel = (model: ResourceModel, ast: FilterExpr) => {\n const ctx: CheckContext = { model, errors: [] }\n const filter = checkNode(ctx, ast)\n if (!filter || ctx.errors.length > 0) {\n return { ok: false, errors: [...ctx.errors].sort((a, b) => a.span.start - b.span.start) } as const\n }\n return { ok: true, filter } as const\n}\n","import { checkFilter as check } from 'aip-parsers/filter'\nimport type { CheckedFilter, FilterError, FilterExpr, ResourceModel } from '../model'\nimport { checkAgainstModel } from './check-model'\nimport { lift } from './lift'\nimport { schemaOf } from './profile'\n\n/** What `checkFilter` gives: the filter with each field resolved to its model, or the errors. */\nexport type CheckResult =\n | {\n /** The filter is valid for the resource. */\n ok: true\n /** The filter, each field resolved to the resource's field model. */\n filter: CheckedFilter\n }\n | {\n /** The filter is not valid for the resource. */\n ok: false\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/**\n * Validates against the resource: the library checks fields, aliases, filterability, enum\n * values, operators and function signatures; the model pass then checks the value formats the\n * library cannot know (decimal, bigint, uuid, date, ...), traversal and search fields.\n */\nexport const checkFilter = (model: ResourceModel, ast: FilterExpr): CheckResult => {\n const traversal = checkAgainstModel(model, ast)\n if (!traversal.ok && traversal.errors.some((e) => e.code === 'unsupported-traversal')) return traversal\n const generic = check(lift(ast), schemaOf(model))\n if (!generic.ok) return { ok: false, errors: generic.errors }\n return checkAgainstModel(model, ast)\n}\n","import { checkOrderBy as check, parseOrderBy as parse, printOrderBy as print } from 'aip-parsers/order-by'\nimport type { FilterError, OrderByItem, ResourceModel, SortSpec } from '../model'\nimport { filterError } from './errors'\nimport { schemaOf } from './profile'\n\n/** What `parseOrderBy` gives: the order's items, or the errors. */\nexport type OrderByParse =\n | {\n /** The text parsed. */\n ok: true\n /** The fields to sort on, in order. */\n items: OrderByItem[]\n /** None. */\n errors: []\n }\n | {\n /** The text did not parse. */\n ok: false\n /** The items that parsed. */\n items: OrderByItem[]\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/** What `checkOrderBy` gives: the sort, or the errors. */\nexport type OrderByCheck =\n | {\n /** The order is valid for the resource. */\n ok: true\n /** The fields to sort on and their directions, in order. */\n sort: SortSpec\n }\n | {\n /** The order is not valid for the resource. */\n ok: false\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\nconst generic = (items: OrderByItem[]) => items.map((item) => ({ path: item.path.path, direction: item.direction, span: item.span }))\n\n// The library accepts only lowercase asc/desc; Protobase also accepts any case. The rewrite keeps\n// offsets, and leaves a first word (the field name) alone.\nconst lowercaseDirections = (source: string) =>\n source.replace(/([^\\s,])(\\s+)(asc|desc)(?=\\s|,|$)/gi, (_, before: string, space: string, word: string) => `${before}${space}${word.toLowerCase()}`)\n\n/** Parses order text, AIP-132 as the API's `order_by` takes it, such as `created_at desc, name`; `asc` and `desc` in any case. */\nexport const parseOrderBy = (source: string): OrderByParse => {\n const parsed = parse(lowercaseDirections(source))\n const items: OrderByItem[] = parsed.items.map((item) => ({\n path: { kind: 'field', path: item.path, span: item.span },\n direction: item.direction,\n span: item.span,\n }))\n return parsed.ok ? { ok: true, items, errors: [] } : { ok: false, items, errors: parsed.errors }\n}\n\n/** The order as text, as `parseOrderBy` reads it. */\nexport const printOrderBy = (items: OrderByItem[]) => print(generic(items))\n\n/** Validates against sortable fields. <gap>An order cannot sort on fields of related resources, as traversal is not supported yet.</gap> */\nexport const checkOrderBy = (model: ResourceModel, items: OrderByItem[]): OrderByCheck => {\n const traversal = items\n .filter((item) => item.path.path.length > 1)\n .map((item) => filterError('unsupported-traversal', `Traversal into \"${item.path.path.join('.')}\" is not supported yet`, 'Sort on fields of this resource only', item.path.span))\n if (traversal.length > 0) return { ok: false, errors: traversal }\n const checked = check(generic(items), schemaOf(model))\n if (!checked.ok) return { ok: false, errors: checked.errors }\n return { ok: true, sort: checked.items.map((item) => [item.path[0]!, item.direction]) }\n}\n","import type { DurationLiteral, DurationUnit } from '../model'\n\nexport const parseDurationText = (text: string): DurationLiteral => {\n const match = /^(\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)([smhdw])$/.exec(text)\n if (!match) throw new Error(`Invalid duration \"${text}\", expected for example 30d or 1.5h`)\n return {\n kind: 'duration',\n amount: Number(match[1]),\n unit: match[2] as DurationUnit,\n span: { start: 0, end: 0 },\n }\n}\n","import type { FieldPath, FilterExpr, FilterValue, Literal, Span } from '../model'\nimport type { Field } from '../field'\nimport type { RecordOf } from '../resource-types'\nimport { parseDurationText } from './duration'\n\n/** @inline */\ntype Scalar = string | number | boolean\n/** @inline */\ntype Source = {\n /** The resource's fields, as `resource(...)` declares them. */\n readonly $fields: unknown\n}\n/** @inline */\ntype Fields<R extends Source> = keyof RecordOf<R['$fields']> & string\n/** @inline */\ntype Value<R extends Source, K extends Fields<R>> =\n | Extract<NonNullable<RecordOf<R['$fields']>[K]>, Scalar>\n | FilterValue\n/** @inline */\ntype Anything = {\n /** Any fields: names and values are not checked. */\n readonly $fields: Record<string, Field<any>>\n}\n\n/** @inline */\ntype RelatedPage =\n | {\n /** The order the related records are read in, as a list's `order_by`; `''` for the list's default. */\n orderBy: string\n /** A page token needs a limit: the page size it was read with. */\n pageToken?: never\n }\n | {\n /** The order the related records are read in, as a list's `order_by`; `''` for the list's default. */\n orderBy: string\n /** How many of them, in that order. */\n limit: number\n /** Which page of them, a `next_page_token` of their list. */\n pageToken?: string\n }\n\nconst span: Span = { start: 0, end: 0 }\nconst field = (name: string): FieldPath => ({ kind: 'field', path: name.split('.'), span })\n\nconst literal = (value: Scalar): Literal => {\n if (typeof value === 'string') return { kind: 'string', value, span }\n if (typeof value === 'boolean') return { kind: 'boolean', value, span }\n if (!Number.isFinite(value)) throw new Error('Filter numbers must be finite')\n return { kind: 'number', value, raw: String(value), span }\n}\n\nconst filterValue = (value: Scalar | FilterValue): FilterValue =>\n typeof value === 'object' ? value : literal(value)\n\nconst group = (kind: 'and' | 'or', args: FilterExpr[]): FilterExpr => {\n if (args.length === 0) throw new Error(`where.${kind} needs at least one filter`)\n if (args.length === 1) return args[0]!\n return { kind, args, span }\n}\n\n/**\n * Builds filters in code, for the client and the UI, as `where` does, with field names and values typed against the\n * resource `R`: `createWhere<typeof orders>().eq('status', 'paid')`. A filter it builds prints as filter text with\n * `printFilter`.\n */\nexport const createWhere = <R extends Source = Anything>() => {\n const compare =\n (op: '=' | '!=' | '<' | '<=' | '>' | '>=') =>\n <K extends Fields<R>>(name: K, value: Value<R, K>): FilterExpr => ({\n kind: 'compare',\n op,\n field: field(name),\n value: filterValue(value),\n span,\n })\n const offset = (sign: '+' | '-') => (duration: string): FilterValue => ({\n kind: 'now',\n offset: { sign, duration: parseDurationText(duration) },\n span,\n })\n\n return {\n /** The field equals the value: `status = \"paid\"`. */\n eq: compare('='),\n /** The field differs from the value: `status != \"paid\"`. */\n ne: compare('!='),\n /** The field is below the value: `total < 100`. */\n lt: compare('<'),\n /** The field is at most the value: `total <= 100`. */\n lte: compare('<='),\n /** The field is above the value: `total > 100`. */\n gt: compare('>'),\n /** The field is at least the value: `total >= 100`. */\n gte: compare('>='),\n /** The field lies from `low` to `high`, both included. */\n between: <K extends Fields<R>>(name: K, low: Value<R, K>, high: Value<R, K>) =>\n group('and', [compare('>=')(name, low), compare('<=')(name, high)]),\n /** A JSON field holds the value, as a key or an element: `tags:\"urgent\"`. */\n has: <K extends Fields<R>>(name: K, value: Scalar) =>\n ({ kind: 'has', field: field(name), value: literal(value), span }) as FilterExpr,\n /** The field has a value, a JSON field one other than `null`: `field:*`. */\n present: <K extends Fields<R>>(name: K) => ({ kind: 'present', field: field(name), span }) as FilterExpr,\n /** The field equals one of the values: `in(status, \"paid\", \"sent\")`. */\n in: <K extends Fields<R>>(name: K, values: Extract<NonNullable<RecordOf<R['$fields']>[K]>, Scalar>[]) =>\n ({ kind: 'in', field: field(name), values: values.map(literal), span }) as FilterExpr,\n /** The field has no value: `isNull(field)`. */\n isNull: <K extends Fields<R>>(name: K) => ({ kind: 'isNull', field: field(name), span }) as FilterExpr,\n /** Every word of the text appears, ignoring case, in one of the resource's search fields: `search(\"text\")`. */\n search: (text: string): FilterExpr => ({ kind: 'search', text, span }),\n /** The text field is close to the text by trigram similarity, typos included: `similar(field, \"text\")`. */\n similar: <K extends Fields<R>>(name: K, text: string) =>\n ({ kind: 'similar', field: field(name), text, span }) as FilterExpr,\n /** The text field matches the regular expression, ignoring case: `regex(field, \"pattern\")`. */\n regex: <K extends Fields<R>>(name: K, pattern: string) =>\n ({ kind: 'regex', field: field(name), pattern, span }) as FilterExpr,\n /**\n * The field holds the `key` of a record of `resource` the caller may list that meets `filter`, in a list-style read\n * of the API: `related(task_id, objective_tasks.task_id, (objective_id = 40))`. `page` keeps to one page of those\n * records, as a list of `resource` reads it: `{ orderBy: 'created_at desc', limit: 10, pageToken }`.\n */\n related: <K extends Fields<R>>(name: K, resource: string, key: string, filter?: FilterExpr, page?: RelatedPage): FilterExpr =>\n ({ kind: 'related', field: field(name), resource, key, ...(filter && { filter }), ...page, span }),\n /** Every filter holds; one filter is returned as it is, none throws. */\n and: (...args: FilterExpr[]) => group('and', args),\n /** At least one filter holds; one filter is returned as it is, none throws. */\n or: (...args: FilterExpr[]) => group('or', args),\n /** The filter does not hold. */\n not: (arg: FilterExpr): FilterExpr => ({ kind: 'not', arg, span }),\n /** The current time, as a value to compare with: `now()`. */\n now: (): FilterValue => ({ kind: 'now', span }),\n /** A time the duration before now, such as `ago('7d')` for `now() - 7d`; units are `s`, `m`, `h`, `d` and `w`. */\n ago: offset('-'),\n /** A time the duration after now, such as `fromNow('1h')` for `now() + 1h`. */\n fromNow: offset('+'),\n }\n}\n\n/**\n * Builds a filter in code instead of writing filter text, for any resource; `createWhere` checks names and values\n * against one. The [Filters](docs/website/src/content/docs/reference/api.md#filters) of the API take what it builds.\n *\n * @example\n * ```ts\n * where.and(where.eq('status', 'paid'), where.gte('created_at', where.ago('30d')))\n * ```\n */\nexport const where = createWhere()\n","import type { AnyField, Field } from './field'\n\n/** The fields of `.fields({ ... })` by name; `null` ignores a column on purpose. */\nexport type FieldsInput = Record<string, AnyField | null>\n\nexport type ActiveFields<F> = { [K in keyof F as F[K] extends null ? never : K]: F[K] }\n\n/** A field picked in a builder's callback, such as `r.status`: its name, typed with its value. */\nexport type Ref<N extends string = string, V = unknown> = {\n /** The field's name. */\n readonly name: N\n /** The field's value type, for the compiler only; never set. */\n readonly $value?: V\n}\n\n/** A reference per field of `F`, by name. */\nexport type Refs<F> = {\n readonly [K in keyof F & string]: F[K] extends Field<infer V> ? Ref<K, V> : never\n}\n\n/** The `r` of a builder's callback: a reference per field of `F`, the ignored (`null`) ones left out. */\nexport type FieldRefs<F> = Refs<ActiveFields<F>>\n\nconst refMark = Symbol('protobase.ref')\n\n/** A field reference as a view builder hands it out (`r.status`), recognisable wherever it is passed, props included. */\nexport const ref = (name: string): Ref => Object.defineProperty({ name }, refMark, { value: true })\n\nexport const isRef = (value: unknown): value is Ref => typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[refMark] === true\n\n// Records the accessed field name; with `known`, unknown names throw at runtime.\nexport const createRefs = <R>(make: (name: string) => unknown, known?: readonly string[]) =>\n new Proxy(\n {},\n {\n get: (_, name) => {\n if (typeof name === 'symbol') return undefined\n if (known && !known.includes(name)) throw new Error(`Unknown field \"${name}\"`)\n return make(name)\n },\n },\n ) as R\n","import type { JsonValue } from './model'\nimport { isRef } from './refs'\n\n/**\n * A field named inside free-form data, such as a custom component's props: `{ $field: 'status' }`, or a path through\n * relations (`plan.name`) on a page. Marked, so that the walker leaving out hidden fields finds it wherever it is.\n */\nexport type FieldRefValue = {\n /** The field's name, or a path through relations. */\n readonly $field: string\n}\n\n/** A field reference for a layout's custom component props, such as `<UsageChart field={fieldRef('total')} />`. */\nexport const fieldRef = (path: string): FieldRefValue => ({ $field: path })\n\nexport const isFieldRef = (value: unknown): value is FieldRefValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && typeof (value as FieldRefValue).$field === 'string'\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Props as a view stores them: every `r.field` in them, at any depth, becomes a field reference. */\nexport const markFieldRefs = (value: unknown): JsonValue => {\n if (isRef(value)) return fieldRef(value.name)\n if (Array.isArray(value)) return value.map(markFieldRefs)\n if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, markFieldRefs(entry)]))\n return value as JsonValue\n}\n\n/** Props as a custom component gets them: every field reference as its field's name. */\nexport const unmarkFieldRefs = <T>(value: T): T => {\n if (isFieldRef(value)) return value.$field as T\n if (Array.isArray(value)) return value.map(unmarkFieldRefs) as T\n if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, unmarkFieldRefs(entry)])) as T\n return value\n}\n\n/** Every field the value names through field references, at any depth. */\nexport const fieldRefsIn = (value: unknown): string[] => {\n if (isFieldRef(value)) return [value.$field]\n if (Array.isArray(value)) return value.flatMap(fieldRefsIn)\n if (isObject(value)) return Object.values(value).flatMap(fieldRefsIn)\n return []\n}\n","import { fieldRefsIn, markFieldRefs } from './field-ref'\nimport type { CardFavoriteModel, CardPhotosModel, JsonValue, ListDisplayModel, RelatedColumnModel, ResourceModel } from './model'\nimport type { Ref } from './refs'\nimport type { ListColumn } from './view-columns'\n\n/** A custom component as `component(name)` from `@protobase/layout` declares it. */\nexport type ComponentRef<P> = ((props: P) => unknown) & {\n /** The name it is registered under. */\n readonly blockName: string\n /** Whether it is the project's or a plugin's, rather than a built-in block. */\n readonly custom: boolean\n}\n\n/** A custom component's props as a view gives them: plain data, or `r.field` where it takes a field's name. */\nexport type ViewProps<P> = { [K in keyof Omit<P, 'children'>]: P[K] extends string ? P[K] | Ref : P[K] }\n\n/** @inline */\ntype Naming = { name?: string; label?: string; icon?: string }\n\nconst naming = ({ label, icon }: Naming) => ({ ...(label !== undefined && { label }), ...(icon !== undefined && { icon }) })\n\n/** The most photos a card steps through, its own image among them, each marked by a dot: a list includes this many of each record's photos. */\nexport const cardPhotoLimit = 10\n\n/** The name of the list's own display, which every list has. */\nexport const tableDisplay = 'table'\n\n/** The component of a custom display or section, which must be a project's, not a built-in block. */\nexport const customComponent = (component: ComponentRef<never>, where: string) => {\n if (!component.custom) throw new Error(`${where} takes a component declared with component(...), not the built-in block ${component.blockName}`)\n return component.blockName\n}\n\nexport const displays = {\n /**\n * A card per record: `image`, a file field shown as a picture across the card's top, then `title` (default: the\n * view's title) over `subtitle`, `badge` drawn as a badge with its value labels, `amount` the first of its fields with a\n * value in bold, such as a purchase price or a rent, `code` its value in full as a block of monospaced text that wraps,\n * such as a shell command, and a few small `meta` fields such as dates. `footer` is a line at\n * the card's bottom of its fields with a value, joined by bullets. `flags` are boolean fields shown as small badges of their labels when true, such as a garden or parking.\n * `dots` are related columns of the list (`c.related`), each a line of its dots under the rest of the card, with the\n * colours, order and hover cards they have in the table; a column with no records for the row shows no line.\n * With `card`, a component of the project or a plugin draws each card's content instead, from the row of those\n * fields (`{ row }`); without it, or when it throws, the card is the built-in one. With `photos`, the built-in card's\n * picture gets arrows through the `image` of the records of another resource that point at the card's record, after\n * its own `image`, ten pictures at most; they come with the list's records, so its dots mark the one shown from the\n * start. A list's cards displays name the same `photos`. With `favorite`, a heart in the card's top right corner saves\n * the record to the signed-in user's own records of another resource, such as favorites, and takes it off again; a\n * visitor who is not signed in is told why to sign in. Named `cards` unless `name` says otherwise.\n */\n cards: (\n fields: { image?: Ref; title?: Ref; subtitle?: Ref; amount?: Ref[]; badge?: Ref; code?: Ref; meta?: Ref[]; footer?: Ref[]; flags?: Ref[]; dots?: ListColumn[] },\n o: Naming & { card?: ComponentRef<never>; photos?: CardPhotosModel; favorite?: CardFavoriteModel } = {},\n ): ListDisplayModel => ({\n kind: 'cards',\n name: o.name ?? 'cards',\n ...naming(o),\n ...(fields.image && { image: fields.image.name }),\n ...(fields.title && { title: fields.title.name }),\n ...(fields.subtitle && { subtitle: fields.subtitle.name }),\n ...(fields.amount && { amount: fields.amount.map((ref) => ref.name) }),\n ...(fields.badge && { badge: fields.badge.name }),\n ...(fields.code && { code: fields.code.name }),\n ...(fields.meta && { meta: fields.meta.map((ref) => ref.name) }),\n ...(fields.footer && { footer: fields.footer.map((ref) => ref.name) }),\n ...(fields.flags && { flags: fields.flags.map((ref) => ref.name) }),\n ...(fields.dots && { dots: fields.dots.map((column) => column.name) }),\n ...(o.card && { card: customComponent(o.card, 'd.cards card') }),\n ...(o.photos && { photos: { ...o.photos } }),\n ...(o.favorite && { favorite: { ...o.favorite } }),\n }),\n /**\n * A map of the records at their `latitude` and `longitude`, filterable fields in decimal degrees, drawn with the app's\n * map style. It asks for the records in its view as it pans and zooms: from far out a count for each part of the map,\n * which zooms in when chosen, closer in the records. A marker stands for the records that lie close together at the\n * zoom; choosing it shows their card at the map's bottom, with arrows through them. The card is the one of the cards display named `cards`, the list's first cards display\n * when it names none, or the record's title alone without one. A record's position is approximate when its boolean\n * `approximate` field is true, or its `exact` field false: its marker is drawn hollow and says so, and close enough in\n * an area is drawn around it, the GeoJSON polygon or line its `area` field holds, else a circle of its `radius` field\n * in metres, else one of `defaultRadius`. Named `map` unless `name` says otherwise. See\n * [Approximate positions](docs/website/src/content/docs/reference/ui-config.mdx#approximate-positions).\n */\n map: (\n fields: { latitude: Ref; longitude: Ref; approximate?: Ref; exact?: Ref; radius?: Ref; area?: Ref },\n o: Naming & { cards?: string; defaultRadius?: number } = {},\n ): ListDisplayModel => ({\n kind: 'map',\n name: o.name ?? 'map',\n ...naming(o),\n latitude: fields.latitude.name,\n longitude: fields.longitude.name,\n ...(o.cards !== undefined && { cards: o.cards }),\n ...(fields.approximate && { approximate: fields.approximate.name }),\n ...(fields.exact && { exact: fields.exact.name }),\n ...(fields.radius && { radius: fields.radius.name }),\n ...(o.defaultRadius !== undefined && { defaultRadius: o.defaultRadius }),\n ...(fields.area && { area: fields.area.name }),\n }),\n /**\n * A column per value of the enum field `by`, in the order the field lists them, each headed by its value label and how\n * many of the list's records have it; with a column for records without a value when the field may be empty. Each\n * column pages through the list API with the list's filter and search, its value added, in the list's order. A card\n * shows `title` (default: the view's title) over `subtitle`, with `badge` and a few small `meta` fields, as the built-in\n * card of `d.cards` does, and opens the record. With the list's `drag: { board: true }`, dragging a card to another\n * column, or picking it up with Space and moving it with the arrow keys, saves the record with `by` set to that\n * column's value, as one update with its ETag, so the resource's access rules and `validate` decide, and a refusal\n * puts the card back and says why; with `drag: { board: 'name' }` only between the columns the UI config's board drop\n * of that name lists, each running its own write; with `drag: { rank: true }` a card moves within its column too. `by` must be\n * a filterable enum field. Named `board` unless `name` says otherwise. See\n * [Boards](docs/website/src/content/docs/reference/ui-config.mdx#boards).\n */\n board: (fields: { by: Ref; title?: Ref; subtitle?: Ref; badge?: Ref; meta?: Ref[] }, o: Naming = {}): ListDisplayModel => ({\n kind: 'board',\n name: o.name ?? 'board',\n ...naming(o),\n by: fields.by.name,\n ...(fields.title && { title: fields.title.name }),\n ...(fields.subtitle && { subtitle: fields.subtitle.name }),\n ...(fields.badge && { badge: fields.badge.name }),\n ...(fields.meta && { meta: fields.meta.map((ref) => ref.name) }),\n }),\n /**\n * The records on the days from `start` to `end` (or on their start day alone), in a month grid of whole weeks or a\n * week grid, with weeks from Monday and days in UTC. It loads only the days shown through the list API, with the\n * list's filter and search, in start order. An event shows `title` (default: the view's title), after its time for a\n * timestamp, and opens the record. Dragging an event to another day, or picking it up with Space and moving it with\n * the arrow keys, saves the record with `start` and `end` moved by the same days, as one update with its ETag, so the\n * resource's access rules and `validate` decide, and a refusal puts the event back and says why. `start` must be a\n * filterable date or timestamp field and `end` a filterable field of the same type. Named `calendar` unless `name`\n * says otherwise. See [Calendars](docs/website/src/content/docs/reference/ui-config.mdx#calendars).\n */\n calendar: (fields: { start: Ref; end?: Ref; title?: Ref }, o: Naming = {}): ListDisplayModel => ({\n kind: 'calendar',\n name: o.name ?? 'calendar',\n ...naming(o),\n start: fields.start.name,\n ...(fields.end && { end: fields.end.name }),\n ...(fields.title && { title: fields.title.name }),\n }),\n /**\n * The records as bars from the day of `start` to the day of `end` (or their start day alone), one row each, over a\n * week, a month or a quarter, in lanes by the values of `group`, with weeks from Monday. It loads only the days shown\n * through the list API, with the list's filter and search, in start order, as a calendar does. A bar shows `title`\n * (default: the view's title) and opens the record. Dragging a bar along its row, or picking it up with Space and\n * moving it with the arrow keys, saves the record with `start` and `end` moved by the same days, as one update with\n * its ETag, so the resource's access rules and `validate` decide, and a refusal puts the bar back and says why.\n * `start` must be a filterable date or timestamp field and `end` a filterable field of the same type. Named\n * `timeline` unless `name` says otherwise. See [Timelines](docs/website/src/content/docs/reference/ui-config.mdx#timelines).\n */\n timeline: (fields: { start: Ref; end?: Ref; group?: Ref; title?: Ref }, o: Naming = {}): ListDisplayModel => ({\n kind: 'timeline',\n name: o.name ?? 'timeline',\n ...naming(o),\n start: fields.start.name,\n ...(fields.end && { end: fields.end.name }),\n ...(fields.group && { group: fields.group.name }),\n ...(fields.title && { title: fields.title.name }),\n }),\n /**\n * The list drawn by a component of the project, registered in `protobase.ui.tsx` under its name. It gets `props` and\n * reads the rows with `useListDisplay()`; `fields` are the fields it shows, fetched with relation names.\n */\n custom: <P extends object>(component: ComponentRef<P>, o: Naming & { name: string; label: string; fields: Ref[]; props?: ViewProps<P> }): ListDisplayModel => ({\n kind: 'custom',\n name: o.name,\n label: o.label,\n ...naming({ icon: o.icon }),\n component: customComponent(component as ComponentRef<never>, 'd.custom'),\n fields: o.fields.map((ref) => ref.name),\n ...(o.props && { props: markFieldRefs(o.props) as Record<string, JsonValue> }),\n }),\n}\n\nconst displayName = /^[a-z][a-zA-Z0-9-]*$/\n\n/** What is wrong with a list's displays and default, by their names alone. */\nexport const displayErrors = (list: { displays?: ListDisplayModel[]; default?: string; relatedColumns?: RelatedColumnModel[] }): string[] => {\n const names = (list.displays ?? []).map((display) => display.name)\n return [\n ...names.filter((name) => !displayName.test(name)).map((name) => `display name \"${name}\" must start with a lowercase letter and hold only letters, digits and dashes`),\n ...names.filter((name) => name === tableDisplay).map(() => `\"${tableDisplay}\" is the list's own display; give the display another name`),\n ...names.filter((name, index) => names.indexOf(name) !== index).map((name) => `display \"${name}\" is defined twice`),\n ...(list.displays ?? []).flatMap((display) =>\n display.kind === 'map' && display.cards !== undefined && !list.displays!.some((other) => other.kind === 'cards' && other.name === display.cards)\n ? [`display \"${display.name}\" names cards \"${display.cards}\", which is not a cards display of the list`]\n : [],\n ),\n ...(list.displays ?? []).flatMap((display) =>\n display.kind === 'cards'\n ? (display.dots ?? []).filter((name) => !list.relatedColumns?.some((column) => column.name === name)).map((name) => `display \"${display.name}\" shows dots of \"${name}\", which is not a related column of the list`)\n : [],\n ),\n ...(list.displays ?? []).flatMap((display) => (display.kind === 'map' ? approximateErrors(display).map((error) => `display \"${display.name}\": ${error}`) : [])),\n ...(list.default === undefined || list.default === tableDisplay || names.includes(list.default) ? [] : [`default \"${list.default}\" is not one of the displays (${[tableDisplay, ...names].join(', ')})`]),\n ]\n}\n\n// An area surrounds an approximate position, so it needs the field that says which positions are.\nconst approximateErrors = (display: Extract<ListDisplayModel, { kind: 'map' }>) => {\n const { approximate, exact, radius, defaultRadius, area } = display\n if (approximate !== undefined && exact !== undefined) return ['name approximate or exact, not both']\n const surrounds = radius !== undefined || defaultRadius !== undefined || area !== undefined\n return [\n ...(surrounds && approximate === undefined && exact === undefined ? ['an area around approximate positions needs the approximate or exact field'] : []),\n ...(defaultRadius === undefined || (Number.isFinite(defaultRadius) && defaultRadius > 0) ? [] : [`defaultRadius ${defaultRadius} is not a number of metres above 0`]),\n ]\n}\n\n/** What makes a board unable to put the records in columns: a `by` field that is no filterable enum. */\nexport const boardErrors = (display: Extract<ListDisplayModel, { kind: 'board' }>, model: ResourceModel): string[] => {\n const field = Object.hasOwn(model.fields, display.by) ? model.fields[display.by]! : undefined\n // An unknown field is reported with every display's fields\n if (!field) return []\n if (field.type !== 'enum') return [`\"${display.by}\" on ${model.name} is ${field.type}, not an enum, whose values are the board's columns`]\n return field.filterable ? [] : [`\"${display.by}\" on ${model.name} is not filterable, and each column of the board filters by its value`]\n}\n\n/** What makes a calendar or a timeline unable to place the records on days: a `start` that is no filterable date or timestamp, or an `end` that is no filterable field of its type. */\nexport const datesErrors = (display: Extract<ListDisplayModel, { kind: 'calendar' | 'timeline' }>, model: ResourceModel): string[] => {\n const known = (name: string) => (Object.hasOwn(model.fields, name) ? model.fields[name]! : undefined)\n const start = known(display.start)\n const end = display.end === undefined ? undefined : known(display.end)\n // An unknown field is reported with every display's fields\n if (!start) return []\n if (start.type !== 'date' && start.type !== 'timestamp') return [`start \"${display.start}\" on ${model.name} is ${start.type}, not a date or timestamp`]\n const unfilterable = (name: string) => `${name === display.start ? 'start' : 'end'} \"${name}\" on ${model.name} is not filterable, and the ${display.kind} filters by it for the days it shows`\n return [\n ...(start.filterable ? [] : [unfilterable(display.start)]),\n ...(end && end.type !== start.type ? [`end \"${display.end}\" on ${model.name} is ${end.type}, not ${start.type} like start \"${display.start}\"`] : []),\n ...(end && end.type === start.type && !end.filterable ? [unfilterable(display.end!)] : []),\n ]\n}\n\n/** Every field a display names: what it shows, a map's position and the fields saying how exact it is, a board's columns, a calendar's dates, a timeline's dates and lanes, and the field references in a custom display's props. */\nexport const displayFields = (display: ListDisplayModel): string[] => {\n if (display.kind === 'map') return [display.latitude, display.longitude, display.approximate, display.exact, display.radius, display.area].filter((name): name is string => name !== undefined)\n if (display.kind === 'custom') return [...display.fields, ...fieldRefsIn(display.props)]\n if (display.kind === 'board') return [display.by, display.title, display.subtitle, display.badge, ...(display.meta ?? [])].filter((name): name is string => name !== undefined)\n if (display.kind === 'calendar') return [display.start, display.end, display.title].filter((name): name is string => name !== undefined)\n if (display.kind === 'timeline') return [display.start, display.end, display.group, display.title].filter((name): name is string => name !== undefined)\n return [display.image, display.title, display.subtitle, ...(display.amount ?? []), display.badge, display.code, ...(display.meta ?? []), ...(display.footer ?? []), ...(display.flags ?? [])].filter((name): name is string => name !== undefined)\n}\n","import type { ViewModel } from './model'\n\n/**\n * The view a list page shows: `view` itself, or, with `list`, the view with that named list's names, nav, help, list,\n * filters and chart in place of its own, and no named lists; none when the view has no list by that name.\n */\nexport const viewOfList = (view: ViewModel | undefined, list: string | undefined): ViewModel | undefined => {\n if (list === undefined) return view\n const named = view?.lists?.find((entry) => entry.name === list)\n if (!view || !named) return undefined\n const { list: _list, chart: _chart, help: _help, nav: _nav, lists: _lists, names: _names, ...rest } = view\n const { name: _name, ...parts } = named\n return { ...rest, ...parts }\n}\n","import { addressPlaceholders, embeddedFilterFields, filterField, resourceField } from './address-template'\nimport { checkFilter, checkOrderBy, parseFilter, parseOrderBy } from './filter'\nimport type { AppAddress, FilterErrorCode, ResourceModel } from './model'\n\nexport type AddressCheck = {\n /** The resources; against a caller's restricted models, the check says whether that caller can follow the link. */\n models: Record<string, ResourceModel>\n /** The composed pages; without them a page's name is not checked. */\n pages?: ReadonlySet<string>\n /** The resource of the record the link sits on, whose fields its `{{field}}` placeholders name. */\n source?: ResourceModel\n /** Why a placeholder's path cannot be filled, in place of `source`'s fields, such as a layout's lookup through the records around a link. */\n placeholderError?: (path: string) => string | undefined\n /** The resources whose view opens a create page of the app's own, which reads a create address's values whatever their names. */\n createPages?: ReadonlySet<string>\n /** A list's filter may be one `{{field}}`, the record's text, which whoever draws the link parses and checks against the caller's models, as a row button does. */\n filterFromRecord?: boolean\n}\n\n// Errors about names, not values: a placeholder's value is only known when the link is followed.\nconst nameErrors: readonly FilterErrorCode[] = ['unknown-field', 'not-filterable', 'not-sortable', 'unsupported-traversal', 'invalid-traversal']\n\n// A quoted placeholder stands in for a word and any other for a number, so the filter parses and its names can be checked.\nconst withSamples = (filter: string) => filter.replace(/([\"']?)\\{\\{\\s*[^{}]*?\\s*\\}\\}\\1/g, (_, quote: string) => (quote ? `${quote}x${quote}` : '0'))\n\nconst filterErrors = (model: ResourceModel, filter: string) => {\n const embedded = embeddedFilterFields(filter)\n if (embedded.length > 0) return embedded.map((name) => `filter: \"{{${name}}}\" sits inside a longer quoted value; quote it alone, such as title = \"{{${name}}}\"`)\n const parsed = parseFilter(withSamples(filter))\n if (!parsed.ok) return parsed.errors.map((error) => `filter: ${error.message}`)\n if (!parsed.ast) return []\n const checked = checkFilter(model, parsed.ast)\n return checked.ok ? [] : checked.errors.filter((error) => nameErrors.includes(error.code)).map((error) => `filter: ${error.message}`)\n}\n\nconst orderErrors = (model: ResourceModel, orderBy: string) => {\n if (addressPlaceholders({ kind: 'list', resource: model.name, orderBy }).length > 0) return []\n const parsed = parseOrderBy(orderBy)\n if (!parsed.ok) return parsed.errors.map((error) => `orderBy: ${error.message}`)\n const checked = checkOrderBy(model, parsed.items)\n return checked.ok ? [] : checked.errors.map((error) => `orderBy: ${error.message}`)\n}\n\n/**\n * What is wrong with a link's address against these models: an unknown resource or page, a filter, order or values\n * beside a resource taken from the record (`'{{field}}'`), but with `filterFromRecord` a filter that is one `{{field}}`, a `{{field}}` the record it sits\n * on does not have, a filter or order naming fields the resource does not have, or create values for fields it does not\n * have, unless its view opens a create page, which reads them. Empty when it can be followed.\n */\nexport const addressErrors = (to: AppAddress, { models, pages, source, placeholderError, createPages, filterFromRecord }: AddressCheck): string[] => {\n const placeholders = addressPlaceholders(to).flatMap((name) => {\n if (placeholderError) {\n const error = placeholderError(name)\n return error === undefined ? [] : [error]\n }\n if (!source) return [`\"{{${name}}}\" takes a value from the record, but the link sits on none`]\n return Object.hasOwn(source.fields, name) ? [] : [`\"{{${name}}}\" is not a field of ${source.name}`]\n })\n // A filter the record holds whole is known only when the link is drawn, which checks it then.\n const recordFilter = filterFromRecord === true && filterField(to) !== undefined\n // A resource taken from the record is known only when the link is followed, so the address names none of its fields.\n if (to.kind !== 'page' && resourceField(to) !== undefined) {\n const named = to.kind === 'list' ? (to.filter !== undefined && !recordFilter) || to.orderBy !== undefined : to.kind === 'create' && to.values !== undefined\n if (!named) return placeholders\n const allowed = filterFromRecord ? 'no order or values, and a filter only as one field, such as filter: \\'{{filter}}\\'' : 'no filter, order or values'\n return [...placeholders, `a link whose resource comes from the record (\"${to.resource}\") names ${allowed}`]\n }\n switch (to.kind) {\n case 'page':\n return pages && !pages.has(to.page) ? [...placeholders, `unknown page \"${to.page}\"`] : placeholders\n case 'list':\n case 'record':\n case 'create': {\n const target = Object.hasOwn(models, to.resource) ? models[to.resource] : undefined\n if (!target) return [`unknown resource \"${to.resource}\"`]\n if (to.kind === 'create' && createPages?.has(to.resource)) return placeholders\n if (to.kind === 'create') return [...placeholders, ...Object.keys(to.values ?? {}).filter((name) => !Object.hasOwn(target.fields, name)).map((name) => `values: unknown field \"${name}\" on ${to.resource}`)]\n if (to.kind !== 'list') return placeholders\n return [...placeholders, ...(to.filter && !recordFilter ? filterErrors(target, to.filter) : []), ...(to.orderBy ? orderErrors(target, to.orderBy) : [])]\n }\n default:\n return [`an address's kind is list, record, create or page, not \"${String((to as { kind: unknown }).kind)}\"`]\n }\n}\n","import { addressErrors, type AddressCheck } from './address-errors'\nimport { addressPlaceholders, hrefField, textPlaceholders } from './address-template'\nimport type { AppAddress, ResourceModel, RowButtonChoice, RowButtonModel } from './model'\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst shape = \"a row button is { label, to } or { label, href }, such as { label: 'Open', to: { kind: 'record', resource: 'tasks', key: '{{id}}' } } or { label: 'Report', href: '{{report_url}}' }, or a list of them\"\n\n/** A row button's choices, in order: the one it is, or each of its list. */\nexport const rowButtonChoices = (button: RowButtonModel): readonly RowButtonChoice[] => (Array.isArray(button) ? button : [button as RowButtonChoice])\n\n/** Where a choice goes: its `href` when it has one, as the check reads it, otherwise its address in `to`. */\nexport const rowButtonTarget = (choice: RowButtonChoice): { href: string } | { to: AppAddress } => {\n const href = (choice as { href?: string }).href\n return href === undefined ? { to: (choice as { to: AppAddress }).to } : { href }\n}\n\n/** The fields of the row a choice's label and address or href read; a row without a value for one of them skips it. */\nexport const rowButtonChoiceFields = (choice: RowButtonChoice) => {\n const target = rowButtonTarget(choice)\n return [...new Set([...textPlaceholders(choice.label), ...('href' in target ? textPlaceholders(target.href) : addressPlaceholders(target.to))])]\n}\n\n/** The fields of the row any of a button's choices reads, to load with the rows. */\nexport const rowButtonFields = (button: RowButtonModel) => [...new Set(rowButtonChoices(button).flatMap(rowButtonChoiceFields))]\n\nconst missing = (names: string[], source: ResourceModel, part: string) => names.flatMap((name) => (Object.hasOwn(source.fields, name) ? [] : [`${part}: \"{{${name}}}\" is not a field of ${source.name}`]))\n\nconst choiceErrors = (choice: unknown, source: ResourceModel, check: Omit<AddressCheck, 'source'>): string[] => {\n if (!isObject(choice)) return [shape]\n if (typeof choice.label !== 'string' || choice.label.trim() === '') return ['a row button needs a label']\n if (choice.to !== undefined && choice.href !== undefined) return ['a row button opens an address in `to` or an outside page in `href`, not both']\n const label = missing(textPlaceholders(choice.label), source, 'label')\n if (choice.href !== undefined) {\n const field = typeof choice.href === 'string' ? hrefField(choice.href) : undefined\n if (field === undefined) return [...label, \"href: a row button's href is the one field that holds the page's https URL, such as '{{report_url}}'\"]\n return [...label, ...missing([field], source, 'href')]\n }\n if (!isObject(choice.to) || typeof choice.to.kind !== 'string') return [\"a row button needs an address in `to`, such as { kind: 'record', resource: 'tasks', key: '{{id}}' }, or an outside page in `href`\"]\n return [...label, ...addressErrors(choice.to as AppAddress, { ...check, source, filterFromRecord: true }).map((error) => `to: ${error}`)]\n}\n\n/**\n * What is wrong with a row button on the rows of `source`: per choice, a missing label or target, both an address and an\n * href, an href that is not one `{{field}}`, a `{{field}}` the rows do not have, or an address that cannot be followed,\n * against `check`'s models; or a list without choices. Empty when every row can show it.\n */\nexport const rowButtonErrors = (button: unknown, source: ResourceModel, check: Omit<AddressCheck, 'source'>): string[] => {\n if (!Array.isArray(button)) return choiceErrors(button, source, check)\n if (button.length === 0) return ['a row button list needs at least one choice']\n return button.flatMap((choice, index) => choiceErrors(choice, source, check).map((error) => `choice ${index + 1}: ${error}`))\n}\n\n/**\n * `button` with only the choices a caller can follow against `check`'s restricted models, in order, so their rows fall\n * through to the next; none when no choice is left.\n */\nexport const followableRowButton = (button: RowButtonModel, source: ResourceModel, check: Omit<AddressCheck, 'source'>): RowButtonModel | undefined => {\n if (!Array.isArray(button)) return rowButtonErrors(button, source, check).length === 0 ? button : undefined\n const kept = rowButtonChoices(button).filter((choice) => choiceErrors(choice, source, check).length === 0)\n return kept.length === 0 ? undefined : kept\n}\n","import { enumLabel } from './enum-label'\nimport type { FieldModel, ResourceModel, ViewModel } from './model'\n\nconst labelCandidates = ['name', 'title', 'number', 'sku', 'email', 'code', 'description']\n\n// A sensitive field, write-only ones included, is in no list response, so it cannot name a record\nconst namesRecords = (field: FieldModel | undefined) => field?.type === 'text' && !field.sensitive\n\n/** The field that names a record when another record points at it. */\nexport const labelFieldOf = (model: ResourceModel, view?: ViewModel) =>\n view?.title ??\n labelCandidates.find((name) => namesRecords(model.fields[name])) ??\n Object.values(model.fields).find(namesRecords)?.name ??\n model.primaryKey[0]!\n\n/** What names a record: the view's `title`, else the first text column of its list, else `labelFieldOf`. */\nexport const recordTitleField = (model: ResourceModel, view: ViewModel | undefined) =>\n view?.title ?? view?.list?.columns.find((name) => model.fields[name]?.type === 'text') ?? labelFieldOf(model)\n\n/** A record's name as shown: its title field's value, an enum's by its label, else `fallback` when the value is missing. */\nexport const recordTitle = (model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, fallback: string) => {\n const name = recordTitleField(model, view)\n const value = record[name]\n if (value === null || value === undefined) return fallback\n return model.fields[name]?.type === 'enum' ? enumLabel(String(value), view?.fields[name]?.valueLabels) : String(value)\n}\n","import type { ResourceModel, ViewModel } from './model'\n\n/** The fields a view's list shows as columns: its list columns, else the resource's first six fields the caller reads. */\nexport const listColumnNames = (resource: ResourceModel, view: ViewModel | undefined) =>\n view?.list?.columns ?? Object.values(resource.fields).filter((field) => !field.writeOnly).slice(0, 6).map((field) => field.name)\n","import { createContext, useContext, useMemo, type ReactNode } from 'react'\n\nconst GuardedParamsContext = createContext<readonly string[]>([])\n\n/**\n * Content a change of the page parameter `name` replaces, such as the row a `select` chose: a navigation guard inside\n * it asks before that parameter changes, as before leaving the page.\n */\nexport const GuardedParams = ({ name, children }: { name: string; children: ReactNode }) => {\n const outer = useContext(GuardedParamsContext)\n const names = useMemo(() => [...outer, name], [outer, name])\n return <GuardedParamsContext.Provider value={names}>{children}</GuardedParamsContext.Provider>\n}\n\n/** The page parameters whose change replaces the content around, from every `GuardedParams` it sits in. */\nexport const useGuardedParams = () => useContext(GuardedParamsContext)\n","/** A guard's watch: the page parameters whose change replaces the content it sits in, such as the row a `select` chose. */\nexport type GuardWatch = { params: readonly string[] }\n\n/** Whether going from `from` to `to` leaves what a guard holds: another page, or a change of a parameter one watches. */\nexport const leavesPage = (from: string, to: string, guards: Iterable<GuardWatch>) => {\n const before = new URL(from, 'http://local')\n const after = new URL(to, 'http://local')\n if (before.pathname !== after.pathname) return true\n return [...guards].some((guard) => guard.params.some((name) => before.searchParams.get(name) !== after.searchParams.get(name)))\n}\n","export type NavigateOptions = { replace?: boolean; keepScroll?: boolean }\n\n/** A link followed while a guard asks first, held with its options until the person chooses to leave. */\nexport type PendingLink = { kind: 'link'; full: string; replace: boolean; keepScroll: boolean }\n\nexport const pendingLink = (full: string, { replace = false, keepScroll = false }: NavigateOptions = {}): PendingLink => ({ kind: 'link', full, replace, keepScroll })\n\n/** Follows a confirmed pending link as the link itself would have been followed with no guard in the way. */\nexport const followLink = (link: PendingLink, go: (full: string, replace: boolean, keepScroll: boolean) => void) => go(link.full, link.replace, link.keepScroll)\n","import { guarded } from '../lib/guarded'\n\nconst storageKey = 'protobase:page-places'\n/** The places kept, the most recent ones, so the storage stays small however long the tab is used. */\nconst kept = 50\n\nconst isPlace = (value: unknown): value is [string, number] =>\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number' && Number.isFinite(value[1]) && value[1] >= 0\n\nconst read = (storage: Pick<Storage, 'getItem'>): [string, number][] =>\n guarded(() => {\n const raw = storage.getItem(storageKey)\n if (raw === null) return []\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed.filter(isPlace) : []\n }, [])\n\n/**\n * How far down the document was scrolled in each history entry of a tab, by the entry's id, kept in `storage` (the\n * tab's session storage) when `persist` is called, so they outlast a reload of the page. An entry never left yet, as\n * one a link just made, starts at the top.\n */\nexport const createPagePlaces = (storage: Pick<Storage, 'getItem' | 'setItem'>) => {\n // The most recent last\n const places = new Map(read(storage))\n\n const placeOf = (entry: string) => places.get(entry) ?? 0\n\n const save = (entry: string, top: number) => {\n places.delete(entry)\n places.set(entry, Math.max(0, Math.round(top)))\n for (const oldest of [...places.keys()].slice(0, Math.max(0, places.size - kept))) places.delete(oldest)\n }\n\n const persist = () => guarded(() => storage.setItem(storageKey, JSON.stringify([...places])), undefined)\n\n return { placeOf, save, persist }\n}\n\nexport type PagePlaces = ReturnType<typeof createPagePlaces>\n","/** How long a page may take to grow tall enough, as while its data loads, before it is left where it is. */\nconst patience = 3000\n\n/**\n * Scrolls the document to `top`. A page still too short for it, as one whose data is loading, is scrolled again each\n * time it grows, until it is there, a few seconds pass, or anything else scrolls it: the person, or a list that brings\n * itself back to its place. Returns how to stop early.\n */\nexport const restoreScroll = (top: number) => {\n let placed = 0\n const place = () => {\n window.scrollTo({ top, behavior: 'instant' })\n placed = window.scrollY\n return placed >= top - 1\n }\n if (place()) return () => {}\n const observer = new ResizeObserver(() => place() && stop())\n const moved = () => Math.abs(window.scrollY - placed) > 1 && stop()\n const stop = () => {\n observer.disconnect()\n clearTimeout(timer)\n window.removeEventListener('scroll', moved)\n }\n const timer = setTimeout(stop, patience)\n observer.observe(document.body)\n window.addEventListener('scroll', moved, { passive: true })\n return stop\n}\n","import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type AnchorHTMLAttributes, type ReactNode } from 'react'\nimport { guarded } from '../lib/guarded'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { RouteLink } from '../primitives/route-link'\nimport { text as appText } from './messages'\nimport { useGuardedParams } from './guarded-params'\nimport { leavesPage } from './leaves-page'\nimport { followLink, pendingLink, type NavigateOptions, type PendingLink } from './pending-link'\nimport { createPagePlaces } from './page-places'\nimport { restoreScroll } from './restore-scroll'\n\ntype RouterValue = {\n /** Path below the base path, always starting with `/`. */\n path: string\n params: URLSearchParams\n basePath: string\n /** The id of this page's entry in the tab's history: Back and Forward return to the same id, a reload keeps it. */\n entry: string\n /**\n * Moves to a path below the base path, as `appPath` writes it. `keepScroll` starts the new entry where the page is\n * scrolled now, for a change within the page, such as a choice its address holds, instead of at the top.\n */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Goes back to a path below the base path: as the browser's Back when the page before is that path, else as `navigate`. */\n back: (to: string) => void\n /**\n * Asks to be told before the page changes, or one of the page parameters `params` whose content the guard sits in;\n * returns how to stop asking. Used by `useNavigationGuard`.\n */\n registerGuard: (kind?: GuardKind, params?: readonly string[]) => () => void\n /** Reloads the page, asking first while a guard holds unsaved changes. */\n reload: () => void\n /** Whether the person chose to reload despite unsaved changes, so the page leaves without asking again. */\n reloadConfirmed: () => boolean\n /** Whether a guard holds unsaved changes, so leaving the page would ask first. */\n holdsChanges: () => boolean\n}\n\n/**\n * What leaving the page does to the input a guard holds: `draft-kept` when this browser keeps it, as a record's draft,\n * `input-lost` when it is gone.\n */\nexport type GuardKind = 'draft-kept' | 'input-lost'\n\nexport type { NavigateOptions }\n\nconst RouterContext = createContext<RouterValue | null>(null)\n\nexport const useRouter = () => {\n const value = useContext(RouterContext)\n if (!value) throw new Error('useRouter must be used inside Router')\n return value\n}\n\nexport type RouterProps = {\n basePath?: string\n /** Keeps the location in memory instead of the address bar, for Storybook and tests. */\n initialUrl?: string\n children: ReactNode\n}\n\nconst browserUrl = () => `${window.location.pathname}${window.location.search}`\n\n/** A change of page waiting for the person's answer; `inputLost` when a guard's input would be gone, not kept. */\ntype Pending = (PendingLink | { kind: 'history'; delta: number } | { kind: 'reload' }) & { inputLost: boolean }\n\nconst pathOf = (url: string) => new URL(url, 'http://local').pathname\n\n/** `protobasePrevious` is the URL of the page this entry was opened from, so going back to it can take the browser's Back. */\ntype HistoryState = { protobaseIndex?: number; protobaseEntry?: string; protobasePrevious?: string }\nconst historyState = () => (window.history.state as HistoryState | null) ?? {}\n\n/** Our place in the browser history, so a back or forward press can be told apart and, if needed, undone. */\nconst historyIndex = () => historyState().protobaseIndex ?? 0\n\nconst newEntry = () => Math.random().toString(36).slice(2)\n\n/** The id of the current history entry, given one if it has none yet, as an entry pushed before the app started. */\nconst historyEntry = () => {\n const state = historyState()\n if (state.protobaseEntry) return state.protobaseEntry\n const entry = newEntry()\n window.history.replaceState({ ...state, protobaseEntry: entry }, '')\n return entry\n}\n\nconst noStorage = { getItem: () => null, setItem: () => {} }\n\nexport const Router = ({ basePath = '', initialUrl, children }: RouterProps) => {\n const memory = initialUrl !== undefined\n const [page, setPage] = useState(() => ({ url: initialUrl ?? browserUrl(), entry: memory ? newEntry() : historyEntry() }))\n const [places] = useState(() => createPagePlaces(memory ? noStorage : (guarded(() => window.sessionStorage, undefined) ?? noStorage)))\n const guards = useRef(new Map<symbol, { kind: GuardKind; params: readonly string[] }>())\n const losesInput = () => [...guards.current.values()].some((guard) => guard.kind === 'input-lost')\n const current = useRef(page)\n current.current = page\n const position = useRef(memory ? 0 : historyIndex())\n const undoing = useRef(false)\n const proceeding = useRef(false)\n // A Leave pressed before the step back has landed: the browser drops a traversal asked for while another is under way.\n const leaveAfterUndo = useRef<number | undefined>(undefined)\n const reloading = useRef(false)\n const [pending, setPending] = useState<Pending>()\n // Where the page being left was scrolled, read before the next page is drawn and changes it\n const rememberScroll = useCallback(() => places.save(current.current.entry, window.scrollY), [places])\n\n // A new page starts at the top, and one gone back or forward to where it was left. The browser's own restoring cannot:\n // a pushed entry keeps the scroll position, and a traversal restores it before the page it returns to is drawn.\n useLayoutEffect(() => restoreScroll(places.placeOf(page.entry)), [places, page.entry])\n\n useEffect(() => {\n if (memory) return\n window.history.scrollRestoration = 'manual'\n window.history.replaceState({ ...historyState(), protobaseIndex: position.current, protobaseEntry: current.current.entry }, '')\n // A reload or a discarded tab comes back to where the page was\n const persist = () => {\n rememberScroll()\n places.persist()\n }\n const hidden = () => document.visibilityState === 'hidden' && persist()\n window.addEventListener('pagehide', persist)\n document.addEventListener('visibilitychange', hidden)\n const onPop = () => {\n const next = historyIndex()\n if (undoing.current) {\n undoing.current = false\n position.current = next\n if (leaveAfterUndo.current !== undefined) window.history.go(leaveAfterUndo.current)\n leaveAfterUndo.current = undefined\n return\n }\n const delta = next - position.current\n if (!proceeding.current && guards.current.size > 0 && leavesPage(current.current.url, browserUrl(), guards.current.values())) {\n // The browser has already moved; step back to where the person was and ask.\n undoing.current = true\n window.history.go(-delta)\n setPending({ kind: 'history', delta, inputLost: losesInput() })\n return\n }\n proceeding.current = false\n position.current = next\n rememberScroll()\n setPage({ url: browserUrl(), entry: historyEntry() })\n }\n window.addEventListener('popstate', onPop)\n return () => {\n window.removeEventListener('popstate', onPop)\n window.removeEventListener('pagehide', persist)\n document.removeEventListener('visibilitychange', hidden)\n }\n }, [memory, rememberScroll, places])\n\n const go = useCallback(\n (full: string, replace: boolean, keepScroll = false) => {\n const entry = replace ? current.current.entry : newEntry()\n if (!memory) {\n position.current += replace ? 0 : 1\n const previous = replace ? historyState().protobasePrevious : current.current.url\n window.history[replace ? 'replaceState' : 'pushState']({ protobaseIndex: position.current, protobaseEntry: entry, protobasePrevious: previous }, '', full)\n }\n rememberScroll()\n if (keepScroll) places.save(entry, window.scrollY)\n setPage({ url: full, entry })\n },\n [memory, rememberScroll, places],\n )\n\n const navigate = useCallback(\n (to: string, options?: NavigateOptions) => {\n const link = pendingLink(`${basePath}${to}`, options)\n if (guards.current.size > 0 && leavesPage(current.current.url, link.full, guards.current.values())) return setPending({ ...link, inputLost: losesInput() })\n followLink(link, go)\n },\n [basePath, go],\n )\n\n const back = useCallback(\n (to: string) => {\n const previous = memory ? undefined : historyState().protobasePrevious\n if (previous !== undefined && pathOf(previous) === pathOf(`${basePath}${to}`)) return window.history.back()\n navigate(to)\n },\n [memory, basePath, navigate],\n )\n\n const registerGuard = useCallback((kind: GuardKind = 'draft-kept', params: readonly string[] = []) => {\n const token = Symbol('guard')\n guards.current.set(token, { kind, params })\n return () => void guards.current.delete(token)\n }, [])\n\n const reload = useCallback(() => {\n if (guards.current.size > 0) return setPending({ kind: 'reload', inputLost: losesInput() })\n window.location.reload()\n }, [])\n\n const reloadConfirmed = useCallback(() => reloading.current, [])\n const holdsChanges = useCallback(() => guards.current.size > 0, [])\n\n const leave = () => {\n if (!pending) return\n setPending(undefined)\n if (pending.kind === 'link') return followLink(pending, go)\n if (pending.kind === 'reload') {\n reloading.current = true\n return window.location.reload()\n }\n proceeding.current = true\n if (undoing.current) leaveAfterUndo.current = pending.delta\n else window.history.go(pending.delta)\n }\n\n const value = useMemo<RouterValue>(() => {\n const parsed = new URL(page.url, 'http://local')\n const path = parsed.pathname.slice(basePath.length) || '/'\n return {\n path,\n params: parsed.searchParams,\n basePath,\n entry: page.entry,\n navigate,\n back,\n registerGuard,\n reload,\n reloadConfirmed,\n holdsChanges,\n }\n }, [page, basePath, navigate, back, registerGuard, reload, reloadConfirmed, holdsChanges])\n\n return (\n <RouterContext.Provider value={value}>\n {children}\n {pending?.kind === 'reload' && (\n <Dialog\n title={appText('reloadTitle')}\n description={appText(pending.inputLost ? 'reloadInputLost' : 'reloadDraftKept')}\n onClose={() => setPending(undefined)}\n actions={\n <>\n <Button onClick={() => setPending(undefined)}>{appText('keepEditing')}</Button>\n <Button variant=\"primary\" onClick={leave}>\n {appText('reload')}\n </Button>\n </>\n }\n />\n )}\n {pending && pending.kind !== 'reload' && (\n <Dialog\n title={appText('leaveTitle')}\n description={appText(pending.inputLost ? 'leaveInputLost' : 'leaveDescription')}\n onClose={() => setPending(undefined)}\n actions={\n <>\n <Button onClick={() => setPending(undefined)}>{appText('stay')}</Button>\n <Button variant=\"primary\" onClick={leave}>\n {appText('leave')}\n </Button>\n </>\n }\n />\n )}\n </RouterContext.Provider>\n )\n}\n\n/** A link to a path below the base path, as `appPath` writes it, that the router follows without reloading the page. */\nexport const Link = ({ to, replace, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string; replace?: boolean }) => {\n const { navigate, basePath } = useRouter()\n return <RouteLink to={{ href: `${basePath}${to}`, onFollow: () => navigate(to, { replace }) }} {...rest} />\n}\n\n/**\n * While `active`, leaving the page asks first (in-app links, a reload and closing the tab), and so does changing a page\n * parameter whose content it sits in (`GuardedParams`).\n */\nexport const useNavigationGuard = (active: boolean, kind: GuardKind = 'draft-kept') => {\n const { registerGuard, reloadConfirmed } = useRouter()\n const params = useGuardedParams()\n useEffect(() => (active ? registerGuard(kind, params) : undefined), [active, kind, params, registerGuard])\n useEffect(() => {\n if (!active) return\n const warn = (event: BeforeUnloadEvent) => {\n if (!reloadConfirmed()) event.preventDefault()\n }\n window.addEventListener('beforeunload', warn)\n return () => window.removeEventListener('beforeunload', warn)\n }, [active, reloadConfirmed])\n}\n","import { encodeKey } from './keys'\nimport type { AppAddress, CalendarView, FilterLayout, MapView, TimelineView } from './model'\n\n/**\n * The words of the app's addresses. Only `appPath` and `readAppPath` write and read them, so the shape of an address\n * changes in this module alone.\n */\nexport const addressWords = {\n /** A named list of the resource (`.namedList(...)`), in place of its own list. */\n list: 'list',\n /** A list's filter (AIP-160), as the list API takes it. An empty `filter=` means no filter, in place of the view's default. */\n filter: 'filter',\n /** A list's order (AIP-132). */\n orderBy: 'order_by',\n /** The list display shown, when it is not the view's default. */\n display: 'display',\n /** Where a list's filters sit: `bar` (the default) or `panel`. */\n filterLayout: 'layout',\n /** Where a list's map display looks: `latitude,longitude,zoom`. */\n map: 'map',\n /** The month or week a list's calendar display shows: `month,YYYY-MM-DD` or `week,YYYY-MM-DD`. */\n calendar: 'calendar',\n /** The period a list's timeline display shows: `week,YYYY-MM-DD`, `month,YYYY-MM-DD` or `quarter,YYYY-MM-DD`. */\n timeline: 'timeline',\n /** The saved search a list was opened from, by its key. */\n savedSearch: 'saved_search',\n /** The second path segment that opens a resource's create form instead of a record. */\n create: 'new',\n /** A record's form, `edit=true`, on a view whose record page opens as a read view or locked. */\n edit: 'edit',\n /** A record page's open collapsed group, by title, once per group. */\n open: 'open',\n /** A record page's shown tab, by title. */\n tab: 'tab',\n /** A record's standard page, `standard=true`, on a view whose record page is a component of the app's own. */\n standard: 'standard',\n /** A record page that joins the record's call, `call=join`, as a ring's Accept and a call mark's Join open it. */\n call: 'call',\n /** A record's earlier saved version shown read-only, by number, as a field type that keeps versions draws it. */\n version: 'version',\n /** The run a workflow's page shows on its graph, by its key. */\n run: 'run',\n /** The panel a focus page opens with, by a name its surface knows. */\n panel: 'panel',\n /** A record's file field opened in the viewer for its media type, by field name. */\n file: 'file',\n} as const\n\nconst listWords = ['list', 'display', 'filter', 'orderBy', 'filterLayout', 'savedSearch'] as const\n\n// Five decimals of a degree are about a metre; two of a zoom are less than a pixel's difference.\nconst mapText = (view: MapView) => `${view.latitude.toFixed(5)},${view.longitude.toFixed(5)},${view.zoom.toFixed(2)}`\n\nconst inRange = (value: number, limit: number, low = -limit) => Number.isFinite(value) && value >= low && value <= limit\n\n// A map view as `mapText` writes it, or none for anything else\nconst readMap = (text: string | null): MapView | undefined => {\n const parts = text?.split(',')\n if (parts?.length !== 3 || parts.some((part) => part.trim() === '')) return undefined\n const [latitude, longitude, zoom] = parts.map(Number) as [number, number, number]\n return inRange(latitude, 90) && inRange(longitude, 180) && inRange(zoom, 22, 0) ? { latitude, longitude, zoom } : undefined\n}\n\nconst periodText = (view: CalendarView | TimelineView) => `${view.scale},${view.day}`\n\n// A real day as `YYYY-MM-DD`: one whose parts come back from `Date.UTC`, so 2026-02-30 is none\nconst isDay = (text: string) => {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return false\n const [year, month, day] = match.slice(1).map(Number) as [number, number, number]\n const date = new Date(Date.UTC(year, month - 1, day))\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n}\n\n// A period of one of `scales` as `periodText` writes it, or none for anything else\nconst readPeriod = <S extends string>(text: string | null, scales: readonly S[]): { scale: S; day: string } | undefined => {\n const parts = text?.split(',')\n if (parts?.length !== 2) return undefined\n const [scale, day] = parts as [S, string]\n return scales.includes(scale) && isDay(day) ? { scale, day } : undefined\n}\n\nconst listQuery = (address: Extract<AppAddress, { kind: 'list' }>) => {\n const query = new URLSearchParams()\n for (const name of listWords) {\n const value = address[name]\n if (value === undefined || (value === '' && name !== 'filter')) continue\n query.set(addressWords[name], value)\n }\n if (address.map) query.set(addressWords.map, mapText(address.map))\n if (address.calendar) query.set(addressWords.calendar, periodText(address.calendar))\n if (address.timeline) query.set(addressWords.timeline, periodText(address.timeline))\n const text = query.toString()\n return text ? `?${text}` : ''\n}\n\nconst recordQuery = (address: Extract<AppAddress, { kind: 'record' }>) => {\n const query = new URLSearchParams()\n if (address.edit) query.set(addressWords.edit, 'true')\n for (const title of address.open ?? []) query.append(addressWords.open, title)\n if (address.tab) query.set(addressWords.tab, address.tab)\n if (address.standard) query.set(addressWords.standard, 'true')\n if (address.call) query.set(addressWords.call, address.call)\n if (address.version !== undefined) query.set(addressWords.version, String(address.version))\n if (address.run) query.set(addressWords.run, address.run)\n if (address.panel) query.set(addressWords.panel, address.panel)\n if (address.file) query.set(addressWords.file, address.file)\n const text = query.toString()\n return text ? `?${text}` : ''\n}\n\n/** The path of `address` below `basePath` (such as `/admin`), every name and key encoded the one way the app reads them. */\nexport const appPath = (address: AppAddress, basePath = ''): string => {\n switch (address.kind) {\n case 'page':\n return `${basePath}/${encodeURIComponent(address.page)}${address.tab ? `/${encodeURIComponent(address.tab)}` : ''}${valuesQuery(address.params)}`\n case 'create':\n return `${basePath}/${encodeURIComponent(address.resource)}/${addressWords.create}${valuesQuery(address.values)}`\n case 'record':\n return `${basePath}/${encodeURIComponent(address.resource)}/${encodeURIComponent(encodeKey(address.key))}${recordQuery(address)}`\n case 'list':\n return `${basePath}/${encodeURIComponent(address.resource)}${listQuery(address)}`\n }\n}\n\nconst decodeSegments = (pathname: string) => {\n try {\n return pathname.split('/').filter(Boolean).map(decodeURIComponent)\n } catch (error) {\n if (error instanceof URIError) return undefined\n throw error\n }\n}\n\n// A create form's values, by field name, or a page's parameters, as the query.\nconst valuesQuery = (values: Readonly<Record<string, string>> = {}) => {\n const text = new URLSearchParams(Object.entries(values).filter(([, value]) => value !== '')).toString()\n return text ? `?${text}` : ''\n}\n\n// A version's number: a whole number from 1, or none for anything else\nconst readVersion = (text: string | null) => (text !== null && /^[1-9]\\d{0,8}$/.test(text) ? Number(text) : undefined)\n\nconst filterLayout = (value: string | null): FilterLayout | undefined => (value === 'bar' || value === 'panel' ? value : undefined)\n\n/**\n * The address `pathAndQuery` (below the base path) shows, or `undefined` for anything else: the root, the app's own\n * pages under `/-/`, or a path that is not one. A first segment in `pages` is a composed page, and a second one its\n * tab; otherwise it is a resource.\n */\nexport const readAppPath = (pathAndQuery: string, pages: ReadonlySet<string>): AppAddress | undefined => {\n const url = new URL(pathAndQuery, 'http://app')\n const segments = decodeSegments(url.pathname)\n if (!segments || segments.length === 0 || segments.length > 2) return undefined\n const [first, second] = segments as [string, string | undefined]\n if (first === '-') return undefined\n if (pages.has(first)) {\n // A page's query is its parameters alone, whatever their names, as its own SelectInputs name them\n const params = Object.fromEntries([...url.searchParams].filter(([, value]) => value !== ''))\n return { kind: 'page', page: first, ...(second !== undefined && { tab: second }), ...(Object.keys(params).length > 0 && { params }) }\n }\n if (second === addressWords.create) {\n const values = Object.fromEntries([...url.searchParams].filter(([, value]) => value !== ''))\n return { kind: 'create', resource: first, ...(Object.keys(values).length > 0 && { values }) }\n }\n if (second !== undefined) {\n const open = [...new Set(url.searchParams.getAll(addressWords.open).filter((title) => title !== ''))]\n const tab = url.searchParams.get(addressWords.tab) || undefined\n const standard = url.searchParams.get(addressWords.standard) === 'true'\n const call = url.searchParams.get(addressWords.call) === 'join'\n const version = readVersion(url.searchParams.get(addressWords.version))\n const run = url.searchParams.get(addressWords.run) || undefined\n const panel = url.searchParams.get(addressWords.panel) || undefined\n const file = url.searchParams.get(addressWords.file) || undefined\n return {\n kind: 'record',\n resource: first,\n key: second,\n ...(url.searchParams.get(addressWords.edit) === 'true' && { edit: true }),\n ...(open.length > 0 && { open }),\n ...(tab && { tab }),\n ...(standard && { standard }),\n ...(call && { call: 'join' as const }),\n ...(version !== undefined && { version }),\n ...(run && { run }),\n ...(panel && { panel }),\n ...(file && { file }),\n }\n }\n const params = url.searchParams\n const list = params.get(addressWords.list) || undefined\n const display = params.get(addressWords.display) || undefined\n const filter = params.get(addressWords.filter) ?? undefined\n const orderBy = params.get(addressWords.orderBy) || undefined\n const layout = filterLayout(params.get(addressWords.filterLayout))\n const map = readMap(params.get(addressWords.map))\n const calendar = readPeriod(params.get(addressWords.calendar), ['month', 'week'] as const)\n const timeline = readPeriod(params.get(addressWords.timeline), ['week', 'month', 'quarter'] as const)\n const savedSearch = params.get(addressWords.savedSearch) || undefined\n return {\n kind: 'list',\n resource: first,\n ...(list && { list }),\n ...(display && { display }),\n ...(filter !== undefined && { filter }),\n ...(orderBy && { orderBy }),\n ...(layout && { filterLayout: layout }),\n ...(map && { map }),\n ...(calendar && { calendar }),\n ...(timeline && { timeline }),\n ...(savedSearch && { savedSearch }),\n }\n}\n","import type { Client } from './client'\nimport type { ResourceRef } from './types'\n\nconst nameOf = (resource: ResourceRef) => (typeof resource === 'string' ? resource : resource.toModel().name)\n\n/**\n * One client over the app's own API and the sources it draws resources from: a call about a resource goes to the API\n * that serves it (`sourceOf` gives a source's client, or `undefined` for the app's own), and `meta`, `invoke`, the\n * public forms, `live`, the bridges and the user's devices, notifications and status go to the app's own. A batch goes to the one API all its writes are for; one that writes to two cannot be atomic, so it is\n * refused before anything is sent.\n */\nexport const routedClient = (own: Client, sourceOf: (resource: string) => Client | undefined): Client => {\n const to = (resource: ResourceRef) => sourceOf(nameOf(resource)) ?? own\n return {\n list: (resource, params) => to(resource).list(resource, params),\n search: (resource, params) => to(resource).search(resource, params),\n get: (resource, key) => to(resource).get(resource, key),\n create: (resource, body) => to(resource).create(resource, body),\n update: (resource, key, patch, etag) => to(resource).update(resource, key, patch, etag),\n remove: (resource, key, options) => to(resource).remove(resource, key, options),\n undelete: (resource, key) => to(resource).undelete(resource, key),\n generate: (resource, key, action) => to(resource).generate(resource, key, action),\n reveal: (resource, key, field) => to(resource).reveal(resource, key, field),\n history: (resource, key, options) => to(resource).history(resource, key, options),\n comments: (resource, key, options) => to(resource).comments(resource, key, options),\n comment: (resource, key, input) => to(resource).comment(resource, key, input),\n mentionable: (resource, key, query) => to(resource).mentionable(resource, key, query),\n batchWrite: (ops) => {\n const apis = [...new Set(ops.map((op) => to(op.resource)))]\n if (apis.length > 1) return Promise.reject(new Error(`A batch writes to one API, but these writes are for ${[...new Set(ops.map((op) => nameOf(op.resource)))].join(', ')}, which different APIs serve`))\n return (apis[0] ?? own).batchWrite(ops)\n },\n facets: (resource, field, options) => to(resource).facets(resource, field, options),\n aggregate: (resource, params) => to(resource).aggregate(resource, params),\n series: (resource, params) => to(resource).series(resource, params),\n histogram: (resource, field, options) => to(resource).histogram(resource, field, options),\n map: (resource, params) => to(resource).map(resource, params),\n seek: (resource, params) => to(resource).seek(resource, params),\n meta: (etag, options) => own.meta(etag, options),\n fileReadUrl: (resource, file) => to(resource).fileReadUrl(resource, file),\n invoke: (name, options) => own.invoke(name, options),\n upload: (resource, field, file, options) => to(resource).upload(resource, field, file, options),\n form: (name) => own.form(name),\n formChallenge: (name) => own.formChallenge(name),\n submitForm: (name, values, proof) => own.submitForm(name, values, proof),\n live: (handlers) => own.live(handlers),\n channel: (resource, key) => own.channel(resource, key),\n bridges: own.bridges,\n devices: own.devices,\n notifications: own.notifications,\n status: own.status,\n rings: own.rings,\n callGuests: own.callGuests,\n calls: (resource, key) => to(resource).calls(resource, key),\n watchCalls: (resource, key, handlers) => to(resource).watchCalls(resource, key, handlers),\n // The types are those of the API that serves the workflows\n workflowTypes: () => to('workflows').workflowTypes(),\n workflowRunTrace: (runId, held) => to('workflow_runs').workflowRunTrace(runId, held),\n runnerRegistration: (runner) => to('workflow_runners').runnerRegistration(runner),\n }\n}\n","// The recorders a typed layout is written with: `data.title` and `resources.tasks.count` are not values but records of\n// what the layout reads, which turn into today's `{{title}}` placeholders and AIP-160 text when the layout is built.\n\nconst recorded = Symbol('recorded')\n\n// A recorded path names the record it was read from by the child function that was given it, its scope, `0` for the\n// layout's own data. Which `../` or `@root` reaches that record depends on the records around the place it ends up,\n// which JSX builds inner elements first and so knows only once the whole tree is built: a path is written as a marker\n// of its scope, `{{~3~title}}`, and a condition's field as `~~3~status~~`, which `resolveScopes` rewrites.\n\n/** The scopes of the child functions running now, innermost last. */\nconst scopes: number[] = []\nlet lastScope = 0\n/** How many layouts are being built now, inside which a record block's child function may run. */\nlet building = 0\n\n/** Runs `build` as a typed layout builds, so its record blocks may take functions of their records. */\nexport const whileBuilding = <T>(build: () => T): T => {\n building += 1\n try {\n return build()\n } finally {\n building -= 1\n }\n}\n\n/** Runs `build` in a new scope, a record block's child function's, and gives the scope with what it built. */\nexport const inScope = <T>(build: (scope: number) => T): { scope: number; built: T } => {\n if (building === 0) throw new Error(\"A record block's children are a function of its record only inside a typed layout: layout(), recordLayout() or defineTemplate()\")\n lastScope += 1\n const scope = lastScope\n scopes.push(scope)\n try {\n return { scope, built: build(scope) }\n } finally {\n scopes.pop()\n }\n}\n\n/** The elements whose children a child function built, by its scope. */\nconst scopeOf = new WeakMap<object, number>()\n\n/** Notes that `node`'s children were built by the child function of `scope`. */\nexport const markScope = (node: object, scope: number) => {\n scopeOf.set(node, scope)\n}\n\n/** Gives `copy` the scope `node` was marked with, as an element held in a prop is copied into the tree. */\nexport const keepScope = (node: object, copy: object) => {\n const scope = scopeOf.get(node)\n if (scope !== undefined) scopeOf.set(copy, scope)\n}\n\ntype PathInfo = { path: string[]; scope: number }\n\n/** A filter value: written as it is in AIP-160 text. */\ntype Literal = string | number | boolean | null | Date\n\nconst durationPattern = /^\\d+[smhdw]$/\n\n/** A time relative to when the filter is read: `now()`, `now().plus('7d')`, `now().minus('1d')`. */\nexport class Now {\n constructor(readonly offset?: { sign: '+' | '-'; duration: string }) {}\n /** That long after now: `'7d'`, `'12h'`, `'30m'`, `'2w'`. */\n plus(duration: string) {\n return new Now({ sign: '+', duration: checkDuration(duration) })\n }\n /** That long before now. */\n minus(duration: string) {\n return new Now({ sign: '-', duration: checkDuration(duration) })\n }\n toString() {\n return this.offset ? `now() ${this.offset.sign} ${this.offset.duration}` : 'now()'\n }\n}\n\nconst checkDuration = (duration: string) => {\n if (!durationPattern.test(duration)) throw new Error(`\"${duration}\" is not a duration: write a number and s, m, h, d or w, such as '7d'`)\n return duration\n}\n\n/** The time a filter is read, which `plus` and `minus` move: `f.next_run_at.lt(now().plus('7d'))`. */\nexport const now = () => new Now()\n\n/** A condition: a filter of a block's records, or the `when` of a `Show`, written as AIP-160 text. */\nexport class Condition {\n /** @internal */\n constructor(\n /** @internal */\n readonly text: string,\n /** @internal */\n readonly op: 'and' | 'or' | 'term',\n ) {}\n /** Both hold: `a.and(b)`, written `a AND b`. */\n and(other: Condition) {\n return join('and', this, other)\n }\n /** Either holds: `a.or(b)`, written `a OR b`. */\n or(other: Condition) {\n return join('or', this, other)\n }\n toString() {\n return this.text\n }\n}\n\n// One AND or OR of two conditions, flattening a chain of the same operator and bracketing any other compound, as\n// AIP-160 binds OR closer than AND, which a reader does not expect\nconst join = (op: 'and' | 'or', left: Condition, right: Condition) => {\n const side = (part: Condition) => (part.op === 'term' || part.op === op ? part.text : `(${part.text})`)\n return new Condition(`${side(left)} ${op.toUpperCase()} ${side(right)}`, op)\n}\n\n/** The condition does not hold: `not(f.archived.eq(true))`, written `NOT (archived = true)`. */\nexport const not = (condition: Condition) => new Condition(`NOT ${condition.op === 'term' ? condition.text : `(${condition.text})`}`, 'term')\n\n/** Whether a value is a recorded path, such as `data.id`. */\nexport const isRecorded = (value: unknown): value is { [recorded]: PathInfo } => (typeof value === 'object' || typeof value === 'function') && value !== null && recorded in value\n\n/** The `{{…}}` placeholder of a recorded path, marked with its scope until `resolveScopes` writes where it reads from. */\nexport const placeholder = (value: { [recorded]: PathInfo }) => `{{~${value[recorded].scope}~${value[recorded].path.join('.')}}}`\n\n// A condition's field of a recorded record, marked with its scope as a placeholder is\nconst member = ({ path, scope }: PathInfo) => `~~${scope}~${path.join('.')}~~`\n\nconst valueMarker = /\\{\\{~(\\d+)~([^{}~]*)\\}\\}/g\nconst memberMarker = /~~(\\d+)~([^~]*)~~/g\n\n// The path a marked one is where `frames` are the scopes of the records around it, outermost first: by its name in\n// the nearest record, `@root` the layout's own data, `../` a record further out\nconst pathAt = (scope: number, path: string, frames: readonly (number | undefined)[]) => {\n const name = path === '' ? 'this' : path\n if (scope === 0) return frames.length === 0 ? name : path === '' ? '@root' : `@root.${path}`\n const at = frames.lastIndexOf(scope)\n if (at < 0) throw new Error(`\"${name}\" of a record is used outside the record block whose function gave it`)\n const up = frames.length - 1 - at\n return up === 0 ? name : `${'../'.repeat(up)}${name}`\n}\n\n// A condition names fields of the nearest record only\nconst memberAt = (scope: number, path: string, frames: readonly (number | undefined)[]) => {\n if ((scope === 0 && frames.length === 0) || (scope !== 0 && frames.at(-1) === scope)) return path\n throw new Error(`A condition compares \"${path}\" of a record further out than the nearest one around it, which a condition cannot name: compare it outside the inner record block, or in a filter`)\n}\n\nconst resolveText = (text: string, frames: readonly (number | undefined)[]) =>\n text.includes('~') ? text.replace(valueMarker, (_, scope: string, path: string) => `{{${pathAt(Number(scope), path, frames)}}}`).replace(memberMarker, (_, scope: string, path: string) => memberAt(Number(scope), path, frames)) : text\n\ntype Node = { type: string; props: Record<string, unknown>; children: unknown[]; fallback?: unknown[]; custom?: boolean }\n\nconst isNode = (value: unknown): value is Node => typeof value === 'object' && value !== null && !Array.isArray(value) && typeof (value as Node).type === 'string' && Array.isArray((value as Node).children)\n\n/** How an element places what it holds: the scope its children and its element props draw in, given its own. */\nexport type ScopeStep<S> = (node: Node, scope: S) => { children: S; slots: S; depth: (scope: S) => number }\n\n/**\n * The tree with every marked path written as it reads where it ends up, by the records around it: `step` gives the\n * scope an element's children and element props draw in, and how many records deep a scope is.\n */\nexport const resolveScopes = <T extends Node, S>(tree: T, start: S, step: ScopeStep<S>): T => {\n const visit = (node: Node, scope: S, frames: readonly (number | undefined)[]): Node => {\n const { children: inner, slots, depth } = step(node, scope)\n // A scope one record deeper than the element's own holds the record its child function gave, if it had one\n const framed = (next: S) => (depth(next) > depth(scope) ? [...frames, scopeOf.get(node)] : frames)\n const innerFrames = framed(inner)\n const slotFrames = framed(slots)\n const value = (item: unknown): unknown => {\n if (typeof item === 'string') return resolveText(item, frames)\n if (isNode(item)) return visit(item, slots, slotFrames)\n if (Array.isArray(item)) return item.map(value)\n if (typeof item === 'object' && item !== null) return Object.fromEntries(Object.entries(item).map(([key, entry]) => [key, value(entry)]))\n return item\n }\n const child = (at: S, atFrames: readonly (number | undefined)[]) => (entry: unknown) => (typeof entry === 'string' ? resolveText(entry, atFrames) : isNode(entry) ? visit(entry, at, atFrames) : entry)\n return {\n ...node,\n props: Object.fromEntries(Object.entries(node.props).map(([key, entry]) => [key, value(entry)])),\n children: node.children.map(child(inner, innerFrames)),\n ...(node.fallback && { fallback: node.fallback.map(child(scope, frames)) }),\n }\n }\n return visit(tree, start, []) as T\n}\n\n// A value in AIP-160: text quoted as JSON writes it, a recorded path as its placeholder, which the client fills as a\n// literal, and a time relative to now as written\nconst valueText = (value: unknown): string => {\n if (isRecorded(value)) return placeholder(value)\n if (value instanceof Now) return value.toString()\n if (value instanceof Date) return JSON.stringify(value.toISOString())\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean' || value === null) return String(value)\n throw new Error(`${String(value)} cannot be a filter value: compare with text, a number, true or false, null, now() or a recorded field`)\n}\n\nconst term = (text: string) => new Condition(text, 'term')\n\n/** What a field or a recorded path can be compared with. */\nconst comparisons = (name: string) => ({\n eq: (value: unknown) => term(value === null ? `isNull(${name})` : `${name} = ${valueText(value)}`),\n ne: (value: unknown) => term(value === null ? `NOT isNull(${name})` : `${name} != ${valueText(value)}`),\n lt: (value: unknown) => term(`${name} < ${valueText(value)}`),\n le: (value: unknown) => term(`${name} <= ${valueText(value)}`),\n gt: (value: unknown) => term(`${name} > ${valueText(value)}`),\n ge: (value: unknown) => term(`${name} >= ${valueText(value)}`),\n in: (values: readonly unknown[]) => term(`in(${name}, ${values.map(valueText).join(', ')})`),\n contains: (value: unknown) => term(`${name}:${valueText(value)}`),\n isNull: () => term(`isNull(${name})`),\n})\n\nconst comparisonNames = new Set(Object.keys(comparisons('')))\n\n/**\n * A recorder of the values in scope: each property read is a path, `data.plan.name`, which is its `{{plan.name}}`\n * placeholder where it ends up as text, and compares like a field in a condition, `data.status.eq('done')`.\n */\nexport const recorder = (path: string[] = [], scope = scopes.at(-1) ?? 0): unknown =>\n new Proxy({}, {\n get: (_, key) => {\n if (key === recorded) return { path, scope }\n if (key === Symbol.toPrimitive || key === 'toString' || key === 'toJSON') return () => placeholder({ [recorded]: { path, scope } })\n if (typeof key === 'symbol') return undefined\n if (comparisonNames.has(key)) return comparisons(member({ path, scope }))[key as keyof ReturnType<typeof comparisons>]\n return recorder([...path, key], scope)\n },\n has: (_, key) => key === recorded,\n })\n\n/** The fields of a resource as a filter's arrow is given them: `(f) => f.enabled.eq(true)`. A relation's field is `f.plan.name`. */\nexport const fieldRecorder = (path: string[] = []): unknown =>\n new Proxy(\n {},\n {\n get: (_, key) => {\n if (typeof key === 'symbol') return undefined\n if (comparisonNames.has(key) && path.length > 0) return comparisons(path.join('.'))[key as keyof ReturnType<typeof comparisons>]\n return fieldRecorder([...path, key])\n },\n },\n )\n\n/** The page's tables, each counted where a condition reads it: `resources.loop_held.count.gt(0)`, written `loop_held.count > 0`. */\nexport const resourcesRecorder = (): unknown =>\n new Proxy(\n {},\n {\n get: (_, name) => (typeof name === 'symbol' ? undefined : { count: comparisons(`${name}.count`) }),\n },\n )\n","import { isLayoutNode, type Block, type ComponentReads, type LayoutChild, type LayoutNode, type LayoutValue } from './node'\nimport { Condition, Now, fieldRecorder, inScope, isRecorded, keepScope, markScope, placeholder, recorder } from './typed/record'\n\nconst advice = 'Layouts are static data, sent to the browser as JSON: use <Action name=\"...\"> for behaviour, or register a custom component for React code.'\n\nconst describe = (value: unknown) => {\n if (typeof value === 'function') return 'a function'\n if (typeof value === 'number') return String(value)\n if (typeof value !== 'object' || value === null) return `a ${typeof value}`\n return `a ${value.constructor?.name ?? 'object without prototype'}`\n}\n\nconst isPlainObject = (value: object) => {\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/** Throws unless `value` is JSON-safe data: strings, finite numbers, booleans, null, arrays and plain objects of those. */\nexport const staticValue = (value: unknown, where: string): LayoutValue => {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n // What a typed layout records: a path read is its placeholder, a condition or a time its AIP-160 text\n if (isRecorded(value)) return placeholder(value)\n if (value instanceof Condition || value instanceof Now) return value.toString()\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (Array.isArray(value)) return value.map((item, index) => staticValue(item, `${where.slice(0, -1)}[${index}]>`))\n if (typeof value === 'object' && isPlainObject(value)) {\n const copy = Object.fromEntries(Object.entries(value).flatMap(([key, item]) => (item === undefined ? [] : [[key, staticValue(item, `${where.slice(0, -1)}.${key}>`)]])))\n // An element in a prop keeps the records its child function gave, which its paths are written by\n keepScope(value, copy)\n return copy\n }\n throw new Error(`${where} is ${describe(value)}. ${advice}`)\n}\n\n/** Flattens arrays and fragments, drops `null`, `undefined` and booleans, and turns numbers into text, like React. */\nexport const normalizeChildren = (children: unknown, where: string): LayoutChild[] => {\n if (children === undefined || children === null || typeof children === 'boolean') return []\n if (typeof children === 'string') return [children]\n if (isRecorded(children)) return [placeholder(children)]\n if (typeof children === 'number' && Number.isFinite(children)) return [String(children)]\n if (Array.isArray(children)) return children.flatMap((child) => normalizeChildren(child, where))\n if (isLayoutNode(children)) return children.type === fragmentName && !children.custom ? children.children : [children]\n throw new Error(`${where} has a child that is ${describe(children)}. ${advice}`)\n}\n\nexport const fragmentName = 'Fragment'\n\nconst isBlock = (type: unknown): type is Block<unknown> => typeof type === 'function' && typeof (type as Block<unknown>).blockName === 'string'\n\n/** The blocks that draw their children inside a record of their own, whose children may be a function of that record. */\nexport const recordChildBlocks = ['RecordCard', 'CardRow', 'ReferenceField', 'RecordsIterator']\n\n/** The props that are a condition on a block's own records, which a typed layout writes as an arrow of their fields. */\nconst conditionArrows = ['filter', 'edgeFilter', 'animated', 'dashed', 'dotted']\n\n// A typed layout's props as the static tree holds them: a filter's or condition's arrow called with the resource's\n// fields, and a sort's entries as one AIP-132 text\nconst builtProps = (name: string, props: Record<string, unknown>) => {\n const built = { ...props }\n for (const prop of conditionArrows) {\n const value = built[prop]\n if (typeof value === 'function') {\n const condition = (value as (fields: unknown) => unknown)(fieldRecorder())\n if (!(condition instanceof Condition)) throw new Error(`<${name} ${prop}> is an arrow that gives no condition: write (f) => f.status.eq('open'), or the ${prop} as AIP-160 text`)\n built[prop] = condition.text\n } else if (typeof value === 'object' && value !== null && !(value instanceof Condition)) {\n throw new Error(`<${name} ${prop}> is an object: write the ${prop} as an arrow, (f) => f.status.eq('open'), or as AIP-160 text`)\n }\n }\n if (built.sort !== undefined) {\n if (!Array.isArray(built.sort) || !built.sort.every((entry) => typeof entry === 'string')) throw new Error(`<${name} sort> takes a list of fields, each with asc or desc if it likes: sort={['next_run_at asc']}`)\n built.sort = built.sort.join(', ')\n }\n return built\n}\n\n// A record block's children: a function of its record, called once with a recorder of a scope of its own, which the\n// element is marked with, or the elements\nconst builtChildren = (name: string, children: unknown, where: string): { children: LayoutChild[]; scope?: number } => {\n if (typeof children !== 'function') return { children: normalizeChildren(children, where) }\n if (!recordChildBlocks.includes(name)) throw new Error(`<${name}> takes elements as children; only ${recordChildBlocks.join(', ')} take a function of their record`)\n const { scope, built } = inScope((own) => normalizeChildren((children as (record: unknown) => unknown)(recorder([], own)), where))\n return { children: built, scope }\n}\n\n/** The blocks with a prop of elements drawn once per record of their own, which may be a function of that record. */\nexport const recordPropBlocks: Readonly<Record<string, string>> = { Graph: 'node' }\n\n/** The built-in blocks that take a `fallback`, drawn where they cannot draw, which the element holds as a component's. */\nexport const fallbackBlocks: ReadonlySet<string> = new Set(['Graph'])\n\n// A prop of elements drawn once per record, a function of it called as a record block's children are: stored as one\n// element, itself or a Box around several, with the scope of the function that built it\nconst builtRecordProp = (name: string, prop: string, value: unknown): { value: unknown; scope?: number } => {\n const where = `<${name} ${prop}>`\n const one = (children: LayoutChild[]): LayoutNode => {\n const [only] = children\n return children.length === 1 && typeof only === 'object' ? only : { type: 'Box', props: {}, children }\n }\n if (typeof value !== 'function') return { value: value === undefined || isLayoutNode(value) ? value : one(normalizeChildren(value, where)) }\n const { scope, built } = inScope((own) => normalizeChildren((value as (record: unknown) => unknown)(recorder([], own)), where))\n return { value: one(built), scope }\n}\n\n/** The element for `<type {...props} />`: checks that every prop and child is static and returns plain data. */\nexport const createNode = (type: unknown, props: Record<string, unknown>): LayoutNode => {\n if (typeof type === 'string') throw new Error(`<${type}> is an HTML element, not a layout block: use the blocks from @protobase/layout or a custom component`)\n if (!isBlock(type)) {\n throw new Error(`<${typeof type === 'function' && type.name ? type.name : 'unknown'}> is not a layout block. Components in a layout are declared with component('Name') and implemented in the app; ${advice}`)\n }\n const name = type.blockName\n const { children, ...written } = props\n // A built-in block's fallback is the element's, as a component's is\n const ownFallback = !type.custom && fallbackBlocks.has(name)\n const { fallback, ...taken } = written\n const given = ownFallback ? taken : written\n const rest = type.custom ? given : builtProps(name, given)\n const recordProp = type.custom ? undefined : recordPropBlocks[name]\n const perRecord = recordProp === undefined ? undefined : builtRecordProp(name, recordProp, rest[recordProp])\n if (recordProp !== undefined) rest[recordProp] = perRecord!.value\n const built = type.custom ? { children: normalizeChildren(children, `<${name}>`) } : builtChildren(name, children, `<${name}>`)\n const node: LayoutNode = {\n type: name,\n props: Object.fromEntries(Object.entries(rest).flatMap(([key, value]) => (value === undefined ? [] : [[key, staticValue(value, `<${name} ${key}>`)]]))),\n children: built.children,\n }\n // One element holds the records of one function: its children's, or else its prop's\n const scope = built.scope ?? perRecord?.scope\n if (scope !== undefined) markScope(node, scope)\n if (type.custom) node.custom = true\n if (type.fallback) node.fallback = type.fallback\n if (ownFallback && fallback !== undefined) node.fallback = normalizeChildren(fallback, `<${name} fallback>`)\n if (type.reads) node.reads = type.reads\n return node\n}\n\n/**\n * Declares a block named `name`; `custom` marks a component the app implements in React, drawn as `fallback` where it\n * cannot be, and reading what `reads` names.\n */\nexport const defineBlock = <P>(name: string, custom: boolean, fallback?: LayoutChild[], reads?: ComponentReads): Block<P> => {\n const block: Block<P> = Object.assign((props: P) => createNode(block, props as Record<string, unknown>), { blockName: name, custom, ...(fallback && { fallback }), ...(reads && { reads }) })\n return block\n}\n","import type { FieldModel, ResourceModel } from '@protobase/schema'\n\n/** One step of a field path: the field, and the resource it belongs to. */\nexport type PathStep = { model: ResourceModel; field: FieldModel }\n\nexport type PathResolution = { ok: true; steps: PathStep[] } | { ok: false; message: string }\n\n/**\n * Resolves `plan.name` from `resource`: every name but the last must be a relation, and each next name a field of the\n * resource that relation points at. A missing resource or field is reported as unknown, never as hidden.\n */\nexport const resolveFieldPath = (models: Record<string, ResourceModel>, resource: string, path: string): PathResolution => {\n const steps: PathStep[] = []\n let model = models[resource]\n const names = path.split('.')\n for (const [index, name] of names.entries()) {\n if (!model) return { ok: false, message: `unknown resource \"${resource}\"` }\n const field = Object.hasOwn(model.fields, name) ? model.fields[name] : undefined\n if (!field) return { ok: false, message: `unknown field \"${names.slice(0, index + 1).join('.')}\" on ${model.name}` }\n steps.push({ model, field })\n if (index === names.length - 1) break\n if (field.type !== 'relation' || !field.relation) return { ok: false, message: `\"${names.slice(0, index + 1).join('.')}\" is not a relation, so \"${path}\" cannot go through it` }\n resource = field.relation.resource\n model = models[resource]\n }\n return { ok: true, steps }\n}\n","import { IntlMessageFormat } from 'intl-messageformat'\nimport { defineBlock } from './create-node'\nimport { isLayoutNode, type LayoutChild, type LayoutNode, type LayoutValue } from './node'\nimport type { Recorded, Register } from './typed/types'\n\n// The app's own texts in each of its languages, as ICU messages (the syntax `intl-messageformat` reads), and the\n// <Trans> element that shows one by its key, as react-i18next's <Trans i18nKey values components /> does.\n\n/** A language's texts as written: keys nested as deep as one likes, each message ICU text. */\nexport type TextTree = { readonly [key: string]: string | TextTree }\n\n/** The dotted keys of a tree of texts: `{ today: { title: '…' } }` has `today.title`. */\nexport type TextKeys<T> = { [K in keyof T & string]: T[K] extends string ? K : `${K}.${TextKeys<T[K]>}` }[keyof T & string]\n\n/** The app's texts in each of its languages, flattened by key, as `translations({ en, nl })` makes them. */\nexport type Translations<Keys extends string = string> = {\n readonly kind: 'translations'\n /** Each language's messages by dotted key; every language has every key. */\n readonly languages: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** The keys, for the compiler only; never set. */\n readonly $keys?: Keys\n}\n\nconst flatten = (tree: TextTree, at = ''): [string, string][] =>\n Object.entries(tree).flatMap(([key, value]) => (typeof value === 'string' ? [[`${at}${key}`, value] as [string, string]] : flatten(value, `${at}${key}.`)))\n\n/**\n * The app's texts in each of its languages, from one JSON file per language: `translations({ en, nl })`, exported from\n * `config/index.ts`. Every message must parse as ICU, every language must have the same keys, and each language must\n * be a BCP 47 tag, such as `en`, `nl` or `pt-BR`.\n */\nexport const translations = <const L extends Record<string, TextTree>>(languages: L): Translations<TextKeys<L[keyof L]>> => {\n const tags = Object.keys(languages)\n if (tags.length === 0) throw new Error('translations() takes at least one language, such as translations({ en })')\n const flat = Object.fromEntries(tags.map((tag) => [tag, Object.fromEntries(flatten(languages[tag]!))]))\n const problems: string[] = []\n for (const tag of tags) {\n try {\n Intl.getCanonicalLocales(tag)\n } catch {\n problems.push(`\"${tag}\" is not a language tag, such as en, nl or pt-BR`)\n continue\n }\n for (const [key, message] of Object.entries(flat[tag]!)) {\n try {\n new IntlMessageFormat(message, tag)\n } catch (error) {\n problems.push(`${tag}: \"${key}\" is not an ICU message: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n }\n const keys = new Set(tags.flatMap((tag) => Object.keys(flat[tag]!)))\n for (const tag of tags) {\n const missing = [...keys].filter((key) => !Object.hasOwn(flat[tag]!, key))\n if (missing.length > 0) problems.push(`${tag} lacks ${missing.map((key) => `\"${key}\"`).join(', ')}, which ${tags.filter((other) => other !== tag && missing.some((key) => Object.hasOwn(flat[other]!, key))).join(', ')} has`)\n }\n if (problems.length > 0) throw new Error(`The app's translations are not usable: ${problems.join('; ')}`)\n return { kind: 'translations', languages: flat }\n}\n\nexport const isTranslations = (value: unknown): value is Translations =>\n typeof value === 'object' && value !== null && (value as Translations).kind === 'translations' && typeof (value as Translations).languages === 'object'\n\n// The node types of a parsed ICU message (@formatjs/icu-messageformat-parser's TYPE), by what the checks read of them\nconst argumentTypes = new Set([1, 2, 3, 4, 5, 6])\nconst tagType = 8\ntype MessageElement = { type: number; value?: string; options?: Record<string, { value: MessageElement[] }>; children?: MessageElement[] }\n\nconst walk = (elements: readonly MessageElement[], found: { values: Set<string>; tags: Set<string> }) => {\n for (const element of elements) {\n if (argumentTypes.has(element.type) && element.value !== undefined) found.values.add(element.value)\n if (element.type === tagType && element.value !== undefined) found.tags.add(element.value)\n for (const option of Object.values(element.options ?? {})) walk(option.value, found)\n if (element.children) walk(element.children, found)\n }\n}\n\n/** The values a message formats (`{name}`, `{count, plural, …}`) and the tags it holds (`<b>…</b>`). */\nexport const messageParts = (message: string, language: string) => {\n const found = { values: new Set<string>(), tags: new Set<string>() }\n walk(new IntlMessageFormat(message, language).getAst() as unknown as MessageElement[], found)\n return { values: [...found.values], tags: [...found.tags] }\n}\n\n/** The texts a reader gets: their language and the messages by key, of the keys what they see uses. */\nexport type ReaderTexts = { locale: string; messages: Readonly<Record<string, string>> }\n\nconst compiled = new Map<string, IntlMessageFormat>()\n\n/**\n * A message formatted in the reader's language with `values`, or its key when the texts lack it, which the startup\n * check makes impossible in a valid app. Tags format through `tags`, each given the formatted text inside it.\n */\nexport const formatMessage = <T = string>(texts: ReaderTexts | undefined, key: string, values: Record<string, unknown> = {}, tags: Record<string, (chunks: unknown[]) => T> = {}): string | (string | T)[] => {\n const message = texts?.messages[key]\n if (message === undefined || !texts) return key\n const id = `${texts.locale}\\u0000${message}`\n let format = compiled.get(id)\n if (!format) {\n format = new IntlMessageFormat(message, texts.locale)\n compiled.set(id, format)\n }\n return format.format({ ...values, ...tags }) as string | (string | T)[]\n}\n\n/** A message as plain text: its tags' text kept, the tags themselves left out. */\nexport const formatText = (texts: ReaderTexts | undefined, key: string, values: Record<string, unknown> = {}) => {\n const tags = Object.fromEntries((texts?.messages[key] ? messageParts(texts.messages[key], texts.locale).tags : []).map((tag) => [tag, (chunks: unknown[]) => chunks.join('')]))\n const formatted = formatMessage(texts, key, values, tags)\n return Array.isArray(formatted) ? formatted.join('') : formatted\n}\n\ntype AppTexts = Register extends { app: infer A extends object } ? { [K in keyof A]: A[K] extends Translations<infer Keys> ? Keys : never }[keyof A] : never\n\n/** The keys of the app's texts, or any key without the generated types. */\nexport type TransKey = [AppTexts] extends [never] ? string : AppTexts\n\n/** A value a message formats: one of its own, or a recorded path of a typed layout, `data.title`. */\ntype TransValue = string | number | boolean | null | Recorded<unknown>\n\n/**\n * A text in the reader's language, by its key, as react-i18next's `<Trans i18nKey values components />`: ICU text\n * whose `{name}` takes `values.name`, here a value or a recorded path such as `data.title`, and whose tags, `<b>…</b>`,\n * draw as `components.b`. It goes where text goes, a child or a prop such as a `title`, `label` or `empty`.\n */\nexport const Trans = defineBlock<{ i18nKey: TransKey; values?: Record<string, TransValue>; components?: Record<string, LayoutNode> }>('Trans', false)\n\n/** Whether a value is a `<Trans>` element. */\nexport const isTrans = (value: LayoutValue | LayoutChild | undefined): value is LayoutNode => isLayoutNode(value) && value.type === 'Trans' && !value.custom\n\n/** Every key a tree's `<Trans>` elements name, in its children and its props. */\nexport const transKeys = (node: LayoutNode): string[] => {\n const own = isTrans(node) && typeof node.props.i18nKey === 'string' ? [node.props.i18nKey] : []\n const inProps = Object.values(node.props).flatMap((value) => (isLayoutNode(value) ? transKeys(value) : Array.isArray(value) ? value.flatMap((item) => (isLayoutNode(item) ? transKeys(item) : [])) : isObject(value) ? Object.values(value).flatMap((item) => (isLayoutNode(item) ? transKeys(item) : [])) : []))\n const inChildren = node.children.flatMap((child) => (typeof child === 'string' ? [] : transKeys(child)))\n return [...new Set([...own, ...inProps, ...inChildren, ...(node.fallback ?? []).flatMap((child) => (typeof child === 'string' ? [] : transKeys(child)))])]\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The language a reader gets of `languages`, the app's translations: the app's own when it sets one, else the first of\n * the reader's own (`Accept-Language`) the app has, by its full tag or its language, else the first the app has.\n */\nexport const readerLanguage = (languages: readonly string[], preferred: readonly string[], fixed?: string): string | undefined => {\n if (languages.length === 0) return\n if (fixed && languages.includes(fixed)) return fixed\n for (const tag of preferred) {\n const exact = languages.find((language) => language.toLowerCase() === tag.toLowerCase())\n if (exact) return exact\n const base = tag.split('-')[0]!.toLowerCase()\n const near = languages.find((language) => language.split('-')[0]!.toLowerCase() === base)\n if (near) return near\n }\n return languages.includes('en') ? 'en' : languages[0]\n}\n\n// Every <Trans> element of a tree, in its props and its children\nconst transNodes = (node: LayoutNode): LayoutNode[] => {\n const inValue = (value: unknown): LayoutNode[] =>\n isLayoutNode(value) ? transNodes(value) : Array.isArray(value) ? value.flatMap(inValue) : isObject(value) ? Object.values(value).flatMap(inValue) : []\n const children = [...node.children, ...(node.fallback ?? [])].flatMap((child) => (typeof child === 'string' ? [] : transNodes(child)))\n return [...(isTrans(node) ? [node] : []), ...Object.values(node.props).flatMap(inValue), ...children]\n}\n\n/**\n * What the `<Trans>` elements of the app's trees, by where each sits, ask that its translations lack: a key no language\n * has, a value its message formats in some language that the element does not give, or a tag with no component.\n */\nexport const translationProblems = (trees: readonly { at: string; tree: LayoutNode }[], given: Translations | undefined): string[] =>\n trees.flatMap(({ at, tree }) =>\n transNodes(tree).flatMap((node) => {\n const key = String(node.props.i18nKey)\n if (!given) return [`${at}: <Trans i18nKey=\"${key}\"> needs the app's texts: export translations({ en, ... }) from the config`]\n const languages = Object.entries(given.languages)\n if (!languages.some(([, messages]) => Object.hasOwn(messages, key))) return [`${at}: <Trans i18nKey=\"${key}\">: no language has \"${key}\"`]\n const values = new Set(Object.keys(isObject(node.props.values) ? node.props.values : {}))\n const components = new Set(Object.keys(isObject(node.props.components) ? node.props.components : {}))\n const parts = languages.map(([language, messages]) => messageParts(messages[key]!, language))\n const missing = [...new Set(parts.flatMap((part) => part.values))].filter((name) => !values.has(name))\n const untagged = [...new Set(parts.flatMap((part) => part.tags))].filter((name) => !components.has(name))\n return [\n ...(missing.length > 0 ? [`${at}: <Trans i18nKey=\"${key}\"> formats ${missing.map((name) => `{${name}}`).join(', ')}; give it in values`] : []),\n ...(untagged.length > 0 ? [`${at}: <Trans i18nKey=\"${key}\"> has the tag${untagged.length > 1 ? 's' : ''} ${untagged.map((name) => `<${name}>`).join(', ')}; give each an element in components`] : []),\n ]\n }),\n )\n","import { resolveFieldPath } from '@protobase/layout'\nimport type { ActionModel, FieldModel, GroupItemModel, LayoutItemModel, ResourceModel, TabItemModel, ViewModel } from '@protobase/schema'\nimport { addressErrors, followableRowButton } from '@protobase/schema/internal'\nimport type { Meta, ResourcePermissions, SourceRef } from './types'\n\n/** What the app draws of a source: the resources it lists that the user may see there, their views and what the user may do. */\nexport type SourceMeta = { resources: ResourceModel[]; views: ViewModel[]; permissions: Record<string, ResourcePermissions> }\n\n// A relation to a resource the app does not draw from the source shows its key: the app has no such resource, or one of\n// its own by that name, which is another resource.\nconst withinSource = (model: ResourceModel, drawn: Record<string, ResourceModel>): ResourceModel => ({\n ...model,\n fields: Object.fromEntries(\n Object.entries(model.fields).map(([name, field]): [string, FieldModel] => {\n if (!field.relation || Object.hasOwn(drawn, field.relation.resource)) return [name, field]\n const { relation: _outside, ...plain } = field\n return [name, plain]\n }),\n ),\n})\n\n// Related records of a resource the app does not draw go, and so do columns that go through a relation out of the source\n// and a row button's choices that lead out of it.\nconst keptLayoutItem = (item: LayoutItemModel, models: Record<string, ResourceModel>): LayoutItemModel[] => {\n if (item.kind === 'group') {\n const items = item.items.flatMap((inner) => keptLayoutItem(inner, models)) as GroupItemModel[]\n return items.length > 0 ? [{ ...item, items }] : []\n }\n if (item.kind === 'tab') {\n const items = item.items.flatMap((inner) => keptLayoutItem(inner, models)) as TabItemModel[]\n return items.length > 0 ? [{ ...item, items }] : []\n }\n if (item.kind !== 'related') return [item]\n if (!Object.hasOwn(models, item.resource) || (item.through && !Object.hasOwn(models, item.through.resource))) return []\n const { columns, button, ...rest } = item\n const kept = columns?.filter((column) => resolveFieldPath(models, item.resource, column).ok)\n const narrowed = kept && kept.length > 0 ? { ...rest, columns: kept } : rest\n const followable = button === undefined ? undefined : followableRowButton(button, models[item.resource]!, { models, pages: new Set() })\n return [followable === undefined ? narrowed : { ...narrowed, button: followable }]\n}\n\n// A link to an address in the app goes when it leads out of the source: to a page, or to a resource the app does not draw.\nconst keptAction = (action: ActionModel, model: ResourceModel, models: Record<string, ResourceModel>) =>\n action.run?.kind !== 'link' || !('to' in action.run) || addressErrors(action.run.to, { models, pages: new Set(), source: model }).length === 0\n\nconst withinSourceView = (view: ViewModel, models: Record<string, ResourceModel>): ViewModel => ({\n ...view,\n layout: view.layout.flatMap((item) => keptLayoutItem(item, models)),\n actions: view.actions.filter((action) => keptAction(action, models[view.resource]!, models)),\n})\n\n/**\n * The part of a source's `/meta` the app draws: the resources `source` lists, of those the source names to the user,\n * with their views and permissions. Nothing in them leads out of the source: a relation to a resource the app does not\n * draw from it shows its key, and related records of one, columns through one and links to one or to a page go.\n */\nexport const sourceMeta = (meta: Meta, source: SourceRef): SourceMeta => {\n const listed = meta.resources.filter((model) => source.resources.includes(model.name))\n const models: Record<string, ResourceModel> = Object.fromEntries(listed.map((model) => [model.name, model]))\n const resources = listed.map((model) => withinSource(model, models))\n const scoped = Object.fromEntries(resources.map((model) => [model.name, model]))\n const views = meta.views.filter((view) => Object.hasOwn(scoped, view.resource)).map((view) => withinSourceView(view, scoped))\n const permissions = Object.fromEntries(listed.flatMap((model) => (meta.permissions?.[model.name] ? [[model.name, meta.permissions[model.name]!]] : [])))\n return { resources, views, permissions }\n}\n","import type { MapLayerModel, PluginRef, ResourcePermissions, SourceRef } from '@protobase/client'\nimport type { PageModel } from '@protobase/layout'\nimport type { BottomBarModel, ResourceModel, SignInViewModel, UserMenuModel, ViewModel } from '@protobase/schema'\nimport type { Locale } from '@protobase/schema/internal'\n\nexport type MetaData = {\n etag: string\n /** The app's name, which ends the tab titles. */\n appName: string\n /** The Protobase version the server ran when this `/meta` was read. */\n protobaseVersion?: string\n /**\n * Set once the server runs another Protobase version than the page started with: `to` is that version, when the server\n * names one. The page keeps this `/meta` and stops reading it until it is reloaded (see `keepOnVersionChange`).\n */\n versionChange?: { to?: string }\n /** The path of the app's own icon, when the project has one, which the sidebar's logo draws. */\n appIcon?: string\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n /** Composed pages by name. */\n pages: Record<string, PageModel>\n /** The signed-in user's account page, at `/-/account` (see `AccountPage`). */\n account?: PageModel\n permissions: Record<string, ResourcePermissions>\n userMenu?: UserMenuModel\n /** For a visitor, the resources they could use once signed in, by name, with what to tell them (see `SignInPrompt`). */\n signIn?: Record<string, SignInViewModel>\n /** The tabs of the user's bottom bar on phones, when one names their active role. */\n bottomBar?: Omit<BottomBarModel, 'roles'>\n /** The assistant backend, when the app has one and the user has the admin or ai role. */\n assistant?: { url: string }\n /** The runtime updates endpoint, when the app has one and the user has the admin role. */\n runtime?: { url: string }\n /** The error tracker the app sends its errors to, when the app reports them (see `startErrorReporting`). */\n errorReporting?: { dsn: string; environment?: string }\n /** The map style the app's maps are drawn with, and the layers they may switch to, when the app has one (see `MapSection`). */\n maps?: { style: string; layers?: MapLayerModel[] }\n /** Whether the top bar draws the notification bell: the app has notifications and their `ui` is not false (see `ShellBell`). */\n bell?: boolean\n /** Whether people set their own status and see those they share an organization with (see `useStatuses`). */\n status?: boolean\n /** Whether the app has calls, which ring people on any page they have open (see `CallRings`). */\n calls?: boolean\n /** The language the app's screens are in for everyone, when it sets one (see `AppLocale`). */\n locale?: Locale\n /** The app's own texts in the user's language, the messages their pages' `<Trans>` elements name (see `AppTexts`). */\n texts?: { locale: string; messages: Record<string, string> }\n /** The hosts besides the app's own whose images are drawn with the page's referrer (see `FileImage`). */\n files?: { trustedHosts: string[] }\n /** The plugins the app loads for the user (see `PluginGate`). */\n plugins?: PluginRef[]\n /** The other APIs the app draws resources from for the user, and how far their `/meta` has loaded (see `withSources`). */\n sources?: SourceStatus[]\n}\n\n/**\n * A source of resources and its `/meta`: `ready` once its resources are among the app's, `error` when it could not be\n * read, the reason in `error`.\n */\nexport type SourceStatus = { source: SourceRef; state: 'loading' | 'ready' } | { source: SourceRef; state: 'error'; error: Error }\n\nexport const allowEverything: ResourcePermissions = { create: true, update: true, delete: true, conditional: [] }\n","import { useQueries, useQueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport { useMemo } from 'react'\nimport { sourceMeta, type Client, type SourceMeta, type SourceRef } from '@protobase/client'\nimport { keys } from './query-keys'\n\n/** A source's `/meta` as far as it has loaded: the part the app draws once it is `ready`. */\nexport type SourceResult = { source: SourceRef; state: 'loading' } | { source: SourceRef; state: 'ready'; meta: SourceMeta } | { source: SourceRef; state: 'error'; error: Error }\n\ntype Loaded = { etag: string; meta: SourceMeta }\n\n/** How long the app waits for a source's `/meta` before it shows the source's resources as unavailable. */\nexport const sourceTimeoutMs = 10_000\n\n// The combined results keep their identity while nothing changes, so what is merged from them does too.\nconst combine = (results: UseQueryResult<Loaded>[]) => results.map((result) => ({ data: result.data?.meta, error: result.error }))\n\n/**\n * Each source's `/meta`, read with the user's token from that API and scoped to the resources the app draws from it\n * (`sourceMeta`). Like the app's own, it is read again on window focus with `If-None-Match`, and a source that cannot be\n * read is an `error` without holding up the others or the app.\n */\nexport const useSourceMetas = (sources: readonly SourceRef[], clientOf: (source: SourceRef) => Client): SourceResult[] => {\n const queryClient = useQueryClient()\n const results = useQueries({\n queries: sources.map((source) => {\n const queryKey = keys.sourceMeta(source.url, source.resources)\n return {\n queryKey,\n staleTime: 0,\n refetchOnWindowFocus: 'always' as const,\n queryFn: async (): Promise<Loaded> => {\n const previous = queryClient.getQueryData<Loaded>(queryKey)\n const result = await clientOf(source).meta(previous?.etag, { signal: AbortSignal.timeout(sourceTimeoutMs) })\n if (result.status === 'unchanged') {\n if (!previous) throw new Error(`${source.label} answered 304 to a request without If-None-Match`)\n return previous\n }\n return { etag: result.etag, meta: sourceMeta(result.meta, source) }\n },\n }\n }),\n combine,\n })\n // A source read before keeps its resources when a later read fails, as the app's own `/meta` does.\n return useMemo(\n () =>\n sources.map((source, index): SourceResult => {\n const { data, error } = results[index]!\n if (data) return { source, state: 'ready', meta: data }\n if (error) return { source, state: 'error', error }\n return { source, state: 'loading' }\n }),\n [sources, results],\n )\n}\n","import type { MetaData, SourceStatus } from './meta-data'\nimport type { SourceResult } from './use-source-metas'\n\n/**\n * The app's `/meta` with the resources it draws from its sources: those of every source that is ready, with their views\n * and permissions, as if they were the app's own, and how far each source has loaded in `sources`. A source that is\n * loading or cannot be read adds no resources; the app shows its resources as unavailable (see `sourceStatusOf`).\n */\nexport const withSources = (meta: MetaData, results: readonly SourceResult[]): MetaData => {\n if (results.length === 0) return meta\n const ready = results.flatMap((result) => (result.state === 'ready' ? [result.meta] : []))\n const sources = results.map((result): SourceStatus => (result.state === 'error' ? { source: result.source, state: 'error', error: result.error } : { source: result.source, state: result.state }))\n return {\n ...meta,\n resources: { ...meta.resources, ...Object.fromEntries(ready.flatMap((part) => part.resources.map((model) => [model.name, model]))) },\n views: { ...meta.views, ...Object.fromEntries(ready.flatMap((part) => part.views.map((view) => [view.resource, view]))) },\n permissions: { ...meta.permissions, ...Object.assign({}, ...ready.map((part) => part.permissions)) },\n sources,\n }\n}\n\n/** The source the app draws `resource` from, with how far it has loaded; `undefined` for a resource of the app's own. */\nexport const sourceStatusOf = (meta: MetaData, resource: string) => meta.sources?.find((status) => status.source.resources.includes(resource))\n","import { Fragment, useEffect, type ReactNode } from 'react'\nimport type { Locale } from '@protobase/schema/internal'\nimport { activeLocale, setAppLocale } from './active-locale'\n\n/**\n * Puts the screens below in the language the app sets for everyone, from its `/meta`, or in the fallback when it sets\n * none; draws them anew when that changes, and tells the page which language it is in.\n */\nexport const AppLocale = ({ locale, children }: { locale: Locale | undefined; children: ReactNode }) => {\n setAppLocale(locale)\n const active = activeLocale()\n useEffect(() => {\n document.documentElement.lang = active\n }, [active])\n return <Fragment key={active}>{children}</Fragment>\n}\n","import { formatText, isTrans, type LayoutNode, type LayoutValue, type ReaderTexts } from '@protobase/layout'\nimport { createContext, useContext } from 'react'\n\n// The app's own texts in the user's language, from `/meta`, which a page's `<Trans>` elements format.\n\nexport const AppTexts = createContext<ReaderTexts | undefined>(undefined)\n\nexport const useAppTexts = () => useContext(AppTexts)\n\nconst isObject = (value: unknown): value is Record<string, LayoutValue> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A `<Trans>` as plain text in the user's language: what a prop drawn as text, a `title` or a `label`, shows. */\nexport const transText = (node: LayoutNode, texts: ReaderTexts | undefined) => formatText(texts, String(node.props.i18nKey), isObject(node.props.values) ? node.props.values : {})\n\nconst ownPropTexts = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutNode =>\n node.custom || !Object.values(node.props).some(isTrans) ? node : { ...node, props: Object.fromEntries(Object.entries(node.props).map(([name, value]) => [name, isTrans(value) ? transText(value, texts) : value])) }\n\n/**\n * The element with each `<Trans>` in its props as its text, so a block draws its `title` or `empty` as any text; a\n * `Tabs`' tabs' labels too, which it reads to draw its tab bar before each `Tab` draws.\n */\nexport const withPropTexts = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutNode => {\n const own = ownPropTexts(node, texts)\n if (node.custom || node.type !== 'Tabs') return own\n const children = own.children.map((child) => (typeof child === 'string' ? child : ownPropTexts(child, texts)))\n return children.some((child, index) => child !== own.children[index]) ? { ...own, children } : own\n}\n","import type { ActionModel, FieldViewModel, LayoutItemModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { MetaData } from '../../data/meta-data'\nimport { catalogues, messages } from '../../locale/messages'\n\nconst namespace = 'app/built-in-views'\nconst text = messages(namespace)\ntype Id = Parameters<typeof text>[0]\n\n// The English catalogue names every text there is; the view's own text stays where it names none.\nconst translated = (id: string, given: string) => (Object.hasOwn(catalogues.en[namespace], id) ? text(id as Id) : given)\n\nconst field = (prefix: string, hints: FieldViewModel): FieldViewModel => ({\n ...hints,\n ...(hints.label !== undefined && { label: translated(`${prefix}.label`, hints.label) }),\n ...(hints.help !== undefined && { help: translated(`${prefix}.help`, hints.help) }),\n ...(hints.valueLabels && { valueLabels: Object.fromEntries(Object.entries(hints.valueLabels).map(([value, label]) => [value, translated(`${prefix}.values.${value}`, label)])) }),\n})\n\n// A top-level item's title, help and empty text, by its place in the layout.\nconst item = (prefix: string, shown: LayoutItemModel): LayoutItemModel => {\n const texts = shown as { title?: string; help?: string; empty?: string }\n return {\n ...shown,\n ...(texts.title !== undefined && { title: translated(`${prefix}.title`, texts.title) }),\n ...(texts.help !== undefined && { help: translated(`${prefix}.help`, texts.help) }),\n ...(texts.empty !== undefined && { empty: translated(`${prefix}.empty`, texts.empty) }),\n } as LayoutItemModel\n}\n\n// Activity's table sits in the events schema the app picks, `changes` unless it renames it, so it is keyed as `changes.history`.\nconst tableKey = (model: ResourceModel) =>\n model.name === 'record_history' && model.table.name === 'history' ? 'changes.history' : `${model.table.schema ?? 'public'}.${model.table.name}`\n\nconst action = (prefix: string, shown: ActionModel): ActionModel => ({\n ...shown,\n label: translated(`${prefix}.label`, shown.label),\n ...(shown.confirm !== undefined && { confirm: translated(`${prefix}.confirm`, shown.confirm) }),\n})\n\n/**\n * A built-in view with its texts in the active locale, from the `app/built-in-views` catalogue: its names, help, field\n * labels, help and value labels, the titles, help and empty texts of its top-level layout items, and its actions'\n * labels and questions, each keyed by the table of its resource and where the text sits, such as\n * `table_definitions.fields.fields.type.values.long_text`, so an app's own resource of the same name keeps its texts.\n * A text the catalogue does not name stays as `/meta` gives it.\n */\nexport const translatedView = (view: ViewModel, model: ResourceModel | undefined): ViewModel => {\n if (!model) return view\n const at = tableKey(model)\n return {\n ...view,\n ...(view.names && { names: { singular: translated(`${at}.names.singular`, view.names.singular), plural: translated(`${at}.names.plural`, view.names.plural) } }),\n ...(view.help !== undefined && { help: translated(`${at}.help`, view.help) }),\n fields: Object.fromEntries(Object.entries(view.fields).map(([name, hints]) => [name, field(`${at}.fields.${name}`, hints)])),\n layout: view.layout.map((shown, index) => item(`${at}.layout.${index}`, shown)),\n actions: view.actions.map((shown) => action(`${at}.actions.${shown.name}`, shown)),\n }\n}\n\n/** `/meta` with the texts of the built-in views the catalogue translates in the active locale (see `translatedView`). */\nexport const withTranslatedViews = (meta: MetaData): MetaData => ({ ...meta, views: Object.fromEntries(Object.entries(meta.views).map(([name, view]) => [name, translatedView(view, meta.resources[view.resource])])) })\n","import { createContext, useContext, useEffect, type ReactNode } from 'react'\n\n/** Keeps the launch splash up while a loading screen draws, and hides it once, when none does. */\nexport type SplashHold = {\n /** Holds the splash until the returned function releases it. */\n hold: () => () => void\n /** Marks the app as drawn: the splash hides as soon as nothing holds it. */\n start: () => void\n}\n\n/**\n * The hold on the launch splash: `hide` runs once, after `start`, as soon as no loading screen holds it. A screen that\n * replaces another in the same render holds it before the check, since the check waits for the end of that render's\n * effects, so the splash stays up from the auth check through `/meta` to the plugins without a gap.\n */\nexport const createSplashHold = (hide: () => void): SplashHold => {\n let holds = 0\n let started = false\n let hidden = false\n const settle = () =>\n queueMicrotask(() => {\n if (!started || hidden || holds > 0) return\n hidden = true\n hide()\n })\n return {\n hold: () => {\n holds += 1\n let released = false\n return () => {\n if (released) return\n released = true\n holds -= 1\n settle()\n }\n },\n start: () => {\n started = true\n settle()\n },\n }\n}\n\nconst SplashHoldContext = createContext<SplashHold | undefined>(undefined)\n\nexport const SplashHoldProvider = ({ value, children }: { value: SplashHold; children: ReactNode }) => <SplashHoldContext.Provider value={value}>{children}</SplashHoldContext.Provider>\n\n/** Drawn by a loading screen: holds the launch splash while it shows. Nothing outside a `SplashHoldProvider`. */\nexport const HoldSplash = () => {\n const splash = useContext(SplashHoldContext)\n useEffect(() => splash?.hold(), [splash])\n return null\n}\n","import { messages } from '../locale/messages'\n\nexport const text = messages('app/meta-gate')\n","import { useContext, useMemo, type ReactNode } from 'react'\nimport { isApiError, routedClient } from '@protobase/client'\nimport { ClientProvider, useClient, useSourceClients } from '../data/api-provider'\nimport { MetaContext } from '../data/meta-context'\nimport { allowEverything, type MetaData } from '../data/meta-data'\nimport { useMeta } from '../data/use-meta'\nimport { useSourceMetas } from '../data/use-source-metas'\nimport { withSources } from '../data/with-sources'\nimport { AppLocale } from '../locale/app-locale'\nimport { AppTexts } from './pages/app-texts'\nimport { cn } from '../lib/cn'\nimport { revealLate } from '../primitives/skeleton'\nimport { Spinner } from '../primitives/spinner'\nimport { withTranslatedViews } from './built-in-views/translated-views'\nimport { HoldSplash } from './splash-hold'\nimport { text } from './meta-gate-messages'\n\nexport const useAdminMeta = () => {\n const meta = useContext(MetaContext)\n if (!meta) throw new Error('useAdminMeta must be used inside MetaGate')\n return meta\n}\n\nconst Notice = ({ title, children }: { title: string; children: ReactNode }) => (\n <div className=\"flex h-full min-h-48 flex-1 items-center justify-center p-8\">\n <div className=\"max-w-md text-center\">\n <h1 className=\"text-base font-semibold\">{title}</h1>\n <p className=\"mt-1 text-muted-foreground\">{children}</p>\n </div>\n </div>\n)\n\n/**\n * Draws the resources of the app's sources as its own: reads each source's `/meta`, merges what is ready into the app's,\n * translates the texts of the built-in views into the app's language (see `withTranslatedViews`), and gives what is below a client that sends each resource's calls to the API that serves it. The app does not wait\n * for a source; its resources join when it has loaded.\n */\nconst WithSources = ({ meta, children }: { meta: MetaData; children: ReactNode }) => {\n const own = useClient()\n const clientOf = useSourceClients()\n const declared = useMemo(() => (meta.sources ?? []).map((status) => status.source), [meta.sources])\n const results = useSourceMetas(declared, clientOf)\n const merged = useMemo(() => withSources(meta, results), [meta, results])\n const routing = useMemo(() => {\n const byResource = new Map(declared.flatMap((source) => source.resources.map((resource) => [resource, source] as const)))\n const resourceClient = (resource: string) => {\n const source = byResource.get(resource)\n return source && clientOf(source)\n }\n return { client: routedClient(own, resourceClient), resourceClient }\n }, [declared, own, clientOf])\n return (\n <ClientProvider client={routing.client} resourceClient={routing.resourceClient}>\n <AppLocale locale={meta.locale}>\n <AppTexts.Provider value={meta.texts}>\n <TranslatedMeta meta={merged}>{children}</TranslatedMeta>\n </AppTexts.Provider>\n </AppLocale>\n </ClientProvider>\n )\n}\n\n// Below `AppLocale`, which draws it anew when the language changes, so the built-in views read the language it sets.\nconst TranslatedMeta = ({ meta, children }: { meta: MetaData; children: ReactNode }) => {\n // `[meta]` is enough: `AppLocale` renders its children under `key={active}`, so a language switch remounts this\n // component and the memo runs again in the new language.\n const translated = useMemo(() => withTranslatedViews(meta), [meta])\n return <MetaContext.Provider value={translated}>{children}</MetaContext.Provider>\n}\n\n/**\n * Renders its children once `/meta` has loaded, with the resources of the app's sources as they load. The sources'\n * layer is always there, also without sources, so `/meta` gaining or losing them never draws the app anew.\n */\nexport const MetaGate = ({ children }: { children: ReactNode }) => {\n const meta = useMeta()\n if (meta.isPending) {\n return (\n <div className={cn('flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground', revealLate)}>\n <HoldSplash />\n <Spinner /> {text('loading')}\n </div>\n )\n }\n if (meta.error) {\n return <Notice title={text('cannotReach')}>{isApiError(meta.error) ? meta.error.message : text('noAnswer')}</Notice>\n }\n return <WithSources meta={meta.data}>{children}</WithSources>\n}\n\nexport { Notice }\n\n/** What the signed-in user may do with a resource; everything when the server does not say. */\nexport const usePermissions = (resource: string) => useAdminMeta().permissions[resource] ?? allowEverything\n","import { useSyncExternalStore } from 'react'\n\n/** Follows a CSS media query, for layout decisions that cannot be made with classes alone. */\nexport const useMediaQuery = (query: string) =>\n useSyncExternalStore(\n (onChange) => {\n const list = window.matchMedia(query)\n list.addEventListener('change', onChange)\n return () => list.removeEventListener('change', onChange)\n },\n () => window.matchMedia(query).matches,\n () => false,\n )\n\n/** The `md` breakpoint: where the sidebar stops being a drawer and tables stop squeezing. */\nexport const useIsDesktop = () => useMediaQuery('(min-width: 768px)')\n\n/** Below the `sm` breakpoint: a phone, where a list opens in its cards display. */\nexport const useIsXs = () => useMediaQuery('not all and (min-width: 640px)')\n","import type { CardPhotosModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RecordPhotos } from '@protobase/client'\n\n/** Where a loaded row keeps its photos, beside its fields, as it keeps its `id`. */\nexport const photosKey = '$photos'\n\n/** The photos a list's rows load with: those its cards displays name, which the server checks they all share. */\nexport const listPhotos = (view: ViewModel | undefined): CardPhotosModel | undefined => {\n for (const display of view?.list?.displays ?? []) if (display.kind === 'cards' && display.photos) return display.photos\n return undefined\n}\n\n/** The rows, each with its record's photos from a list call's `photos`, when the call asked for them; none for a record it left out. */\nexport const withPhotos = (model: ResourceModel, rows: Array<Record<string, unknown>>, photos: RecordPhotos | undefined) => {\n if (photos === undefined || model.primaryKey.length !== 1) return rows\n const key = model.primaryKey[0]!\n return rows.map((row) => ({ ...row, [photosKey]: photos[String(row[key])] ?? [] }))\n}\n","/** The fields of `names` with a value in `record`: an empty one, null or an empty text, is left out, never shown as `—`. */\nexport const filledFields = (record: Record<string, unknown>, names: readonly string[]) => names.filter((name) => record[name] !== null && record[name] !== undefined && record[name] !== '')\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/displays')\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { enumLabel, printFilter, where } from '@protobase/schema'\nimport { isApiError } from '@protobase/client'\nimport { recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { text } from './messages'\n\nexport type BoardDisplayModel = Extract<ListDisplayModel, { kind: 'board' }>\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\n/** One column of a board: the value its records have, `null` for those without one, and its heading. */\nexport type BoardColumn = { value: string | null; label: string }\n\n/**\n * A board's columns: one per value of its enum field, in the order the field lists them, headed by the view's value\n * label; then, when the field may be empty, one for the records without a value.\n */\nexport const boardColumns = (model: ResourceModel, view: ViewModel | undefined, display: BoardDisplayModel): BoardColumn[] => {\n const field = model.fields[display.by]\n if (!field) return []\n const hints = view?.fields[display.by]\n const values = (field.enumValues ?? []).map((value) => ({ value, label: enumLabel(value, hints?.valueLabels) }))\n if (!field.nullable) return values\n return [...values, { value: null, label: text('noValue', { label: hints?.label ?? humanize(display.by) }) }]\n}\n\n/** The field a board orders each column by: the resource's `.position()`, when its records are ordered as one rather than within a parent. */\nexport const boardRank = (model: ResourceModel) => (model.position && model.position.within === undefined ? model.position.field : undefined)\n\n/** The list's filter, its search included, narrowed to the records of one column. */\nexport const columnFilter = (filter: string, by: string, value: string | null) => {\n const column = printFilter(value === null ? where.isNull(by) : where.eq(by, value))\n return filter === '' ? column : `(${filter}) AND ${column}`\n}\n\n/** The built-in card a board draws for each record: that of a cards display of the board's fields. */\nexport const boardCard = (model: ResourceModel, view: ViewModel | undefined, display: BoardDisplayModel): CardsDisplayModel => ({\n kind: 'cards',\n name: display.name,\n title: display.title ?? recordTitleField(model, view),\n ...(display.subtitle !== undefined && { subtitle: display.subtitle }),\n ...(display.badge !== undefined && { badge: display.badge }),\n ...(display.meta && { meta: display.meta }),\n})\n\n/** Why the server refused a move: the reasons it gives per field, such as a `validate` message, else its detail. */\nexport const refusalReason = (error: unknown) => {\n if (!isApiError(error)) return error instanceof Error ? error.message : text('somethingWrong')\n const reasons = error.errors.map((entry) => entry.message)\n return reasons.length > 0 ? reasons.join('; ') : error.message\n}\n","import type { FieldModel, FieldViewModel, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { encodeKey, tableDisplay, textPlaceholders } from '@protobase/schema/internal'\nimport { listColumnNames } from '../../live/columns-from-model'\nimport { displayValue } from '../../live/display-value'\nimport { recordKey, recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { photosKey } from '../../live/row-photos'\nimport { filledFields } from '../filled-fields'\nimport { boardCard } from './board-columns'\nimport { text } from './messages'\n\n/** A row as a list display gets it: its key, the record as the list API gives it, and names of the records its relations point at. */\nexport type ListDisplayRow = {\n /** The record's key, in the text form the record API takes. */\n key: string\n record: Record<string, unknown>\n /** The name of the record a relation field points at, for the relations the list shows. */\n labels: Record<string, string>\n /** The files of its first photos, when the list loaded the photos its cards display names. */\n photos?: unknown[]\n}\n\n/** What a card component of a cards display (`d.cards(..., { card })`) gets: the record it draws, of the display's fields. */\nexport type RecordCardProps = { row: ListDisplayRow }\n\n/** One choice of the list's display switch: the table first, then the view's displays. */\nexport type DisplayChoice = { name: string; label: string; icon?: string }\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\nexport const displaysOf = (view: ViewModel | undefined): ListDisplayModel[] => view?.list?.displays ?? []\n\n/** The display a list is set to open in: `preferred`, such as a block's `display`, else the view's `default`, else none. */\nconst configuredDisplay = (view: ViewModel | undefined, preferred?: string) => preferred ?? view?.list?.default\n\n/**\n * The display a list opens in when its address names none: the one it is set to open in (`configuredDisplay`) on any\n * screen; with none set, the table, or below the `sm` breakpoint the list's first cards display when it has one.\n */\nexport const defaultDisplay = (view: ViewModel | undefined, xs: boolean, preferred?: string): string => {\n const configured = configuredDisplay(view, preferred)\n if (configured !== undefined) return configured\n if (!xs) return tableDisplay\n return displaysOf(view).find((display) => display.kind === 'cards')?.name ?? tableDisplay\n}\n\n/** The name of the list a phone shows for a list without a cards display. */\nexport const rowsDisplay = 'rows'\n\n/**\n * The list a phone shows for a list without a cards display, as a cards display of a row per record: the title, the\n * first enum column as a badge on the right, and the next two columns, booleans left out, on a muted line below.\n * `undefined` for a view with a cards display, or a display of its own named `rows`.\n */\nexport const phoneRows = (model: ResourceModel, view: ViewModel | undefined): CardsDisplayModel | undefined => {\n if (displaysOf(view).some((display) => display.kind === 'cards' || display.name === rowsDisplay)) return undefined\n const title = recordTitleField(model, view)\n const candidates = listColumnNames(model, view).filter((name) => name !== title && model.fields[name] !== undefined)\n const badge = candidates.find((name) => model.fields[name]!.type === 'enum')\n const footer = candidates.filter((name) => name !== badge && model.fields[name]!.type !== 'boolean').slice(0, 2)\n return { kind: 'cards', name: rowsDisplay, label: text('list'), icon: 'list', title, ...(badge !== undefined && { badge }), footer }\n}\n\nconst isPhoneRows = (view: ViewModel | undefined, display: ListDisplayModel) => display.name === rowsDisplay && !displaysOf(view).some((other) => other.name === rowsDisplay)\n\n/**\n * The display a list page opens in when its address names none: `defaultDisplay`, but below the `sm` breakpoint the\n * phone's rows (`phoneRows`) in place of a table the view is not set to open in.\n */\nexport const listDefaultDisplay = (model: ResourceModel, view: ViewModel | undefined, xs: boolean) => {\n const display = defaultDisplay(view, xs)\n return xs && configuredDisplay(view) === undefined && display === tableDisplay && phoneRows(model, view) ? rowsDisplay : display\n}\n\n/** The display a list page shows for the address's `name`: `shownDisplay`, or the phone's rows when it names them, on any screen. */\nexport const shownListDisplay = (model: ResourceModel, view: ViewModel | undefined, name: string): ListDisplayModel | undefined =>\n (name === rowsDisplay ? phoneRows(model, view) : undefined) ?? shownDisplay(view, name)\n\n/** The display a list shows for the address's `name`: `undefined` for the table, and the view's default for a name it does not have. */\nexport const shownDisplay = (view: ViewModel | undefined, name: string): ListDisplayModel | undefined => {\n if (name === tableDisplay) return undefined\n const named = (wanted: string | undefined) => displaysOf(view).find((display) => display.name === wanted)\n return named(name) ?? named(view?.list?.default)\n}\n\nconst defaultIcons: Partial<Record<ListDisplayModel['kind'], string>> = { cards: 'cards', map: 'map', board: 'kanban', calendar: 'calendar', timeline: 'timeline' }\n\nexport const displayChoices = (view: ViewModel | undefined): DisplayChoice[] => [\n { name: tableDisplay, label: text('table'), icon: 'table' },\n ...displaysOf(view).map((display) => ({ name: display.name, label: display.label ?? humanize(display.name), icon: display.icon ?? defaultIcons[display.kind] })),\n]\n\n/** The list page's display switch: `displayChoices`, and below the `sm` breakpoint the phone's rows when it has them. */\nexport const listDisplayChoices = (model: ResourceModel, view: ViewModel | undefined, xs: boolean): DisplayChoice[] => {\n const choices = displayChoices(view)\n return xs && phoneRows(model, view) ? [...choices, { name: rowsDisplay, label: text('list'), icon: 'list' }] : choices\n}\n\n/** The fields a cards display shows, its title the view's title field when it names none. */\nexport const cardFields = (model: ResourceModel, view: ViewModel | undefined, display: CardsDisplayModel) => ({\n image: display.image,\n title: display.title ?? recordTitleField(model, view),\n subtitle: display.subtitle,\n amount: display.amount ?? [],\n badge: display.badge,\n code: display.code,\n meta: display.meta ?? [],\n footer: display.footer ?? [],\n flags: display.flags ?? [],\n})\n\n/** The meta fields a card shows for a row: those with a value, so a listing for rent only shows no purchase price. */\nexport const filledMeta = (row: ListDisplayRow, meta: string[]) => filledFields(row.record, meta)\n\n/** The amount field a card shows for a row: the first with a value, so a listing for rent only shows its rent. */\nexport const filledAmount = (row: ListDisplayRow, amount: string[]): string | undefined => filledMeta(row, amount)[0]\n\n/** The code field a card shows for a row: the field when it has a value, so an empty one leaves no block behind. */\nexport const filledCode = (row: ListDisplayRow, code: string | undefined): string | undefined => (code === undefined ? undefined : filledMeta(row, [code])[0])\n\n/** A card's code as stored when its field is text, line breaks, spaces and markdown marks all; undefined for another type, which shows its display value. */\nexport const rawCode = (field: FieldModel | undefined, value: unknown) => (field?.type === 'text' && typeof value === 'string' ? value : undefined)\n\n/** A card's amount split for drawing: the number with its prefix, such as `€1,450`, apart from its suffix, such as ` /month`. */\nexport const amountParts = (field: FieldModel, value: unknown, hints: FieldViewModel = {}): { amount: string; suffix?: string } => {\n const { suffix, ...unsuffixed } = hints\n const numeric = field.type === 'decimal' || field.type === 'integer' || field.type === 'bigint'\n if (!numeric || suffix === undefined || hints.format === 'percent') return { amount: displayValue(field, value, hints) }\n return { amount: displayValue(field, value, unsuffixed), suffix }\n}\n\n/** The cards display whose card a map shows for a record: the one it names, else the list's first, else the title alone. */\nexport const mapCards = (view: ViewModel | undefined, display: Extract<ListDisplayModel, { kind: 'map' }>): CardsDisplayModel => {\n const cards = displaysOf(view).filter((other): other is CardsDisplayModel => other.kind === 'cards')\n const named = display.cards === undefined ? cards[0] : cards.find((other) => other.name === display.cards)\n return named ?? { kind: 'cards', name: display.name }\n}\n\n/** Every field a display shows, the fields its rows are loaded and labelled for. */\nexport const shownFields = (model: ResourceModel, view: ViewModel | undefined, display: ListDisplayModel): string[] => {\n if (display.kind === 'custom') return display.fields\n if (display.kind === 'map') return [display.latitude, display.longitude, ...shownFields(model, view, mapCards(view, display))]\n if (display.kind === 'board') {\n const card = boardCard(model, view, display)\n return [display.by, card.title, card.subtitle, card.badge, ...(card.meta ?? [])].filter((name): name is string => name !== undefined)\n }\n if (display.kind === 'calendar') return [display.start, display.end, display.title ?? recordTitleField(model, view)].filter((name): name is string => name !== undefined)\n if (display.kind === 'timeline') return [display.start, display.end, display.group, display.title ?? recordTitleField(model, view)].filter((name): name is string => name !== undefined)\n const { image, title, subtitle, amount, badge, code, meta, footer, flags } = cardFields(model, view, display)\n return [image, title, subtitle, ...amount, badge, code, ...meta, ...footer, ...flags].filter((name): name is string => name !== undefined)\n}\n\n// The fields the view's actions read from a row: each checklist's `from` field, which holds the row's own boxes.\nconst actionFields = (view: ViewModel | undefined) =>\n (view?.actions ?? []).flatMap((action) => (action.inputs ?? []).flatMap((input) => (input.from === undefined ? [] : [input.from])))\n\n// The fields the link texts of shown fields take from the row, such as a report's title for its url.\nconst linkTextFields = (view: ViewModel | undefined, shown: string[]) => shown.flatMap((name) => textPlaceholders(view?.fields[name]?.linkText ?? ''))\n\n/**\n * The fields to load the list's rows with: the table's columns, every display's, the fields their link texts name\n * and those the view's actions read, so one load serves them all.\n */\nexport const loadedFields = (model: ResourceModel, view: ViewModel | undefined, columns: string[]) => {\n const rows = phoneRows(model, view)\n const displays = rows ? [...displaysOf(view), rows] : displaysOf(view)\n const shown = [...columns, ...displays.flatMap((display) => shownFields(model, view, display))]\n return [...new Set([...shown, ...linkTextFields(view, shown), ...actionFields(view)])]\n}\n\n/**\n * The sortable fields a display shows, for the sort menu that stands in for column headers; for the phone's rows, those\n * of the table's columns and the title, as the table's headers sort by.\n */\nexport const sortFields = (model: ResourceModel, view: ViewModel | undefined, display: ListDisplayModel) => {\n const shown = isPhoneRows(view, display) ? [recordTitleField(model, view), ...listColumnNames(model, view)] : shownFields(model, view, display)\n return [...new Set(shown)].filter((name) => model.fields[name]?.sortable)\n}\n\nconst isLabelled = (value: unknown): value is { id: unknown; name: string } => typeof value === 'object' && value !== null && 'id' in value && 'name' in value\n\n/**\n * A loaded row, its relations as `{ id, name }`, split into the record as the API gives it, the relations' names and\n * the photos it was loaded with.\n */\nexport const displayRow = (model: ResourceModel, row: Record<string, unknown>): ListDisplayRow => {\n const record: Record<string, unknown> = {}\n const labels: Record<string, string> = {}\n const photos = Array.isArray(row[photosKey]) ? (row[photosKey] as unknown[]) : undefined\n for (const [name, value] of Object.entries(row)) {\n if ((name === 'id' || name === photosKey) && !Object.hasOwn(model.fields, name)) continue\n if (model.fields[name]?.type === 'relation' && isLabelled(value)) {\n record[name] = value.id\n labels[name] = value.name\n } else {\n record[name] = value\n }\n }\n return { key: encodeKey(recordKey(model, record)), record, labels, ...(photos && { photos }) }\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\n\nexport type Sort = { columnId: string; direction: 'asc' | 'desc' }\n\n/**\n * The order a list opens in: the view's sort, else the primary key's when it is sortable. Otherwise none, as the API\n * refuses a sort by a field that is not sortable and orders a list without one by its key anyway.\n */\nexport const defaultOrderBy = (model: ResourceModel, view: ViewModel | undefined) => {\n const sort = view?.list?.sort?.[0]\n if (sort) return `${sort[0]} ${sort[1]}`\n const key = model.primaryKey[0]!\n return model.fields[key]?.sortable ? `${key} asc` : ''\n}\n\nexport const parseSort = (orderBy: string): Sort => {\n const [columnId = '', direction] = orderBy.trim().split(/\\s+/)\n return { columnId, direction: direction === 'desc' ? 'desc' : 'asc' }\n}\n\nexport const sortToOrderBy = (sort: Sort) => `${sort.columnId} ${sort.direction}`\n","import type { AppAddress, CalendarView, FilterLayout, MapView, ResourceModel, TimelineView, ViewModel } from '@protobase/schema'\nimport { encodeKey, viewOfList } from '@protobase/schema/internal'\nimport { defaultDisplay, listDefaultDisplay } from './displays/list-displays'\nimport { defaultOrderBy } from './list-order'\n\n/**\n * A list as the app shows it: every value there, the view's default where the address names none; `map`, `calendar`,\n * `timeline` and `savedSearch`, the saved search it was opened from, have none.\n */\nexport type ListAddress = { kind: 'list'; resource: string; list?: string; display: string; filter: string; orderBy: string; filterLayout: FilterLayout; map?: MapView; calendar?: CalendarView; timeline?: TimelineView; savedSearch?: string }\n\n/** The address the app shows, as logical values. A record's key is in the text form the record API takes. */\nexport type CurrentAddress =\n | ListAddress\n | { kind: 'record'; resource: string; key: string; edit?: true; open?: readonly string[]; tab?: string; standard?: true; call?: 'join'; version?: number; run?: string; panel?: string; file?: string }\n | { kind: 'create'; resource: string; values?: Readonly<Record<string, string>> }\n | { kind: 'page'; page: string; tab?: string; params?: Readonly<Record<string, string>> }\n\n/** What can change about the list the app shows; `undefined` returns a value to its default. */\nexport type ListChange = Partial<Omit<ListAddress, 'kind' | 'resource' | 'list'>>\n\nexport type ListDefaults = Pick<ListAddress, 'display' | 'orderBy' | 'filterLayout' | 'filter'>\n\n/**\n * The resource whose records a list shows, with its view: the list's own, or, when its view has `listOf`, the resource\n * that relation points at, if the caller can see it.\n */\nexport const listedResource = (resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, resource: string, list?: string) => {\n const model = resources[resource]\n const own = viewOfList(views[resource], list)\n const listOf = own?.listOf\n const target = listOf === undefined ? undefined : model?.fields[listOf]?.relation?.resource\n return target !== undefined && resources[target] ? { model: resources[target], view: views[target], listOf: true } : { model, view: own, listOf: false }\n}\n\n/** What a list shows when its address names nothing: its default display for the screen, the list's sort, the filters in a bar. */\nexport const listDefaults = (model: ResourceModel | undefined, view: ViewModel | undefined, xs = false): ListDefaults => ({\n display: model ? listDefaultDisplay(model, view, xs) : defaultDisplay(view, xs),\n orderBy: model ? defaultOrderBy(model, view) : '',\n filterLayout: 'bar',\n filter: view?.list?.filter ?? '',\n})\n\n/** The address as read from the location, with a list's defaults filled in and a record's key as text. */\nexport const currentAddress = (read: AppAddress | undefined, defaults: (resource: string, list?: string) => ListDefaults): CurrentAddress | undefined => {\n if (read?.kind === 'record') return { kind: 'record', resource: read.resource, key: encodeKey(read.key), ...(read.edit && { edit: true as const }), ...(read.open && { open: read.open }), ...(read.tab && { tab: read.tab }), ...(read.standard && { standard: true as const }), ...(read.call && { call: read.call }), ...(read.version !== undefined && { version: read.version }), ...(read.run && { run: read.run }), ...(read.panel && { panel: read.panel }), ...(read.file && { file: read.file }) }\n if (read?.kind !== 'list') return read\n return { ...defaults(read.resource, read.list), ...read }\n}\n\n/** The list address after `change`, leaving out every value that is empty or its default (a cleared filter is written as an empty `filter=` when the default is not empty), so `/<resource>` stays clean. */\nexport const changedList = (read: Extract<AppAddress, { kind: 'list' }>, change: ListChange, defaults: ListDefaults): AppAddress => {\n const next = { ...read, ...change }\n const differs = (name: keyof ListDefaults) => next[name] !== undefined && next[name] !== defaults[name]\n return {\n kind: 'list',\n resource: read.resource,\n ...(read.list && { list: read.list }),\n ...(differs('filter') && { filter: next.filter }),\n ...(differs('display') && { display: next.display }),\n ...(differs('orderBy') && { orderBy: next.orderBy }),\n ...(differs('filterLayout') && { filterLayout: next.filterLayout }),\n ...(next.map && { map: next.map }),\n ...(next.calendar && { calendar: next.calendar }),\n ...(next.timeline && { timeline: next.timeline }),\n ...(next.savedSearch && { savedSearch: next.savedSearch }),\n }\n}\n","import { useCallback, useMemo, type AnchorHTMLAttributes } from 'react'\nimport { appPath, readAppPath, type AppAddress } from '@protobase/schema'\nimport { useIsXs } from '../lib/use-media-query'\nimport { changedList, currentAddress, listDefaults, listedResource, type ListChange } from './current-address'\nimport { useAdminMeta } from './meta-gate'\nimport { Link, useRouter, type NavigateOptions } from './router'\n\nexport type { CurrentAddress, ListAddress, ListChange } from './current-address'\n\n/**\n * The app's address as logical values, and the ways to change it: `set` changes the list in place, `listTo` is the\n * list after a change for a link to it, `go` moves to\n * another address, `href` is an address for an `<a href>`, `open` follows such an href and `back` goes back to one.\n * Every component reads and writes the address through this hook, never the query string or a path of its own.\n */\nexport const useAppAddress = () => {\n const { path, params, basePath, navigate, back: backTo } = useRouter()\n const { pages, resources, views } = useAdminMeta()\n const xs = useIsXs()\n const pageNames = useMemo(() => new Set(Object.keys(pages)), [pages])\n const query = params.toString()\n const read = useMemo(() => readAppPath(query ? `${path}?${query}` : path, pageNames), [path, query, pageNames])\n const defaults = useCallback(\n (resource: string, list?: string) => {\n const listed = listedResource(resources, views, resource, list)\n return listDefaults(listed.model, listed.view, xs)\n },\n [resources, views, xs],\n )\n const address = useMemo(() => currentAddress(read, defaults), [read, defaults])\n\n const go = useCallback((to: AppAddress, options?: NavigateOptions) => navigate(appPath(to), options), [navigate])\n\n const listTo = useCallback(\n (change: ListChange) => {\n if (read?.kind !== 'list') throw new Error('listTo and set change the list the app shows; use go to move to another address')\n return changedList(read, change, defaults(read.resource, read.list))\n },\n [read, defaults],\n )\n\n const set = useCallback((change: ListChange) => go(listTo(change), { replace: true }), [listTo, go])\n\n const href = useCallback((to: AppAddress) => appPath(to, basePath), [basePath])\n\n // The shell's links carry the base path, as hrefs must; the router takes the path below it.\n const below = useCallback((target: string) => (target.startsWith(`${basePath}/`) ? target.slice(basePath.length) : target), [basePath])\n const open = useCallback((target: string) => navigate(below(target)), [below, navigate])\n const back = useCallback((target: string) => backTo(below(target)), [below, backTo])\n\n return { address, set, listTo, go, href, open, back }\n}\n\n/** A link to an address in the app: an ordinary anchor that the router follows without reloading the page. */\nexport const AppLink = ({ to, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: AppAddress; replace?: boolean }) => <Link to={appPath(to)} {...rest} />\n"],"mappings":"+nCAEA,IAAaiF,GACX,EACA,EACA,EACA,KACiB,CAAE,OAAM,UAAS,OAAM,MAAK,GAIzCC,IAAY,EAAW,IAAc,CACzC,IAAIC,EAAM,MAAM,KAAK,CAAE,OAAQC,EAAE,OAAS,CAAE,G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AAsL,EAAA,IAAA,CAAC2E,GAAD,CAAM,GAAIyB,EAAQrI,CAAE,EAAG,GAAIrJ,CAAO,CAAA","debugId":"f9d1f375-9cfb-4aa5-a465-7f9e0fd2e010"}
1
+ {"version":3,"file":"use-app-address-B6k3dkV0.js","names":["parse","check","parse","check","field","isObject","isObject","createContext","useContext","useMemo","createContext","useContext","useState","useRef","useCallback","useMemo","appText","_Fragment","useMemo","Fragment","createContext","useContext","text","createContext","useContext","text","useContext","useMemo","text","useSyncExternalStore","useMemo","useCallback","n","a","t","__toESM","require_react","require_jsx_runtime","guarded","parseFilter$1","parseOrderBy$1","checkOrderBy$1","checkFilter$1","useQueries","IntlMessageFormat","useQueryClient","printFilter","functions","parseOptions","schemaOf","Spinner","isApiError","Button","lift","encodeKey","ClientProvider","useSourceClients","useClient","keys","hrefField","text$3","RouteLink","embeddedFilterFields","isLayoutNode","enumLabel","revealLate","addressPlaceholders","filterField","recordKey","resourceField","textPlaceholders","displayValue","activeLocale","messages","setAppLocale","catalogues","humanize","MetaContext","Dialog","useMeta","cn","filterError","distance","row","b","i","next","j","cost","suggest","lower","name","scored","candidates","candidate","findField","model","field","resolveField","path","ctx","usable","f","capability","close","method","unsupported","l","message","hint","span","fieldOf","node","valueOf","left","literalOf","wordOf","isSubfilter","arg","pageOf","orderBy","limit","pageToken","extra","args","lowerRelated","target","rest","usage","bad","subfilter","page","related","filter","lowerCall","first","second","string","values","v","all","items","item","value","parseFilter","parsed","source","limits","lowering","ast","errors","daysIn","month","year","isValidDate","match","text","day","isValidTimestamp","hour","minute","offsetHour","offsetMinute","problem","int64Min","int64Max","uuid","numericText","expected","what","checkInteger","number","checkBigint","checkDecimal","checkValue","equality","ordered","compareOps","type","isOpaque","relatedRefused","operatorError","isWildcard","op","checkCompare","allowed","checkHas","checkIn","literal","checkText","checkNode","checkAgainstModel","checkFilter","traversal","generic","lowercaseDirections","before","space","word","parseOrderBy","checkOrderBy","checked","parseDurationText","field$1","filterValue","group","kind","createWhere","compare","offset","duration","low","high","where","refMark","ref","isRef","createRefs","known","make","fieldRef","isFieldRef","isObject$2","markFieldRefs","entry","unmarkFieldRefs","fieldRefsIn","naming","label","icon","tableDisplay","customComponent","component","displays","o","fields","column","displayName","displayErrors","names","list","display","index","other","approximateErrors","error","approximate","exact","radius","defaultRadius","area","boardErrors","datesErrors","start","end","unfilterable","displayFields","viewOfList","view","named","_list","_chart","_help","_nav","_lists","_names","_name","parts","nameErrors","withSamples","quote","filterErrors","embedded","orderErrors","addressErrors","placeholders","to","placeholderError","recordFilter","filterFromRecord","pages","models","createPages","isObject$1","shape","rowButtonChoices","button","rowButtonTarget","href","choice","rowButtonChoiceFields","rowButtonFields","missing","part","choiceErrors","check","rowButtonErrors","followableRowButton","kept","labelCandidates","namesRecords","labelFieldOf","recordTitleField","recordTitle","record","fallback","listColumnNames","resource","import_react","import_jsx_runtime","GuardedParamsContext","GuardedParams","outer","useGuardedParams","leavesPage","from","after","guards","guard","pendingLink","followLink","go","link","storageKey","isPlace","read","raw","storage","createPagePlaces","places","top","oldest","patience","restoreScroll","placed","place","observer","stop","moved","timer","RouterContext","useRouter","browserUrl","pathOf","url","historyState","historyIndex","newEntry","historyEntry","state","noStorage","Router","memory","initialUrl","setPage","losesInput","current","position","undoing","proceeding","leaveAfterUndo","reloading","pending","setPending","rememberScroll","persist","hidden","onPop","delta","replace","previous","full","keepScroll","navigate","basePath","options","back","registerGuard","token","reload","reloadConfirmed","holdsChanges","leave","children","Link","useNavigationGuard","params","active","warn","event","addressWords","listWords","mapText","inRange","readMap","latitude","longitude","zoom","periodText","isDay","date","readPeriod","scale","scales","listQuery","query","address","recordQuery","title","appPath","valuesQuery","decodeSegments","pathname","readVersion","filterLayout","readAppPath","pathAndQuery","segments","open","tab","standard","call","version","run","panel","file","layout","map","calendar","timeline","savedSearch","nameOf","routedClient","sourceOf","own","key","body","patch","etag","action","input","apis","ops","proof","handlers","runId","held","runner","recorded","scopes","lastScope","building","inScope","scope","build","scopeOf","markScope","keepScope","copy","durationPattern","Now","checkDuration","Condition","join","side","right","isRecorded","placeholder","member","valueText","term","comparisons","comparisonNames","recorder","fieldRecorder","advice","describe","isPlainObject","prototype","staticValue","normalizeChildren","child","isBlock","recordChildBlocks","conditionArrows","builtProps","built","props","prop","condition","builtChildren","recordPropBlocks","fallbackBlocks","builtRecordProp","one","only","createNode","written","ownFallback","taken","given","recordProp","perRecord","defineBlock","block","reads","resolveFieldPath","steps","argumentTypes","tagType","walk","element","elements","found","option","messageParts","language","compiled","formatMessage","texts","id","format","tags","formatText","formatted","tag","chunks","isTrans","withinSource","drawn","_outside","plain","keptLayoutItem","inner","columns","narrowed","followable","keptAction","withinSourceView","sourceMeta","listed","meta","resources","scoped","allowEverything","sourceTimeoutMs","combine","results","result","useSourceMetas","queryClient","sources","queryKey","clientOf","data","withSources","ready","sourceStatusOf","status","AppLocale","locale","AppTexts","useAppTexts","isObject","transText","ownPropTexts","withPropTexts","namespace","text$2","translated","hints","prefix","shown","tableKey","translatedView","at","withTranslatedViews","createSplashHold","holds","started","settle","hide","released","SplashHoldContext","SplashHoldProvider","HoldSplash","splash","text$1","useAdminMeta","Notice","WithSources","declared","merged","routing","byResource","resourceClient","TranslatedMeta","MetaGate","usePermissions","useMediaQuery","onChange","useIsDesktop","useIsXs","photosKey","listPhotos","withPhotos","photos","rows","filledFields","boardColumns","boardRank","columnFilter","by","boardCard","refusalReason","reasons","displaysOf","configuredDisplay","preferred","defaultDisplay","configured","xs","rowsDisplay","phoneRows","badge","footer","isPhoneRows","listDefaultDisplay","shownListDisplay","shownDisplay","wanted","defaultIcons","displayChoices","listDisplayChoices","choices","cardFields","filledMeta","filledAmount","amount","filledCode","code","rawCode","amountParts","unsuffixed","suffix","mapCards","cards","shownFields","card","image","subtitle","flags","actionFields","linkTextFields","loadedFields","sortFields","isLabelled","displayRow","labels","\"$photos\"","defaultOrderBy","sort","parseSort","columnId","direction","sortToOrderBy","listedResource","views","listOf","listDefaults","currentAddress","defaults","changedList","change","differs","useAppAddress","backTo","pageNames","listTo","set","below","AppLink"],"sources":["../../../../schema/src/filter/errors.ts","../../../../schema/src/filter/check-field.ts","../../../../schema/src/filter/lower.ts","../../../../schema/src/filter/parse.ts","../../../../schema/src/filter/datetime.ts","../../../../schema/src/filter/check-value.ts","../../../../schema/src/filter/operators.ts","../../../../schema/src/filter/related.ts","../../../../schema/src/filter/check-model.ts","../../../../schema/src/filter/check.ts","../../../../schema/src/filter/order-by.ts","../../../../schema/src/filter/duration.ts","../../../../schema/src/filter/where.ts","../../../../schema/src/refs.ts","../../../../schema/src/field-ref.ts","../../../../schema/src/view-displays.ts","../../../../schema/src/named-list.ts","../../../../schema/src/address-errors.ts","../../../../schema/src/row-button.ts","../../../../schema/src/record-title.ts","../../../../schema/src/list-columns.ts","../../../src/app/guarded-params.tsx","../../../src/app/leaves-page.ts","../../../src/app/pending-link.ts","../../../src/app/page-places.ts","../../../src/app/restore-scroll.ts","../../../src/app/router.tsx","../../../../schema/src/app-address.ts","../../../../client/src/routed-client.ts","../../../../layout/src/typed/record.ts","../../../../layout/src/create-node.ts","../../../../layout/src/field-path.ts","../../../../layout/src/translations.ts","../../../../client/src/source-meta.ts","../../../src/data/meta-data.ts","../../../src/data/use-source-metas.ts","../../../src/data/with-sources.ts","../../../src/locale/app-locale.tsx","../../../src/app/pages/app-texts.ts","../../../src/app/built-in-views/translated-views.ts","../../../src/app/splash-hold.tsx","../../../src/app/meta-gate-messages.ts","../../../src/app/meta-gate.tsx","../../../src/lib/use-media-query.ts","../../../src/live/row-photos.ts","../../../src/app/filled-fields.ts","../../../src/app/displays/messages.ts","../../../src/app/displays/board-columns.ts","../../../src/app/displays/list-displays.ts","../../../src/app/list-order.ts","../../../src/app/current-address.ts","../../../src/app/use-app-address.tsx"],"sourcesContent":["import type { FilterError, FilterErrorCode, Span } from '../model'\n\nexport const filterError = (\n code: FilterErrorCode,\n message: string,\n hint: string,\n span: Span,\n): FilterError => ({ code, message, hint, span })\n\nexport const joinSpans = (a: Span, b: Span): Span => ({ start: a.start, end: b.end })\n\nconst distance = (a: string, b: string) => {\n let row = Array.from({ length: b.length + 1 }, (_, i) => i)\n for (let i = 1; i <= a.length; i++) {\n const next = [i]\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + cost)\n }\n row = next\n }\n return row[b.length]!\n}\n\nexport const suggest = (name: string, candidates: string[]) => {\n const lower = name.toLowerCase()\n const scored = candidates\n .map((candidate) => ({ candidate, score: distance(lower, candidate.toLowerCase()) }))\n .sort((a, b) => a.score - b.score)[0]\n return scored && scored.score <= Math.max(2, Math.floor(name.length / 3)) ? scored.candidate : undefined\n}\n","import type { FieldModel, FieldPath, FilterError, ResourceModel } from '../model'\nimport { filterError, suggest } from './errors'\n\nexport type CheckContext = { model: ResourceModel; errors: FilterError[] }\n\nexport const findField = (model: ResourceModel, name: string) =>\n Object.hasOwn(model.fields, name)\n ? model.fields[name]\n : Object.values(model.fields).find((field) => field.aliases.includes(name))\n\nexport const resolveField = (\n ctx: CheckContext,\n path: FieldPath,\n capability: 'filterable' | 'sortable',\n): FieldModel | undefined => {\n if (path.path.length > 1) {\n ctx.errors.push(\n filterError(\n 'unsupported-traversal',\n `Traversal into \"${path.path.join('.')}\" is not supported yet`,\n 'Filter on fields of this resource only',\n path.span,\n ),\n )\n return undefined\n }\n const name = path.path[0]!\n const field = findField(ctx.model, name)\n if (!field) {\n const usable = Object.values(ctx.model.fields).filter((f) => f[capability]).map((f) => f.name)\n const close = suggest(name, usable)\n ctx.errors.push(\n filterError(\n 'unknown-field',\n `Unknown field \"${name}\"`,\n close ? `Did you mean \"${close}\"?` : `Available fields: ${usable.join(', ')}`,\n path.span,\n ),\n )\n return undefined\n }\n if (!field[capability]) {\n const method = capability === 'filterable' ? 'filterable' : 'sortable'\n ctx.errors.push(\n filterError(\n capability === 'filterable' ? 'not-filterable' : 'not-sortable',\n `Field \"${field.name}\" is not ${method}`,\n `Mark it with .${method}() in data.ts`,\n path.span,\n ),\n )\n return undefined\n }\n return field\n}\n","import type { Arg, Call, Expr as Generic, Operand } from 'aip-parsers/filter'\nimport type { FieldPath, FilterError, FilterExpr, FilterValue, Literal, Span } from '../model'\nimport { filterError } from './errors'\nimport { functions } from './profile'\n\nexport type Lowering = { errors: FilterError[] }\n\nconst unsupported = (l: Lowering, message: string, hint: string, span: Span) => {\n l.errors.push(filterError('unsupported', message, hint, span))\n return undefined\n}\n\nconst fieldOf = (l: Lowering, node: Operand): FieldPath | undefined =>\n node.kind === 'member'\n ? { kind: 'field', path: node.path, span: node.span }\n : unsupported(l, 'Only fields can be compared', 'Put a field name on the left, for example total > 100', node.span)\n\n// Bare words on the right are text; now() with an optional duration offset is a NowValue.\nconst valueOf = (l: Lowering, node: Operand): FilterValue | undefined => {\n switch (node.kind) {\n case 'member':\n return { kind: 'string', value: node.path.join('.'), span: node.span }\n case 'call':\n if (node.name === 'now' && node.args.length === 0) return { kind: 'now', span: node.span }\n return unsupported(l, `${node.name}() cannot be used as a value`, 'Only now() is a value function', node.span)\n case 'binary': {\n const left = node.left\n const isNow = left.kind === 'call' && left.name === 'now' && left.args.length === 0\n if (isNow && node.right.kind === 'duration') {\n return { kind: 'now', offset: { sign: node.op, duration: node.right }, span: node.span }\n }\n return unsupported(l, 'Arithmetic is only supported as now() +/- duration', 'Write now() - 30d', node.span)\n }\n default:\n return node\n }\n}\n\nconst literalOf = (l: Lowering, node: Arg): Literal | undefined => {\n const value = 'kind' in node && ['member', 'call', 'binary'].includes(node.kind) ? undefined : (node as Literal)\n if (value) return value\n if (node.kind === 'member') return { kind: 'string', value: node.path.join('.'), span: node.span }\n return unsupported(l, 'Expected a literal value', 'Use strings, numbers, true/false, durations or timestamps', node.span)\n}\n\nconst wordOf = (node: Operand) => {\n switch (node.kind) {\n case 'member':\n return node.path.join('.')\n case 'string':\n case 'timestamp':\n return node.kind === 'string' ? node.value : node.value\n case 'number':\n return node.raw\n case 'boolean':\n return String(node.value)\n case 'duration':\n return `${node.amount}${node.unit}`\n default:\n return ''\n }\n}\n\n// The subfilter is a group in parentheses, or a function call alone in them, as `related(...)` is when it nests. A bare\n// value would lower to nothing and drop the whole filter without an error.\nconst isSubfilter = (arg: Arg): arg is Generic => ['sequence', 'and', 'or', 'not', 'compare', 'has', 'present', 'global', 'call'].includes(arg.kind)\n\n// After the optional subfilter come the parent read's page, in a list's order: `\"order_by\"`, a positive whole `limit`\n// and `\"page_token\"`, each needing the one before it.\nconst pageOf = (args: Arg[]) => {\n const [orderBy, limit, pageToken, ...extra] = args\n if (extra.length > 0) return undefined\n if (orderBy && orderBy.kind !== 'string') return undefined\n if (limit && (limit.kind !== 'number' || !Number.isSafeInteger(limit.value) || limit.value < 1)) return undefined\n if (pageToken && pageToken.kind !== 'string') return undefined\n return {\n ...(orderBy?.kind === 'string' && { orderBy: orderBy.value }),\n ...(limit?.kind === 'number' && { limit: limit.value }),\n ...(pageToken?.kind === 'string' && { pageToken: pageToken.value }),\n }\n}\n\nconst lowerRelated = (l: Lowering, node: Call, field: FieldPath | undefined, bad: (usage: string) => undefined): FilterExpr | undefined => {\n const [, target, ...rest] = node.args\n const usage = 'related(field, resource.field, (filter), \"order_by\", limit, \"page_token\"), each after the field optional'\n if (!field || target?.kind !== 'member' || target.path.length !== 2) return bad(usage)\n const subfilter = rest[0] && isSubfilter(rest[0]) ? rest[0] : undefined\n const page = pageOf(subfilter ? rest.slice(1) : rest)\n if (!page) return bad(usage)\n const related = { kind: 'related', field, resource: target.path[0]!, key: target.path[1]!, ...page, span: node.span } as const\n if (!subfilter) return related\n const filter = lower(l, subfilter)\n return filter && { ...related, filter }\n}\n\nconst lowerCall = (l: Lowering, node: Call): FilterExpr | undefined => {\n const [first, second, ...rest] = node.args\n const field = first?.kind === 'member' ? fieldOf(l, first) : undefined\n const string = (arg: Arg | undefined) => (arg?.kind === 'string' ? arg.value : undefined)\n const bad = (usage: string) => {\n l.errors.push(filterError('invalid-arguments', `Invalid arguments to ${node.name}()`, `Usage: ${usage}`, node.span))\n return undefined\n }\n switch (node.name) {\n case 'in': {\n const values = node.args.slice(1).map((arg) => literalOf(l, arg))\n if (!field || values.length === 0) return bad('in(field, value1, value2, ...)')\n return values.every((v) => v) ? { kind: 'in', field, values: values as Literal[], span: node.span } : undefined\n }\n case 'search':\n return string(first) !== undefined && !second ? { kind: 'search', text: string(first)!, span: node.span } : bad('search(\"text\")')\n case 'similar':\n return field && string(second) !== undefined && rest.length === 0 ? { kind: 'similar', field, text: string(second)!, span: node.span } : bad('similar(field, \"text\")')\n case 'regex':\n return field && string(second) !== undefined && rest.length === 0 ? { kind: 'regex', field, pattern: string(second)!, span: node.span } : bad('regex(field, \"pattern\")')\n case 'isNull':\n return field && !second ? { kind: 'isNull', field, span: node.span } : bad('isNull(field)')\n case 'related':\n return lowerRelated(l, node, field, bad)\n default:\n l.errors.push(filterError('unknown-function', `Unknown function \"${node.name}\"`, `Available functions: ${Object.keys(functions).join(', ')}`, node.span))\n return undefined\n }\n}\n\nconst all = (items: (FilterExpr | undefined)[]) => (items.every((item) => item) ? (items as FilterExpr[]) : undefined)\n\n/** Lowers a generic AIP-160 expression to Protobase's filter shape; unsupported constructs become errors. */\nexport const lower = (l: Lowering, node: Generic): FilterExpr | undefined => {\n switch (node.kind) {\n case 'sequence':\n case 'and':\n case 'or': {\n const args = all(node.args.map((arg) => lower(l, arg)))\n return args && { kind: node.kind === 'or' ? 'or' : 'and', args, span: node.span }\n }\n case 'not': {\n const arg = lower(l, node.arg)\n return arg && { kind: 'not', arg, span: node.span }\n }\n case 'compare': {\n const field = fieldOf(l, node.left)\n const value = valueOf(l, node.right)\n return field && value && { kind: 'compare', op: node.op, field, value, span: node.span }\n }\n case 'has': {\n const field = fieldOf(l, node.left)\n const value = literalOf(l, node.right)\n return field && value && { kind: 'has', field, value, span: node.span }\n }\n case 'present': {\n const field = fieldOf(l, node.left)\n return field && { kind: 'present', field, span: node.span }\n }\n case 'global':\n return { kind: 'search', text: wordOf(node.value), span: node.span }\n case 'call':\n return lowerCall(l, node)\n }\n}\n","import { parseFilter as parse, type ParseOptions } from 'aip-parsers/filter'\nimport type { FilterError, FilterExpr } from '../model'\nimport { lower } from './lower'\nimport { parseOptions } from './profile'\n\n/** What `parseFilter` gives: the filter, `undefined` for empty text, or the errors in the order they occur in the text. */\nexport type FilterParse =\n | {\n /** The text parsed. */\n ok: true\n /** The filter, or `undefined` when the text is empty. */\n ast: FilterExpr | undefined\n /** None. */\n errors: []\n }\n | {\n /** The text did not parse. */\n ok: false\n /** As much of the filter as parsed. */\n ast: FilterExpr | undefined\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/** Bounds on filter text: its length in characters and how deeply its expressions nest. */\nexport type FilterLimits = Pick<ParseOptions, 'maxLength' | 'maxDepth'>\n\n/**\n * Parses filter text, AIP-160 as the API takes it, into a filter, collecting every error. `maxLength` defaults to\n * 10,000 characters and `maxDepth` to 64. Check the result against a resource with `checkFilter` before running it.\n *\n * @example\n * ```ts\n * const parsed = parseFilter('status = \"paid\" AND total > 100')\n * if (parsed.ok && parsed.ast) printFilter(parsed.ast) // 'status = \"paid\" AND total > 100'\n * ```\n */\nexport const parseFilter = (source: string, limits: FilterLimits = {}): FilterParse => {\n const parsed = parse(source, { ...parseOptions, ...limits })\n const lowering = { errors: [] as FilterError[] }\n const ast = parsed.ast && lower(lowering, parsed.ast)\n const errors = [...parsed.errors, ...lowering.errors].sort((a, b) => a.span.start - b.span.start)\n return errors.length === 0 ? { ok: true, ast, errors: [] } : { ok: false, ast, errors }\n}\n","const daysIn = (year: number, month: number) => {\n if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28\n return [4, 6, 9, 11].includes(month) ? 30 : 31\n}\n\nexport const isValidDate = (text: string) => {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return false\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n return month >= 1 && month <= 12 && day >= 1 && day <= daysIn(year, month)\n}\n\nexport const isValidTimestamp = (text: string) => {\n const match =\n /^(\\d{4}-\\d{2}-\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:[Zz]|[+-](\\d{2}):(\\d{2}))$/.exec(text)\n if (!match) return false\n const [hour, minute, second] = [Number(match[2]), Number(match[3]), Number(match[4])]\n const [offsetHour, offsetMinute] = [Number(match[5] ?? 0), Number(match[6] ?? 0)]\n return (\n isValidDate(match[1]!) &&\n hour <= 23 &&\n minute <= 59 &&\n second <= 59 &&\n offsetHour <= 23 &&\n offsetMinute <= 59\n )\n}\n","import type { FieldModel, FilterValue } from '../model'\nimport { isValidDate, isValidTimestamp } from './datetime'\n\nexport type Problem = { message: string; hint: string }\n\nconst problem = (message: string, hint: string): Problem => ({ message, hint })\n\nconst int64Min = -(2n ** 63n)\nconst int64Max = 2n ** 63n - 1n\nconst uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n// Numbers may be written as number literals or quoted strings; precision lives in the text.\nconst numericText = (value: FilterValue) =>\n value.kind === 'number' ? value.raw : value.kind === 'string' ? value.value : undefined\n\nconst expected = (what: string, hint = `Write ${what} values like the examples in the docs`) =>\n problem(`Expected ${what}`, hint)\n\nconst checkInteger = (value: FilterValue) => {\n const text = numericText(value)\n const number = text === undefined ? NaN : Number(text)\n if (text === undefined || text.trim() === '' || !Number.isSafeInteger(number)) {\n return expected('a whole number', 'Use an integer such as 42, or a bigint field for larger values')\n }\n}\n\nconst checkBigint = (value: FilterValue) => {\n const text = numericText(value)\n if (text === undefined || !/^-?\\d+$/.test(text) || BigInt(text) < int64Min || BigInt(text) > int64Max) {\n return expected('a 64-bit integer', 'Use plain digits such as 9007199254740993 (no exponent or fraction)')\n }\n}\n\nconst checkDecimal = (value: FilterValue) => {\n const text = numericText(value)\n if (text === undefined || !/^-?\\d+(\\.\\d+)?$/.test(text)) {\n return expected('a decimal number', 'Use plain digits such as 100.50, or quote it: \"100.50\" (no exponent)')\n }\n}\n\nexport const checkValue = (field: FieldModel, value: FilterValue): Problem | undefined => {\n if (value.kind === 'now') {\n if (field.type === 'date' || field.type === 'timestamp') return undefined\n return problem('now() only works with date and timestamp fields', `Field \"${field.name}\" is ${field.type}`)\n }\n switch (field.type) {\n case 'text':\n if (value.kind !== 'string') return expected('a quoted string', 'Wrap the text in double quotes')\n return undefined\n case 'integer':\n return checkInteger(value)\n case 'bigint':\n return checkBigint(value)\n case 'decimal':\n return checkDecimal(value)\n case 'boolean':\n return value.kind === 'boolean' ? undefined : expected('true or false')\n case 'date':\n if (value.kind === 'string' && isValidDate(value.value)) return undefined\n return expected('a date', 'Quote a calendar date: \"2012-04-21\"')\n case 'timestamp':\n if (value.kind === 'timestamp' || (value.kind === 'string' && isValidTimestamp(value.value))) return undefined\n return expected('an RFC-3339 timestamp', 'Use 2012-04-21T11:30:00Z, or now() - 7d')\n case 'uuid':\n if (value.kind === 'string' && uuid.test(value.value)) return undefined\n return expected('a uuid', 'Quote a uuid like \"0b5a4f0e-6f2a-4a3c-9d4e-1f2a3b4c5d6e\"')\n case 'enum':\n if (value.kind === 'string' && field.enumValues?.includes(value.value)) return undefined\n return problem('Invalid enum value', `Allowed values: ${(field.enumValues ?? []).join(', ')}`)\n case 'currency':\n if (value.kind === 'string' && /^[A-Z]{3}$/.test(value.value)) return undefined\n return expected('an ISO 4217 currency code', 'Use three capital letters, for example \"EUR\"')\n case 'country':\n if (value.kind === 'string' && /^[A-Z]{2}$/.test(value.value)) return undefined\n return expected('an ISO 3166-1 country code', 'Use two capital letters, for example \"NL\"')\n case 'relation':\n if (value.kind === 'string' || (value.kind === 'number' && Number.isSafeInteger(value.value))) return undefined\n return expected('a record key', 'Use the related record key: 42 or \"abc\"')\n case 'json':\n case 'file':\n return problem(`${field.type} fields cannot be compared`, 'Use field:value on json fields, or isNull(field)')\n }\n}\n","import type { CompareOp, FieldType } from '../model'\n\nconst equality: CompareOp[] = ['=', '!=']\nconst ordered: CompareOp[] = ['=', '!=', '<', '<=', '>', '>=']\n\nexport const compareOps = (type: FieldType): CompareOp[] => {\n switch (type) {\n case 'text':\n case 'integer':\n case 'bigint':\n case 'decimal':\n case 'date':\n case 'timestamp':\n return ordered\n case 'json':\n case 'file':\n return []\n default:\n return equality\n }\n}\n\nexport const isOpaque = (type: FieldType) => type === 'json' || type === 'file'\n","import type { FieldModel, FilterError, FilterExpr, RelatedFilter, ResourceModel, Span } from '../model'\nimport { filterError } from './errors'\n\n/** How deep `related()` nests inside the subfilters of a filter. */\nexport const maxRelatedDepth = 2\n/** How many `related()` terms one filter holds, those in its subfilters included. */\nexport const maxRelatedTerms = 3\n\n/** Everything but a list-style read refuses `related()`, which only the database can answer; so does any place but a term ANDed at the top. */\nexport const relatedRefused = (span: Span) =>\n filterError('unsupported-traversal', \"related() only works in a list's filter, ANDed with the rest\", 'Put it at the top of the filter or of a subfilter, joined with AND', span)\n\n/** The resource whose records the field holds keys of: a relation's to a single key, or the resource's own for its single key. */\nexport const relatedTarget = (model: ResourceModel, field: FieldModel) => {\n if (field.relation) return field.relation.columns.length === 1 ? field.relation.resource : undefined\n return model.primaryKey.length === 1 && model.primaryKey[0] === field.name ? model.name : undefined\n}\n\nconst conjuncts = (node: FilterExpr): FilterExpr[] => (node.kind === 'and' ? node.args.flatMap(conjuncts) : [node])\n\n/** Takes the `related()` terms ANDed at the top of a filter out of it, leaving the rest as it was written when there are none. */\nexport const splitRelated = (ast: FilterExpr) => {\n const parts = conjuncts(ast)\n const terms = parts.filter((part): part is RelatedFilter => part.kind === 'related')\n if (terms.length === 0) return { terms, rest: ast }\n const others = parts.filter((part) => part.kind !== 'related')\n const rest: FilterExpr | undefined = others.length < 2 ? others[0] : { kind: 'and', args: others, span: ast.span }\n return { terms, rest }\n}\n\nconst nested = (node: FilterExpr, inGroup: boolean, depth: number): Array<{ term: RelatedFilter; inGroup: boolean; depth: number }> => {\n switch (node.kind) {\n case 'and':\n return node.args.flatMap((arg) => nested(arg, inGroup, depth))\n case 'or':\n return node.args.flatMap((arg) => nested(arg, true, depth))\n case 'not':\n return nested(node.arg, true, depth)\n case 'related':\n return [{ term: node, inGroup, depth }, ...(node.filter ? nested(node.filter, false, depth + 1) : [])]\n default:\n return []\n }\n}\n\n/** What is wrong with where the `related()` terms of a filter stand and how many there are, whatever they name. */\nexport const relatedErrors = (ast: FilterExpr): FilterError[] => {\n const terms = nested(ast, false, 1)\n const misplaced = terms.filter(({ inGroup }) => inGroup).map(({ term }) => relatedRefused(term.span))\n const deep = terms.filter(({ depth }) => depth > maxRelatedDepth).map(({ term }) =>\n filterError('too-deep', `related() nests at most ${maxRelatedDepth} levels deep`, 'Read the deeper level first, or filter a resource closer to it', term.span))\n const many = terms.length > maxRelatedTerms\n ? [filterError('unsupported', `A filter holds at most ${maxRelatedTerms} related() terms`, 'Narrow it with fewer terms', terms[maxRelatedTerms]!.term.span)]\n : []\n return [...misplaced, ...deep, ...many]\n}\n","import type {\n CheckedFilter, CompareOp, FieldModel, FieldPath, FilterError, FilterExpr, FilterValue, Literal, ResourceModel, Span,\n} from '../model'\nimport { checkValue } from './check-value'\nimport { resolveField, type CheckContext } from './check-field'\nimport { filterError } from './errors'\nimport { compareOps, isOpaque } from './operators'\nimport { relatedRefused } from './related'\n\nconst value = (ctx: CheckContext, field: FieldModel, node: FilterValue) => {\n const problem = checkValue(field, node)\n if (problem) ctx.errors.push(filterError('invalid-value', problem.message, problem.hint, node.span))\n return !problem\n}\n\nconst operatorError = (ctx: CheckContext, message: string, hint: string, span: Span) => {\n ctx.errors.push(filterError('operator-not-allowed', message, hint, span))\n}\n\nconst isWildcard = (op: CompareOp, node: FilterValue) =>\n (op === '=' || op === '!=') && node.kind === 'string' && node.value.includes('*')\n\nconst checkCompare = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'compare' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n const allowed = compareOps(field.type)\n if (!allowed.includes(node.op)) {\n operatorError(\n ctx,\n `Operator \"${node.op}\" is not supported for ${field.type} fields`,\n allowed.length ? `Supported: ${allowed.join(' ')}` : 'Use field:value on json fields, or isNull(field)',\n node.span,\n )\n return undefined\n }\n if (isWildcard(node.op, node.value) && field.type !== 'text') {\n ctx.errors.push(\n filterError('wildcard-not-allowed', `Wildcards are only supported on text fields, not ${field.type}`, 'Remove the \"*\" or filter a text field', node.value.span),\n )\n return undefined\n }\n if (!isWildcard(node.op, node.value) && !value(ctx, field, node.value)) return undefined\n return { ...node, field }\n}\n\nconst checkHas = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'has' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n if (field.type !== 'json') {\n operatorError(ctx, `\":\" is only supported on json fields, not ${field.type}`, `Use = on ${field.type} fields, or field:* to test for a value`, node.span)\n return undefined\n }\n return { ...node, field }\n}\n\nconst checkIn = (ctx: CheckContext, node: Extract<FilterExpr, { kind: 'in' }>) => {\n const field = resolveField(ctx, node.field, 'filterable')\n if (!field) return undefined\n if (isOpaque(field.type)) {\n operatorError(ctx, `in() is not supported for ${field.type} fields`, 'Use field:value on json fields', node.span)\n return undefined\n }\n const valid = node.values.map((literal: Literal) => value(ctx, field, literal))\n return valid.every(Boolean) ? { ...node, field } : undefined\n}\n\nconst checkText = (ctx: CheckContext, name: string, path: FieldPath) => {\n const field = resolveField(ctx, path, 'filterable')\n if (field && field.type !== 'text') {\n operatorError(ctx, `${name}() only works on text fields, not ${field.type}`, `Field \"${field.name}\" is ${field.type}`, path.span)\n return undefined\n }\n return field\n}\n\nconst checkNode = (ctx: CheckContext, node: FilterExpr): CheckedFilter | undefined => {\n switch (node.kind) {\n case 'and':\n case 'or': {\n const args = node.args.map((arg) => checkNode(ctx, arg))\n return args.every((arg) => arg) ? { ...node, args: args as CheckedFilter[] } : undefined\n }\n case 'not': {\n const arg = checkNode(ctx, node.arg)\n return arg && { ...node, arg }\n }\n case 'compare':\n return checkCompare(ctx, node)\n case 'has':\n return checkHas(ctx, node)\n case 'in':\n return checkIn(ctx, node)\n case 'search':\n if (ctx.model.search?.length) return node\n ctx.errors.push(filterError('no-search-fields', 'This resource has no search fields', 'Declare them with .search((r) => [r.title]) in data.ts', node.span))\n return undefined\n case 'present':\n case 'isNull': {\n const field = resolveField(ctx, node.field, 'filterable')\n return field && { ...node, field }\n }\n case 'similar':\n case 'regex': {\n const field = checkText(ctx, node.kind, node.field)\n return field && { ...node, field }\n }\n case 'related':\n ctx.errors.push(relatedRefused(node.span))\n return undefined\n }\n}\n\nexport const checkAgainstModel = (model: ResourceModel, ast: FilterExpr) => {\n const ctx: CheckContext = { model, errors: [] }\n const filter = checkNode(ctx, ast)\n if (!filter || ctx.errors.length > 0) {\n return { ok: false, errors: [...ctx.errors].sort((a, b) => a.span.start - b.span.start) } as const\n }\n return { ok: true, filter } as const\n}\n","import { checkFilter as check } from 'aip-parsers/filter'\nimport type { CheckedFilter, FilterError, FilterExpr, ResourceModel } from '../model'\nimport { checkAgainstModel } from './check-model'\nimport { lift } from './lift'\nimport { schemaOf } from './profile'\n\n/** What `checkFilter` gives: the filter with each field resolved to its model, or the errors. */\nexport type CheckResult =\n | {\n /** The filter is valid for the resource. */\n ok: true\n /** The filter, each field resolved to the resource's field model. */\n filter: CheckedFilter\n }\n | {\n /** The filter is not valid for the resource. */\n ok: false\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/**\n * Validates against the resource: the library checks fields, aliases, filterability, enum\n * values, operators and function signatures; the model pass then checks the value formats the\n * library cannot know (decimal, bigint, uuid, date, ...), traversal and search fields.\n */\nexport const checkFilter = (model: ResourceModel, ast: FilterExpr): CheckResult => {\n const traversal = checkAgainstModel(model, ast)\n if (!traversal.ok && traversal.errors.some((e) => e.code === 'unsupported-traversal')) return traversal\n const generic = check(lift(ast), schemaOf(model))\n if (!generic.ok) return { ok: false, errors: generic.errors }\n return checkAgainstModel(model, ast)\n}\n","import { checkOrderBy as check, parseOrderBy as parse, printOrderBy as print } from 'aip-parsers/order-by'\nimport type { FilterError, OrderByItem, ResourceModel, SortSpec } from '../model'\nimport { filterError } from './errors'\nimport { schemaOf } from './profile'\n\n/** What `parseOrderBy` gives: the order's items, or the errors. */\nexport type OrderByParse =\n | {\n /** The text parsed. */\n ok: true\n /** The fields to sort on, in order. */\n items: OrderByItem[]\n /** None. */\n errors: []\n }\n | {\n /** The text did not parse. */\n ok: false\n /** The items that parsed. */\n items: OrderByItem[]\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\n/** What `checkOrderBy` gives: the sort, or the errors. */\nexport type OrderByCheck =\n | {\n /** The order is valid for the resource. */\n ok: true\n /** The fields to sort on and their directions, in order. */\n sort: SortSpec\n }\n | {\n /** The order is not valid for the resource. */\n ok: false\n /** Each problem, with where it is in the text. */\n errors: FilterError[]\n }\n\nconst generic = (items: OrderByItem[]) => items.map((item) => ({ path: item.path.path, direction: item.direction, span: item.span }))\n\n// The library accepts only lowercase asc/desc; Protobase also accepts any case. The rewrite keeps\n// offsets, and leaves a first word (the field name) alone.\nconst lowercaseDirections = (source: string) =>\n source.replace(/([^\\s,])(\\s+)(asc|desc)(?=\\s|,|$)/gi, (_, before: string, space: string, word: string) => `${before}${space}${word.toLowerCase()}`)\n\n/** Parses order text, AIP-132 as the API's `order_by` takes it, such as `created_at desc, name`; `asc` and `desc` in any case. */\nexport const parseOrderBy = (source: string): OrderByParse => {\n const parsed = parse(lowercaseDirections(source))\n const items: OrderByItem[] = parsed.items.map((item) => ({\n path: { kind: 'field', path: item.path, span: item.span },\n direction: item.direction,\n span: item.span,\n }))\n return parsed.ok ? { ok: true, items, errors: [] } : { ok: false, items, errors: parsed.errors }\n}\n\n/** The order as text, as `parseOrderBy` reads it. */\nexport const printOrderBy = (items: OrderByItem[]) => print(generic(items))\n\n/** Validates against sortable fields. <gap>An order cannot sort on fields of related resources, as traversal is not supported yet.</gap> */\nexport const checkOrderBy = (model: ResourceModel, items: OrderByItem[]): OrderByCheck => {\n const traversal = items\n .filter((item) => item.path.path.length > 1)\n .map((item) => filterError('unsupported-traversal', `Traversal into \"${item.path.path.join('.')}\" is not supported yet`, 'Sort on fields of this resource only', item.path.span))\n if (traversal.length > 0) return { ok: false, errors: traversal }\n const checked = check(generic(items), schemaOf(model))\n if (!checked.ok) return { ok: false, errors: checked.errors }\n return { ok: true, sort: checked.items.map((item) => [item.path[0]!, item.direction]) }\n}\n","import type { DurationLiteral, DurationUnit } from '../model'\n\nexport const parseDurationText = (text: string): DurationLiteral => {\n const match = /^(\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)([smhdw])$/.exec(text)\n if (!match) throw new Error(`Invalid duration \"${text}\", expected for example 30d or 1.5h`)\n return {\n kind: 'duration',\n amount: Number(match[1]),\n unit: match[2] as DurationUnit,\n span: { start: 0, end: 0 },\n }\n}\n","import type { FieldPath, FilterExpr, FilterValue, Literal, Span } from '../model'\nimport type { Field } from '../field'\nimport type { RecordOf } from '../resource-types'\nimport { parseDurationText } from './duration'\n\n/** @inline */\ntype Scalar = string | number | boolean\n/** @inline */\ntype Source = {\n /** The resource's fields, as `resource(...)` declares them. */\n readonly $fields: unknown\n}\n/** @inline */\ntype Fields<R extends Source> = keyof RecordOf<R['$fields']> & string\n/** @inline */\ntype Value<R extends Source, K extends Fields<R>> =\n | Extract<NonNullable<RecordOf<R['$fields']>[K]>, Scalar>\n | FilterValue\n/** @inline */\ntype Anything = {\n /** Any fields: names and values are not checked. */\n readonly $fields: Record<string, Field<any>>\n}\n\n/** @inline */\ntype RelatedPage =\n | {\n /** The order the related records are read in, as a list's `order_by`; `''` for the list's default. */\n orderBy: string\n /** A page token needs a limit: the page size it was read with. */\n pageToken?: never\n }\n | {\n /** The order the related records are read in, as a list's `order_by`; `''` for the list's default. */\n orderBy: string\n /** How many of them, in that order. */\n limit: number\n /** Which page of them, a `next_page_token` of their list. */\n pageToken?: string\n }\n\nconst span: Span = { start: 0, end: 0 }\nconst field = (name: string): FieldPath => ({ kind: 'field', path: name.split('.'), span })\n\nconst literal = (value: Scalar): Literal => {\n if (typeof value === 'string') return { kind: 'string', value, span }\n if (typeof value === 'boolean') return { kind: 'boolean', value, span }\n if (!Number.isFinite(value)) throw new Error('Filter numbers must be finite')\n return { kind: 'number', value, raw: String(value), span }\n}\n\nconst filterValue = (value: Scalar | FilterValue): FilterValue =>\n typeof value === 'object' ? value : literal(value)\n\nconst group = (kind: 'and' | 'or', args: FilterExpr[]): FilterExpr => {\n if (args.length === 0) throw new Error(`where.${kind} needs at least one filter`)\n if (args.length === 1) return args[0]!\n return { kind, args, span }\n}\n\n/**\n * Builds filters in code, for the client and the UI, as `where` does, with field names and values typed against the\n * resource `R`: `createWhere<typeof orders>().eq('status', 'paid')`. A filter it builds prints as filter text with\n * `printFilter`.\n */\nexport const createWhere = <R extends Source = Anything>() => {\n const compare =\n (op: '=' | '!=' | '<' | '<=' | '>' | '>=') =>\n <K extends Fields<R>>(name: K, value: Value<R, K>): FilterExpr => ({\n kind: 'compare',\n op,\n field: field(name),\n value: filterValue(value),\n span,\n })\n const offset = (sign: '+' | '-') => (duration: string): FilterValue => ({\n kind: 'now',\n offset: { sign, duration: parseDurationText(duration) },\n span,\n })\n\n return {\n /** The field equals the value: `status = \"paid\"`. */\n eq: compare('='),\n /** The field differs from the value: `status != \"paid\"`. */\n ne: compare('!='),\n /** The field is below the value: `total < 100`. */\n lt: compare('<'),\n /** The field is at most the value: `total <= 100`. */\n lte: compare('<='),\n /** The field is above the value: `total > 100`. */\n gt: compare('>'),\n /** The field is at least the value: `total >= 100`. */\n gte: compare('>='),\n /** The field lies from `low` to `high`, both included. */\n between: <K extends Fields<R>>(name: K, low: Value<R, K>, high: Value<R, K>) =>\n group('and', [compare('>=')(name, low), compare('<=')(name, high)]),\n /** A JSON field holds the value, as a key or an element: `tags:\"urgent\"`. */\n has: <K extends Fields<R>>(name: K, value: Scalar) =>\n ({ kind: 'has', field: field(name), value: literal(value), span }) as FilterExpr,\n /** The field has a value, a JSON field one other than `null`: `field:*`. */\n present: <K extends Fields<R>>(name: K) => ({ kind: 'present', field: field(name), span }) as FilterExpr,\n /** The field equals one of the values: `in(status, \"paid\", \"sent\")`. */\n in: <K extends Fields<R>>(name: K, values: Extract<NonNullable<RecordOf<R['$fields']>[K]>, Scalar>[]) =>\n ({ kind: 'in', field: field(name), values: values.map(literal), span }) as FilterExpr,\n /** The field has no value: `isNull(field)`. */\n isNull: <K extends Fields<R>>(name: K) => ({ kind: 'isNull', field: field(name), span }) as FilterExpr,\n /** Every word of the text appears, ignoring case, in one of the resource's search fields: `search(\"text\")`. */\n search: (text: string): FilterExpr => ({ kind: 'search', text, span }),\n /** The text field is close to the text by trigram similarity, typos included: `similar(field, \"text\")`. */\n similar: <K extends Fields<R>>(name: K, text: string) =>\n ({ kind: 'similar', field: field(name), text, span }) as FilterExpr,\n /** The text field matches the regular expression, ignoring case: `regex(field, \"pattern\")`. */\n regex: <K extends Fields<R>>(name: K, pattern: string) =>\n ({ kind: 'regex', field: field(name), pattern, span }) as FilterExpr,\n /**\n * The field holds the `key` of a record of `resource` the caller may list that meets `filter`, in a list-style read\n * of the API: `related(task_id, objective_tasks.task_id, (objective_id = 40))`. `page` keeps to one page of those\n * records, as a list of `resource` reads it: `{ orderBy: 'created_at desc', limit: 10, pageToken }`.\n */\n related: <K extends Fields<R>>(name: K, resource: string, key: string, filter?: FilterExpr, page?: RelatedPage): FilterExpr =>\n ({ kind: 'related', field: field(name), resource, key, ...(filter && { filter }), ...page, span }),\n /** Every filter holds; one filter is returned as it is, none throws. */\n and: (...args: FilterExpr[]) => group('and', args),\n /** At least one filter holds; one filter is returned as it is, none throws. */\n or: (...args: FilterExpr[]) => group('or', args),\n /** The filter does not hold. */\n not: (arg: FilterExpr): FilterExpr => ({ kind: 'not', arg, span }),\n /** The current time, as a value to compare with: `now()`. */\n now: (): FilterValue => ({ kind: 'now', span }),\n /** A time the duration before now, such as `ago('7d')` for `now() - 7d`; units are `s`, `m`, `h`, `d` and `w`. */\n ago: offset('-'),\n /** A time the duration after now, such as `fromNow('1h')` for `now() + 1h`. */\n fromNow: offset('+'),\n }\n}\n\n/**\n * Builds a filter in code instead of writing filter text, for any resource; `createWhere` checks names and values\n * against one. The [Filters](docs/website/src/content/docs/reference/api.md#filters) of the API take what it builds.\n *\n * @example\n * ```ts\n * where.and(where.eq('status', 'paid'), where.gte('created_at', where.ago('30d')))\n * ```\n */\nexport const where = createWhere()\n","import type { AnyField, Field } from './field'\n\n/** The fields of `.fields({ ... })` by name; `null` ignores a column on purpose. */\nexport type FieldsInput = Record<string, AnyField | null>\n\nexport type ActiveFields<F> = { [K in keyof F as F[K] extends null ? never : K]: F[K] }\n\n/** A field picked in a builder's callback, such as `r.status`: its name, typed with its value. */\nexport type Ref<N extends string = string, V = unknown> = {\n /** The field's name. */\n readonly name: N\n /** The field's value type, for the compiler only; never set. */\n readonly $value?: V\n}\n\n/** A reference per field of `F`, by name. */\nexport type Refs<F> = {\n readonly [K in keyof F & string]: F[K] extends Field<infer V> ? Ref<K, V> : never\n}\n\n/** The `r` of a builder's callback: a reference per field of `F`, the ignored (`null`) ones left out. */\nexport type FieldRefs<F> = Refs<ActiveFields<F>>\n\nconst refMark = Symbol('protobase.ref')\n\n/** A field reference as a view builder hands it out (`r.status`), recognisable wherever it is passed, props included. */\nexport const ref = (name: string): Ref => Object.defineProperty({ name }, refMark, { value: true })\n\nexport const isRef = (value: unknown): value is Ref => typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[refMark] === true\n\n// Records the accessed field name; with `known`, unknown names throw at runtime.\nexport const createRefs = <R>(make: (name: string) => unknown, known?: readonly string[]) =>\n new Proxy(\n {},\n {\n get: (_, name) => {\n if (typeof name === 'symbol') return undefined\n if (known && !known.includes(name)) throw new Error(`Unknown field \"${name}\"`)\n return make(name)\n },\n },\n ) as R\n","import type { JsonValue } from './model'\nimport { isRef } from './refs'\n\n/**\n * A field named inside free-form data, such as a custom component's props: `{ $field: 'status' }`, or a path through\n * relations (`plan.name`) on a page. Marked, so that the walker leaving out hidden fields finds it wherever it is.\n */\nexport type FieldRefValue = {\n /** The field's name, or a path through relations. */\n readonly $field: string\n}\n\n/** A field reference for a layout's custom component props, such as `<UsageChart field={fieldRef('total')} />`. */\nexport const fieldRef = (path: string): FieldRefValue => ({ $field: path })\n\nexport const isFieldRef = (value: unknown): value is FieldRefValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && typeof (value as FieldRefValue).$field === 'string'\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Props as a view stores them: every `r.field` in them, at any depth, becomes a field reference. */\nexport const markFieldRefs = (value: unknown): JsonValue => {\n if (isRef(value)) return fieldRef(value.name)\n if (Array.isArray(value)) return value.map(markFieldRefs)\n if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, markFieldRefs(entry)]))\n return value as JsonValue\n}\n\n/** Props as a custom component gets them: every field reference as its field's name. */\nexport const unmarkFieldRefs = <T>(value: T): T => {\n if (isFieldRef(value)) return value.$field as T\n if (Array.isArray(value)) return value.map(unmarkFieldRefs) as T\n if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, unmarkFieldRefs(entry)])) as T\n return value\n}\n\n/** Every field the value names through field references, at any depth. */\nexport const fieldRefsIn = (value: unknown): string[] => {\n if (isFieldRef(value)) return [value.$field]\n if (Array.isArray(value)) return value.flatMap(fieldRefsIn)\n if (isObject(value)) return Object.values(value).flatMap(fieldRefsIn)\n return []\n}\n","import { fieldRefsIn, markFieldRefs } from './field-ref'\nimport type { CardFavoriteModel, CardPhotosModel, JsonValue, ListDisplayModel, RelatedColumnModel, ResourceModel } from './model'\nimport type { Ref } from './refs'\nimport type { ListColumn } from './view-columns'\n\n/** A custom component as `component(name)` from `@protobase/layout` declares it. */\nexport type ComponentRef<P> = ((props: P) => unknown) & {\n /** The name it is registered under. */\n readonly blockName: string\n /** Whether it is the project's or a plugin's, rather than a built-in block. */\n readonly custom: boolean\n}\n\n/** A custom component's props as a view gives them: plain data, or `r.field` where it takes a field's name. */\nexport type ViewProps<P> = { [K in keyof Omit<P, 'children'>]: P[K] extends string ? P[K] | Ref : P[K] }\n\n/** @inline */\ntype Naming = { name?: string; label?: string; icon?: string }\n\nconst naming = ({ label, icon }: Naming) => ({ ...(label !== undefined && { label }), ...(icon !== undefined && { icon }) })\n\n/** The most photos a card steps through, its own image among them, each marked by a dot: a list includes this many of each record's photos. */\nexport const cardPhotoLimit = 10\n\n/** The name of the list's own display, which every list has. */\nexport const tableDisplay = 'table'\n\n/** The component of a custom display or section, which must be a project's, not a built-in block. */\nexport const customComponent = (component: ComponentRef<never>, where: string) => {\n if (!component.custom) throw new Error(`${where} takes a component declared with component(...), not the built-in block ${component.blockName}`)\n return component.blockName\n}\n\nexport const displays = {\n /**\n * A card per record: `image`, a file field shown as a picture across the card's top, then `title` (default: the\n * view's title) over `subtitle`, `badge` drawn as a badge with its value labels, `amount` the first of its fields with a\n * value in bold, such as a purchase price or a rent, `code` its value in full as a block of monospaced text that wraps,\n * such as a shell command, and a few small `meta` fields such as dates. `footer` is a line at\n * the card's bottom of its fields with a value, joined by bullets. `flags` are boolean fields shown as small badges of their labels when true, such as a garden or parking.\n * `dots` are related columns of the list (`c.related`), each a line of its dots under the rest of the card, with the\n * colours, order and hover cards they have in the table; a column with no records for the row shows no line.\n * With `card`, a component of the project or a plugin draws each card's content instead, from the row of those\n * fields (`{ row }`); without it, or when it throws, the card is the built-in one. With `photos`, the built-in card's\n * picture gets arrows through the `image` of the records of another resource that point at the card's record, after\n * its own `image`, ten pictures at most; they come with the list's records, so its dots mark the one shown from the\n * start. A list's cards displays name the same `photos`. With `favorite`, a heart in the card's top right corner saves\n * the record to the signed-in user's own records of another resource, such as favorites, and takes it off again; a\n * visitor who is not signed in is told why to sign in. Named `cards` unless `name` says otherwise.\n */\n cards: (\n fields: { image?: Ref; title?: Ref; subtitle?: Ref; amount?: Ref[]; badge?: Ref; code?: Ref; meta?: Ref[]; footer?: Ref[]; flags?: Ref[]; dots?: ListColumn[] },\n o: Naming & { card?: ComponentRef<never>; photos?: CardPhotosModel; favorite?: CardFavoriteModel } = {},\n ): ListDisplayModel => ({\n kind: 'cards',\n name: o.name ?? 'cards',\n ...naming(o),\n ...(fields.image && { image: fields.image.name }),\n ...(fields.title && { title: fields.title.name }),\n ...(fields.subtitle && { subtitle: fields.subtitle.name }),\n ...(fields.amount && { amount: fields.amount.map((ref) => ref.name) }),\n ...(fields.badge && { badge: fields.badge.name }),\n ...(fields.code && { code: fields.code.name }),\n ...(fields.meta && { meta: fields.meta.map((ref) => ref.name) }),\n ...(fields.footer && { footer: fields.footer.map((ref) => ref.name) }),\n ...(fields.flags && { flags: fields.flags.map((ref) => ref.name) }),\n ...(fields.dots && { dots: fields.dots.map((column) => column.name) }),\n ...(o.card && { card: customComponent(o.card, 'd.cards card') }),\n ...(o.photos && { photos: { ...o.photos } }),\n ...(o.favorite && { favorite: { ...o.favorite } }),\n }),\n /**\n * A map of the records at their `latitude` and `longitude`, filterable fields in decimal degrees, drawn with the app's\n * map style. It asks for the records in its view as it pans and zooms: from far out a count for each part of the map,\n * which zooms in when chosen, closer in the records. A marker stands for the records that lie close together at the\n * zoom; choosing it shows their card at the map's bottom, with arrows through them. The card is the one of the cards display named `cards`, the list's first cards display\n * when it names none, or the record's title alone without one. A record's position is approximate when its boolean\n * `approximate` field is true, or its `exact` field false: its marker is drawn hollow and says so, and close enough in\n * an area is drawn around it, the GeoJSON polygon or line its `area` field holds, else a circle of its `radius` field\n * in metres, else one of `defaultRadius`. Named `map` unless `name` says otherwise. See\n * [Approximate positions](docs/website/src/content/docs/reference/ui-config.mdx#approximate-positions).\n */\n map: (\n fields: { latitude: Ref; longitude: Ref; approximate?: Ref; exact?: Ref; radius?: Ref; area?: Ref },\n o: Naming & { cards?: string; defaultRadius?: number } = {},\n ): ListDisplayModel => ({\n kind: 'map',\n name: o.name ?? 'map',\n ...naming(o),\n latitude: fields.latitude.name,\n longitude: fields.longitude.name,\n ...(o.cards !== undefined && { cards: o.cards }),\n ...(fields.approximate && { approximate: fields.approximate.name }),\n ...(fields.exact && { exact: fields.exact.name }),\n ...(fields.radius && { radius: fields.radius.name }),\n ...(o.defaultRadius !== undefined && { defaultRadius: o.defaultRadius }),\n ...(fields.area && { area: fields.area.name }),\n }),\n /**\n * A column per value of the enum field `by`, in the order the field lists them, each headed by its value label and how\n * many of the list's records have it; with a column for records without a value when the field may be empty. Each\n * column pages through the list API with the list's filter and search, its value added, in the list's order. A card\n * shows `title` (default: the view's title) over `subtitle`, with `badge` and a few small `meta` fields, as the built-in\n * card of `d.cards` does, and opens the record. With the list's `drag: { board: true }`, dragging a card to another\n * column, or picking it up with Space and moving it with the arrow keys, saves the record with `by` set to that\n * column's value, as one update with its ETag, so the resource's access rules and `validate` decide, and a refusal\n * puts the card back and says why; with `drag: { board: 'name' }` only between the columns the UI config's board drop\n * of that name lists, each running its own write; with `drag: { rank: true }` a card moves within its column too. `by` must be\n * a filterable enum field. Named `board` unless `name` says otherwise. See\n * [Boards](docs/website/src/content/docs/reference/ui-config.mdx#boards).\n */\n board: (fields: { by: Ref; title?: Ref; subtitle?: Ref; badge?: Ref; meta?: Ref[] }, o: Naming = {}): ListDisplayModel => ({\n kind: 'board',\n name: o.name ?? 'board',\n ...naming(o),\n by: fields.by.name,\n ...(fields.title && { title: fields.title.name }),\n ...(fields.subtitle && { subtitle: fields.subtitle.name }),\n ...(fields.badge && { badge: fields.badge.name }),\n ...(fields.meta && { meta: fields.meta.map((ref) => ref.name) }),\n }),\n /**\n * The records on the days from `start` to `end` (or on their start day alone), in a month grid of whole weeks or a\n * week grid, with weeks from Monday and days in UTC. It loads only the days shown through the list API, with the\n * list's filter and search, in start order. An event shows `title` (default: the view's title), after its time for a\n * timestamp, and opens the record. Dragging an event to another day, or picking it up with Space and moving it with\n * the arrow keys, saves the record with `start` and `end` moved by the same days, as one update with its ETag, so the\n * resource's access rules and `validate` decide, and a refusal puts the event back and says why. `start` must be a\n * filterable date or timestamp field and `end` a filterable field of the same type. Named `calendar` unless `name`\n * says otherwise. See [Calendars](docs/website/src/content/docs/reference/ui-config.mdx#calendars).\n */\n calendar: (fields: { start: Ref; end?: Ref; title?: Ref }, o: Naming = {}): ListDisplayModel => ({\n kind: 'calendar',\n name: o.name ?? 'calendar',\n ...naming(o),\n start: fields.start.name,\n ...(fields.end && { end: fields.end.name }),\n ...(fields.title && { title: fields.title.name }),\n }),\n /**\n * The records as bars from the day of `start` to the day of `end` (or their start day alone), one row each, over a\n * week, a month or a quarter, in lanes by the values of `group`, with weeks from Monday. It loads only the days shown\n * through the list API, with the list's filter and search, in start order, as a calendar does. A bar shows `title`\n * (default: the view's title) and opens the record. Dragging a bar along its row, or picking it up with Space and\n * moving it with the arrow keys, saves the record with `start` and `end` moved by the same days, as one update with\n * its ETag, so the resource's access rules and `validate` decide, and a refusal puts the bar back and says why.\n * `start` must be a filterable date or timestamp field and `end` a filterable field of the same type. Named\n * `timeline` unless `name` says otherwise. See [Timelines](docs/website/src/content/docs/reference/ui-config.mdx#timelines).\n */\n timeline: (fields: { start: Ref; end?: Ref; group?: Ref; title?: Ref }, o: Naming = {}): ListDisplayModel => ({\n kind: 'timeline',\n name: o.name ?? 'timeline',\n ...naming(o),\n start: fields.start.name,\n ...(fields.end && { end: fields.end.name }),\n ...(fields.group && { group: fields.group.name }),\n ...(fields.title && { title: fields.title.name }),\n }),\n /**\n * The list drawn by a component of the project, registered in `protobase.ui.tsx` under its name. It gets `props` and\n * reads the rows with `useListDisplay()`; `fields` are the fields it shows, fetched with relation names.\n */\n custom: <P extends object>(component: ComponentRef<P>, o: Naming & { name: string; label: string; fields: Ref[]; props?: ViewProps<P> }): ListDisplayModel => ({\n kind: 'custom',\n name: o.name,\n label: o.label,\n ...naming({ icon: o.icon }),\n component: customComponent(component as ComponentRef<never>, 'd.custom'),\n fields: o.fields.map((ref) => ref.name),\n ...(o.props && { props: markFieldRefs(o.props) as Record<string, JsonValue> }),\n }),\n}\n\nconst displayName = /^[a-z][a-zA-Z0-9-]*$/\n\n/** What is wrong with a list's displays and default, by their names alone. */\nexport const displayErrors = (list: { displays?: ListDisplayModel[]; default?: string; relatedColumns?: RelatedColumnModel[] }): string[] => {\n const names = (list.displays ?? []).map((display) => display.name)\n return [\n ...names.filter((name) => !displayName.test(name)).map((name) => `display name \"${name}\" must start with a lowercase letter and hold only letters, digits and dashes`),\n ...names.filter((name) => name === tableDisplay).map(() => `\"${tableDisplay}\" is the list's own display; give the display another name`),\n ...names.filter((name, index) => names.indexOf(name) !== index).map((name) => `display \"${name}\" is defined twice`),\n ...(list.displays ?? []).flatMap((display) =>\n display.kind === 'map' && display.cards !== undefined && !list.displays!.some((other) => other.kind === 'cards' && other.name === display.cards)\n ? [`display \"${display.name}\" names cards \"${display.cards}\", which is not a cards display of the list`]\n : [],\n ),\n ...(list.displays ?? []).flatMap((display) =>\n display.kind === 'cards'\n ? (display.dots ?? []).filter((name) => !list.relatedColumns?.some((column) => column.name === name)).map((name) => `display \"${display.name}\" shows dots of \"${name}\", which is not a related column of the list`)\n : [],\n ),\n ...(list.displays ?? []).flatMap((display) => (display.kind === 'map' ? approximateErrors(display).map((error) => `display \"${display.name}\": ${error}`) : [])),\n ...(list.default === undefined || list.default === tableDisplay || names.includes(list.default) ? [] : [`default \"${list.default}\" is not one of the displays (${[tableDisplay, ...names].join(', ')})`]),\n ]\n}\n\n// An area surrounds an approximate position, so it needs the field that says which positions are.\nconst approximateErrors = (display: Extract<ListDisplayModel, { kind: 'map' }>) => {\n const { approximate, exact, radius, defaultRadius, area } = display\n if (approximate !== undefined && exact !== undefined) return ['name approximate or exact, not both']\n const surrounds = radius !== undefined || defaultRadius !== undefined || area !== undefined\n return [\n ...(surrounds && approximate === undefined && exact === undefined ? ['an area around approximate positions needs the approximate or exact field'] : []),\n ...(defaultRadius === undefined || (Number.isFinite(defaultRadius) && defaultRadius > 0) ? [] : [`defaultRadius ${defaultRadius} is not a number of metres above 0`]),\n ]\n}\n\n/** What makes a board unable to put the records in columns: a `by` field that is no filterable enum. */\nexport const boardErrors = (display: Extract<ListDisplayModel, { kind: 'board' }>, model: ResourceModel): string[] => {\n const field = Object.hasOwn(model.fields, display.by) ? model.fields[display.by]! : undefined\n // An unknown field is reported with every display's fields\n if (!field) return []\n if (field.type !== 'enum') return [`\"${display.by}\" on ${model.name} is ${field.type}, not an enum, whose values are the board's columns`]\n return field.filterable ? [] : [`\"${display.by}\" on ${model.name} is not filterable, and each column of the board filters by its value`]\n}\n\n/** What makes a calendar or a timeline unable to place the records on days: a `start` that is no filterable date or timestamp, or an `end` that is no filterable field of its type. */\nexport const datesErrors = (display: Extract<ListDisplayModel, { kind: 'calendar' | 'timeline' }>, model: ResourceModel): string[] => {\n const known = (name: string) => (Object.hasOwn(model.fields, name) ? model.fields[name]! : undefined)\n const start = known(display.start)\n const end = display.end === undefined ? undefined : known(display.end)\n // An unknown field is reported with every display's fields\n if (!start) return []\n if (start.type !== 'date' && start.type !== 'timestamp') return [`start \"${display.start}\" on ${model.name} is ${start.type}, not a date or timestamp`]\n const unfilterable = (name: string) => `${name === display.start ? 'start' : 'end'} \"${name}\" on ${model.name} is not filterable, and the ${display.kind} filters by it for the days it shows`\n return [\n ...(start.filterable ? [] : [unfilterable(display.start)]),\n ...(end && end.type !== start.type ? [`end \"${display.end}\" on ${model.name} is ${end.type}, not ${start.type} like start \"${display.start}\"`] : []),\n ...(end && end.type === start.type && !end.filterable ? [unfilterable(display.end!)] : []),\n ]\n}\n\n/** Every field a display names: what it shows, a map's position and the fields saying how exact it is, a board's columns, a calendar's dates, a timeline's dates and lanes, and the field references in a custom display's props. */\nexport const displayFields = (display: ListDisplayModel): string[] => {\n if (display.kind === 'map') return [display.latitude, display.longitude, display.approximate, display.exact, display.radius, display.area].filter((name): name is string => name !== undefined)\n if (display.kind === 'custom') return [...display.fields, ...fieldRefsIn(display.props)]\n if (display.kind === 'board') return [display.by, display.title, display.subtitle, display.badge, ...(display.meta ?? [])].filter((name): name is string => name !== undefined)\n if (display.kind === 'calendar') return [display.start, display.end, display.title].filter((name): name is string => name !== undefined)\n if (display.kind === 'timeline') return [display.start, display.end, display.group, display.title].filter((name): name is string => name !== undefined)\n return [display.image, display.title, display.subtitle, ...(display.amount ?? []), display.badge, display.code, ...(display.meta ?? []), ...(display.footer ?? []), ...(display.flags ?? [])].filter((name): name is string => name !== undefined)\n}\n","import type { ViewModel } from './model'\n\n/**\n * The view a list page shows: `view` itself, or, with `list`, the view with that named list's names, nav, help, list,\n * filters and chart in place of its own, and no named lists; none when the view has no list by that name.\n */\nexport const viewOfList = (view: ViewModel | undefined, list: string | undefined): ViewModel | undefined => {\n if (list === undefined) return view\n const named = view?.lists?.find((entry) => entry.name === list)\n if (!view || !named) return undefined\n const { list: _list, chart: _chart, help: _help, nav: _nav, lists: _lists, names: _names, ...rest } = view\n const { name: _name, ...parts } = named\n return { ...rest, ...parts }\n}\n","import { addressPlaceholders, embeddedFilterFields, filterField, resourceField } from './address-template'\nimport { checkFilter, checkOrderBy, parseFilter, parseOrderBy } from './filter'\nimport type { AppAddress, FilterErrorCode, ResourceModel } from './model'\n\nexport type AddressCheck = {\n /** The resources; against a caller's restricted models, the check says whether that caller can follow the link. */\n models: Record<string, ResourceModel>\n /** The composed pages; without them a page's name is not checked. */\n pages?: ReadonlySet<string>\n /** The resource of the record the link sits on, whose fields its `{{field}}` placeholders name. */\n source?: ResourceModel\n /** Why a placeholder's path cannot be filled, in place of `source`'s fields, such as a layout's lookup through the records around a link. */\n placeholderError?: (path: string) => string | undefined\n /** The resources whose view opens a create page of the app's own, which reads a create address's values whatever their names. */\n createPages?: ReadonlySet<string>\n /** A list's filter may be one `{{field}}`, the record's text, which whoever draws the link parses and checks against the caller's models, as a row button does. */\n filterFromRecord?: boolean\n}\n\n// Errors about names, not values: a placeholder's value is only known when the link is followed.\nconst nameErrors: readonly FilterErrorCode[] = ['unknown-field', 'not-filterable', 'not-sortable', 'unsupported-traversal', 'invalid-traversal']\n\n// A quoted placeholder stands in for a word and any other for a number, so the filter parses and its names can be checked.\nconst withSamples = (filter: string) => filter.replace(/([\"']?)\\{\\{\\s*[^{}]*?\\s*\\}\\}\\1/g, (_, quote: string) => (quote ? `${quote}x${quote}` : '0'))\n\nconst filterErrors = (model: ResourceModel, filter: string) => {\n const embedded = embeddedFilterFields(filter)\n if (embedded.length > 0) return embedded.map((name) => `filter: \"{{${name}}}\" sits inside a longer quoted value; quote it alone, such as title = \"{{${name}}}\"`)\n const parsed = parseFilter(withSamples(filter))\n if (!parsed.ok) return parsed.errors.map((error) => `filter: ${error.message}`)\n if (!parsed.ast) return []\n const checked = checkFilter(model, parsed.ast)\n return checked.ok ? [] : checked.errors.filter((error) => nameErrors.includes(error.code)).map((error) => `filter: ${error.message}`)\n}\n\nconst orderErrors = (model: ResourceModel, orderBy: string) => {\n if (addressPlaceholders({ kind: 'list', resource: model.name, orderBy }).length > 0) return []\n const parsed = parseOrderBy(orderBy)\n if (!parsed.ok) return parsed.errors.map((error) => `orderBy: ${error.message}`)\n const checked = checkOrderBy(model, parsed.items)\n return checked.ok ? [] : checked.errors.map((error) => `orderBy: ${error.message}`)\n}\n\n/**\n * What is wrong with a link's address against these models: an unknown resource or page, a filter, order or values\n * beside a resource taken from the record (`'{{field}}'`), but with `filterFromRecord` a filter that is one `{{field}}`, a `{{field}}` the record it sits\n * on does not have, a filter or order naming fields the resource does not have, or create values for fields it does not\n * have, unless its view opens a create page, which reads them. Empty when it can be followed.\n */\nexport const addressErrors = (to: AppAddress, { models, pages, source, placeholderError, createPages, filterFromRecord }: AddressCheck): string[] => {\n const placeholders = addressPlaceholders(to).flatMap((name) => {\n if (placeholderError) {\n const error = placeholderError(name)\n return error === undefined ? [] : [error]\n }\n if (!source) return [`\"{{${name}}}\" takes a value from the record, but the link sits on none`]\n return Object.hasOwn(source.fields, name) ? [] : [`\"{{${name}}}\" is not a field of ${source.name}`]\n })\n // A filter the record holds whole is known only when the link is drawn, which checks it then.\n const recordFilter = filterFromRecord === true && filterField(to) !== undefined\n // A resource taken from the record is known only when the link is followed, so the address names none of its fields.\n if (to.kind !== 'page' && resourceField(to) !== undefined) {\n const named = to.kind === 'list' ? (to.filter !== undefined && !recordFilter) || to.orderBy !== undefined : to.kind === 'create' && to.values !== undefined\n if (!named) return placeholders\n const allowed = filterFromRecord ? 'no order or values, and a filter only as one field, such as filter: \\'{{filter}}\\'' : 'no filter, order or values'\n return [...placeholders, `a link whose resource comes from the record (\"${to.resource}\") names ${allowed}`]\n }\n switch (to.kind) {\n case 'page':\n return pages && !pages.has(to.page) ? [...placeholders, `unknown page \"${to.page}\"`] : placeholders\n case 'list':\n case 'record':\n case 'create': {\n const target = Object.hasOwn(models, to.resource) ? models[to.resource] : undefined\n if (!target) return [`unknown resource \"${to.resource}\"`]\n if (to.kind === 'create' && createPages?.has(to.resource)) return placeholders\n if (to.kind === 'create') return [...placeholders, ...Object.keys(to.values ?? {}).filter((name) => !Object.hasOwn(target.fields, name)).map((name) => `values: unknown field \"${name}\" on ${to.resource}`)]\n if (to.kind !== 'list') return placeholders\n return [...placeholders, ...(to.filter && !recordFilter ? filterErrors(target, to.filter) : []), ...(to.orderBy ? orderErrors(target, to.orderBy) : [])]\n }\n default:\n return [`an address's kind is list, record, create or page, not \"${String((to as { kind: unknown }).kind)}\"`]\n }\n}\n","import { addressErrors, type AddressCheck } from './address-errors'\nimport { addressPlaceholders, hrefField, textPlaceholders } from './address-template'\nimport type { AppAddress, ResourceModel, RowButtonChoice, RowButtonModel } from './model'\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst shape = \"a row button is { label, to } or { label, href }, such as { label: 'Open', to: { kind: 'record', resource: 'tasks', key: '{{id}}' } } or { label: 'Report', href: '{{report_url}}' }, or a list of them\"\n\n/** A row button's choices, in order: the one it is, or each of its list. */\nexport const rowButtonChoices = (button: RowButtonModel): readonly RowButtonChoice[] => (Array.isArray(button) ? button : [button as RowButtonChoice])\n\n/** Where a choice goes: its `href` when it has one, as the check reads it, otherwise its address in `to`. */\nexport const rowButtonTarget = (choice: RowButtonChoice): { href: string } | { to: AppAddress } => {\n const href = (choice as { href?: string }).href\n return href === undefined ? { to: (choice as { to: AppAddress }).to } : { href }\n}\n\n/** The fields of the row a choice's label and address or href read; a row without a value for one of them skips it. */\nexport const rowButtonChoiceFields = (choice: RowButtonChoice) => {\n const target = rowButtonTarget(choice)\n return [...new Set([...textPlaceholders(choice.label), ...('href' in target ? textPlaceholders(target.href) : addressPlaceholders(target.to))])]\n}\n\n/** The fields of the row any of a button's choices reads, to load with the rows. */\nexport const rowButtonFields = (button: RowButtonModel) => [...new Set(rowButtonChoices(button).flatMap(rowButtonChoiceFields))]\n\nconst missing = (names: string[], source: ResourceModel, part: string) => names.flatMap((name) => (Object.hasOwn(source.fields, name) ? [] : [`${part}: \"{{${name}}}\" is not a field of ${source.name}`]))\n\nconst choiceErrors = (choice: unknown, source: ResourceModel, check: Omit<AddressCheck, 'source'>): string[] => {\n if (!isObject(choice)) return [shape]\n if (typeof choice.label !== 'string' || choice.label.trim() === '') return ['a row button needs a label']\n if (choice.to !== undefined && choice.href !== undefined) return ['a row button opens an address in `to` or an outside page in `href`, not both']\n const label = missing(textPlaceholders(choice.label), source, 'label')\n if (choice.href !== undefined) {\n const field = typeof choice.href === 'string' ? hrefField(choice.href) : undefined\n if (field === undefined) return [...label, \"href: a row button's href is the one field that holds the page's https URL, such as '{{report_url}}'\"]\n return [...label, ...missing([field], source, 'href')]\n }\n if (!isObject(choice.to) || typeof choice.to.kind !== 'string') return [\"a row button needs an address in `to`, such as { kind: 'record', resource: 'tasks', key: '{{id}}' }, or an outside page in `href`\"]\n return [...label, ...addressErrors(choice.to as AppAddress, { ...check, source, filterFromRecord: true }).map((error) => `to: ${error}`)]\n}\n\n/**\n * What is wrong with a row button on the rows of `source`: per choice, a missing label or target, both an address and an\n * href, an href that is not one `{{field}}`, a `{{field}}` the rows do not have, or an address that cannot be followed,\n * against `check`'s models; or a list without choices. Empty when every row can show it.\n */\nexport const rowButtonErrors = (button: unknown, source: ResourceModel, check: Omit<AddressCheck, 'source'>): string[] => {\n if (!Array.isArray(button)) return choiceErrors(button, source, check)\n if (button.length === 0) return ['a row button list needs at least one choice']\n return button.flatMap((choice, index) => choiceErrors(choice, source, check).map((error) => `choice ${index + 1}: ${error}`))\n}\n\n/**\n * `button` with only the choices a caller can follow against `check`'s restricted models, in order, so their rows fall\n * through to the next; none when no choice is left.\n */\nexport const followableRowButton = (button: RowButtonModel, source: ResourceModel, check: Omit<AddressCheck, 'source'>): RowButtonModel | undefined => {\n if (!Array.isArray(button)) return rowButtonErrors(button, source, check).length === 0 ? button : undefined\n const kept = rowButtonChoices(button).filter((choice) => choiceErrors(choice, source, check).length === 0)\n return kept.length === 0 ? undefined : kept\n}\n","import { enumLabel } from './enum-label'\nimport type { FieldModel, ResourceModel, ViewModel } from './model'\n\nconst labelCandidates = ['name', 'title', 'number', 'sku', 'email', 'code', 'description']\n\n// A sensitive field, write-only ones included, is in no list response, so it cannot name a record\nconst namesRecords = (field: FieldModel | undefined) => field?.type === 'text' && !field.sensitive\n\n/** The field that names a record when another record points at it. */\nexport const labelFieldOf = (model: ResourceModel, view?: ViewModel) =>\n view?.title ??\n labelCandidates.find((name) => namesRecords(model.fields[name])) ??\n Object.values(model.fields).find(namesRecords)?.name ??\n model.primaryKey[0]!\n\n/** What names a record: the view's `title`, else the first text column of its list, else `labelFieldOf`. */\nexport const recordTitleField = (model: ResourceModel, view: ViewModel | undefined) =>\n view?.title ?? view?.list?.columns.find((name) => model.fields[name]?.type === 'text') ?? labelFieldOf(model)\n\n/** A record's name as shown: its title field's value, an enum's by its label, else `fallback` when the value is missing. */\nexport const recordTitle = (model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, fallback: string) => {\n const name = recordTitleField(model, view)\n const value = record[name]\n if (value === null || value === undefined) return fallback\n return model.fields[name]?.type === 'enum' ? enumLabel(String(value), view?.fields[name]?.valueLabels) : String(value)\n}\n","import type { ResourceModel, ViewModel } from './model'\n\n/** The fields a view's list shows as columns: its list columns, else the resource's first six fields the caller reads. */\nexport const listColumnNames = (resource: ResourceModel, view: ViewModel | undefined) =>\n view?.list?.columns ?? Object.values(resource.fields).filter((field) => !field.writeOnly).slice(0, 6).map((field) => field.name)\n","import { createContext, useContext, useMemo, type ReactNode } from 'react'\n\nconst GuardedParamsContext = createContext<readonly string[]>([])\n\n/**\n * Content a change of the page parameter `name` replaces, such as the row a `select` chose: a navigation guard inside\n * it asks before that parameter changes, as before leaving the page.\n */\nexport const GuardedParams = ({ name, children }: { name: string; children: ReactNode }) => {\n const outer = useContext(GuardedParamsContext)\n const names = useMemo(() => [...outer, name], [outer, name])\n return <GuardedParamsContext.Provider value={names}>{children}</GuardedParamsContext.Provider>\n}\n\n/** The page parameters whose change replaces the content around, from every `GuardedParams` it sits in. */\nexport const useGuardedParams = () => useContext(GuardedParamsContext)\n","/** A guard's watch: the page parameters whose change replaces the content it sits in, such as the row a `select` chose. */\nexport type GuardWatch = { params: readonly string[] }\n\n/** Whether going from `from` to `to` leaves what a guard holds: another page, or a change of a parameter one watches. */\nexport const leavesPage = (from: string, to: string, guards: Iterable<GuardWatch>) => {\n const before = new URL(from, 'http://local')\n const after = new URL(to, 'http://local')\n if (before.pathname !== after.pathname) return true\n return [...guards].some((guard) => guard.params.some((name) => before.searchParams.get(name) !== after.searchParams.get(name)))\n}\n","export type NavigateOptions = { replace?: boolean; keepScroll?: boolean }\n\n/** A link followed while a guard asks first, held with its options until the person chooses to leave. */\nexport type PendingLink = { kind: 'link'; full: string; replace: boolean; keepScroll: boolean }\n\nexport const pendingLink = (full: string, { replace = false, keepScroll = false }: NavigateOptions = {}): PendingLink => ({ kind: 'link', full, replace, keepScroll })\n\n/** Follows a confirmed pending link as the link itself would have been followed with no guard in the way. */\nexport const followLink = (link: PendingLink, go: (full: string, replace: boolean, keepScroll: boolean) => void) => go(link.full, link.replace, link.keepScroll)\n","import { guarded } from '../lib/guarded'\n\nconst storageKey = 'protobase:page-places'\n/** The places kept, the most recent ones, so the storage stays small however long the tab is used. */\nconst kept = 50\n\nconst isPlace = (value: unknown): value is [string, number] =>\n Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number' && Number.isFinite(value[1]) && value[1] >= 0\n\nconst read = (storage: Pick<Storage, 'getItem'>): [string, number][] =>\n guarded(() => {\n const raw = storage.getItem(storageKey)\n if (raw === null) return []\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed.filter(isPlace) : []\n }, [])\n\n/**\n * How far down the document was scrolled in each history entry of a tab, by the entry's id, kept in `storage` (the\n * tab's session storage) when `persist` is called, so they outlast a reload of the page. An entry never left yet, as\n * one a link just made, starts at the top.\n */\nexport const createPagePlaces = (storage: Pick<Storage, 'getItem' | 'setItem'>) => {\n // The most recent last\n const places = new Map(read(storage))\n\n const placeOf = (entry: string) => places.get(entry) ?? 0\n\n const save = (entry: string, top: number) => {\n places.delete(entry)\n places.set(entry, Math.max(0, Math.round(top)))\n for (const oldest of [...places.keys()].slice(0, Math.max(0, places.size - kept))) places.delete(oldest)\n }\n\n const persist = () => guarded(() => storage.setItem(storageKey, JSON.stringify([...places])), undefined)\n\n return { placeOf, save, persist }\n}\n\nexport type PagePlaces = ReturnType<typeof createPagePlaces>\n","/** How long a page may take to grow tall enough, as while its data loads, before it is left where it is. */\nconst patience = 3000\n\n/**\n * Scrolls the document to `top`. A page still too short for it, as one whose data is loading, is scrolled again each\n * time it grows, until it is there, a few seconds pass, or anything else scrolls it: the person, or a list that brings\n * itself back to its place. Returns how to stop early.\n */\nexport const restoreScroll = (top: number) => {\n let placed = 0\n const place = () => {\n window.scrollTo({ top, behavior: 'instant' })\n placed = window.scrollY\n return placed >= top - 1\n }\n if (place()) return () => {}\n const observer = new ResizeObserver(() => place() && stop())\n const moved = () => Math.abs(window.scrollY - placed) > 1 && stop()\n const stop = () => {\n observer.disconnect()\n clearTimeout(timer)\n window.removeEventListener('scroll', moved)\n }\n const timer = setTimeout(stop, patience)\n observer.observe(document.body)\n window.addEventListener('scroll', moved, { passive: true })\n return stop\n}\n","import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type AnchorHTMLAttributes, type ReactNode } from 'react'\nimport { guarded } from '../lib/guarded'\nimport { Button } from '../primitives/button'\nimport { Dialog } from '../primitives/dialog'\nimport { RouteLink } from '../primitives/route-link'\nimport { text as appText } from './messages'\nimport { useGuardedParams } from './guarded-params'\nimport { leavesPage } from './leaves-page'\nimport { followLink, pendingLink, type NavigateOptions, type PendingLink } from './pending-link'\nimport { createPagePlaces } from './page-places'\nimport { restoreScroll } from './restore-scroll'\n\ntype RouterValue = {\n /** Path below the base path, always starting with `/`. */\n path: string\n params: URLSearchParams\n basePath: string\n /** The id of this page's entry in the tab's history: Back and Forward return to the same id, a reload keeps it. */\n entry: string\n /**\n * Moves to a path below the base path, as `appPath` writes it. `keepScroll` starts the new entry where the page is\n * scrolled now, for a change within the page, such as a choice its address holds, instead of at the top.\n */\n navigate: (to: string, options?: NavigateOptions) => void\n /** Goes back to a path below the base path: as the browser's Back when the page before is that path, else as `navigate`. */\n back: (to: string) => void\n /**\n * Asks to be told before the page changes, or one of the page parameters `params` whose content the guard sits in;\n * returns how to stop asking. Used by `useNavigationGuard`.\n */\n registerGuard: (kind?: GuardKind, params?: readonly string[]) => () => void\n /** Reloads the page, asking first while a guard holds unsaved changes. */\n reload: () => void\n /** Whether the person chose to reload despite unsaved changes, so the page leaves without asking again. */\n reloadConfirmed: () => boolean\n /** Whether a guard holds unsaved changes, so leaving the page would ask first. */\n holdsChanges: () => boolean\n}\n\n/**\n * What leaving the page does to the input a guard holds: `draft-kept` when this browser keeps it, as a record's draft,\n * `input-lost` when it is gone.\n */\nexport type GuardKind = 'draft-kept' | 'input-lost'\n\nexport type { NavigateOptions }\n\nconst RouterContext = createContext<RouterValue | null>(null)\n\nexport const useRouter = () => {\n const value = useContext(RouterContext)\n if (!value) throw new Error('useRouter must be used inside Router')\n return value\n}\n\nexport type RouterProps = {\n basePath?: string\n /** Keeps the location in memory instead of the address bar, for Storybook and tests. */\n initialUrl?: string\n children: ReactNode\n}\n\nconst browserUrl = () => `${window.location.pathname}${window.location.search}`\n\n/** A change of page waiting for the person's answer; `inputLost` when a guard's input would be gone, not kept. */\ntype Pending = (PendingLink | { kind: 'history'; delta: number } | { kind: 'reload' }) & { inputLost: boolean }\n\nconst pathOf = (url: string) => new URL(url, 'http://local').pathname\n\n/** `protobasePrevious` is the URL of the page this entry was opened from, so going back to it can take the browser's Back. */\ntype HistoryState = { protobaseIndex?: number; protobaseEntry?: string; protobasePrevious?: string }\nconst historyState = () => (window.history.state as HistoryState | null) ?? {}\n\n/** Our place in the browser history, so a back or forward press can be told apart and, if needed, undone. */\nconst historyIndex = () => historyState().protobaseIndex ?? 0\n\nconst newEntry = () => Math.random().toString(36).slice(2)\n\n/** The id of the current history entry, given one if it has none yet, as an entry pushed before the app started. */\nconst historyEntry = () => {\n const state = historyState()\n if (state.protobaseEntry) return state.protobaseEntry\n const entry = newEntry()\n window.history.replaceState({ ...state, protobaseEntry: entry }, '')\n return entry\n}\n\nconst noStorage = { getItem: () => null, setItem: () => {} }\n\nexport const Router = ({ basePath = '', initialUrl, children }: RouterProps) => {\n const memory = initialUrl !== undefined\n const [page, setPage] = useState(() => ({ url: initialUrl ?? browserUrl(), entry: memory ? newEntry() : historyEntry() }))\n const [places] = useState(() => createPagePlaces(memory ? noStorage : (guarded(() => window.sessionStorage, undefined) ?? noStorage)))\n const guards = useRef(new Map<symbol, { kind: GuardKind; params: readonly string[] }>())\n const losesInput = () => [...guards.current.values()].some((guard) => guard.kind === 'input-lost')\n const current = useRef(page)\n current.current = page\n const position = useRef(memory ? 0 : historyIndex())\n const undoing = useRef(false)\n const proceeding = useRef(false)\n // A Leave pressed before the step back has landed: the browser drops a traversal asked for while another is under way.\n const leaveAfterUndo = useRef<number | undefined>(undefined)\n const reloading = useRef(false)\n const [pending, setPending] = useState<Pending>()\n // Where the page being left was scrolled, read before the next page is drawn and changes it\n const rememberScroll = useCallback(() => places.save(current.current.entry, window.scrollY), [places])\n\n // A new page starts at the top, and one gone back or forward to where it was left. The browser's own restoring cannot:\n // a pushed entry keeps the scroll position, and a traversal restores it before the page it returns to is drawn.\n useLayoutEffect(() => restoreScroll(places.placeOf(page.entry)), [places, page.entry])\n\n useEffect(() => {\n if (memory) return\n window.history.scrollRestoration = 'manual'\n window.history.replaceState({ ...historyState(), protobaseIndex: position.current, protobaseEntry: current.current.entry }, '')\n // A reload or a discarded tab comes back to where the page was\n const persist = () => {\n rememberScroll()\n places.persist()\n }\n const hidden = () => document.visibilityState === 'hidden' && persist()\n window.addEventListener('pagehide', persist)\n document.addEventListener('visibilitychange', hidden)\n const onPop = () => {\n const next = historyIndex()\n if (undoing.current) {\n undoing.current = false\n position.current = next\n if (leaveAfterUndo.current !== undefined) window.history.go(leaveAfterUndo.current)\n leaveAfterUndo.current = undefined\n return\n }\n const delta = next - position.current\n if (!proceeding.current && guards.current.size > 0 && leavesPage(current.current.url, browserUrl(), guards.current.values())) {\n // The browser has already moved; step back to where the person was and ask.\n undoing.current = true\n window.history.go(-delta)\n setPending({ kind: 'history', delta, inputLost: losesInput() })\n return\n }\n proceeding.current = false\n position.current = next\n rememberScroll()\n setPage({ url: browserUrl(), entry: historyEntry() })\n }\n window.addEventListener('popstate', onPop)\n return () => {\n window.removeEventListener('popstate', onPop)\n window.removeEventListener('pagehide', persist)\n document.removeEventListener('visibilitychange', hidden)\n }\n }, [memory, rememberScroll, places])\n\n const go = useCallback(\n (full: string, replace: boolean, keepScroll = false) => {\n const entry = replace ? current.current.entry : newEntry()\n if (!memory) {\n position.current += replace ? 0 : 1\n const previous = replace ? historyState().protobasePrevious : current.current.url\n window.history[replace ? 'replaceState' : 'pushState']({ protobaseIndex: position.current, protobaseEntry: entry, protobasePrevious: previous }, '', full)\n }\n rememberScroll()\n if (keepScroll) places.save(entry, window.scrollY)\n setPage({ url: full, entry })\n },\n [memory, rememberScroll, places],\n )\n\n const navigate = useCallback(\n (to: string, options?: NavigateOptions) => {\n const link = pendingLink(`${basePath}${to}`, options)\n if (guards.current.size > 0 && leavesPage(current.current.url, link.full, guards.current.values())) return setPending({ ...link, inputLost: losesInput() })\n followLink(link, go)\n },\n [basePath, go],\n )\n\n const back = useCallback(\n (to: string) => {\n const previous = memory ? undefined : historyState().protobasePrevious\n if (previous !== undefined && pathOf(previous) === pathOf(`${basePath}${to}`)) return window.history.back()\n navigate(to)\n },\n [memory, basePath, navigate],\n )\n\n const registerGuard = useCallback((kind: GuardKind = 'draft-kept', params: readonly string[] = []) => {\n const token = Symbol('guard')\n guards.current.set(token, { kind, params })\n return () => void guards.current.delete(token)\n }, [])\n\n const reload = useCallback(() => {\n if (guards.current.size > 0) return setPending({ kind: 'reload', inputLost: losesInput() })\n window.location.reload()\n }, [])\n\n const reloadConfirmed = useCallback(() => reloading.current, [])\n const holdsChanges = useCallback(() => guards.current.size > 0, [])\n\n const leave = () => {\n if (!pending) return\n setPending(undefined)\n if (pending.kind === 'link') return followLink(pending, go)\n if (pending.kind === 'reload') {\n reloading.current = true\n return window.location.reload()\n }\n proceeding.current = true\n if (undoing.current) leaveAfterUndo.current = pending.delta\n else window.history.go(pending.delta)\n }\n\n const value = useMemo<RouterValue>(() => {\n const parsed = new URL(page.url, 'http://local')\n const path = parsed.pathname.slice(basePath.length) || '/'\n return {\n path,\n params: parsed.searchParams,\n basePath,\n entry: page.entry,\n navigate,\n back,\n registerGuard,\n reload,\n reloadConfirmed,\n holdsChanges,\n }\n }, [page, basePath, navigate, back, registerGuard, reload, reloadConfirmed, holdsChanges])\n\n return (\n <RouterContext.Provider value={value}>\n {children}\n {pending?.kind === 'reload' && (\n <Dialog\n title={appText('reloadTitle')}\n description={appText(pending.inputLost ? 'reloadInputLost' : 'reloadDraftKept')}\n onClose={() => setPending(undefined)}\n actions={\n <>\n <Button onClick={() => setPending(undefined)}>{appText('keepEditing')}</Button>\n <Button variant=\"primary\" onClick={leave}>\n {appText('reload')}\n </Button>\n </>\n }\n />\n )}\n {pending && pending.kind !== 'reload' && (\n <Dialog\n title={appText('leaveTitle')}\n description={appText(pending.inputLost ? 'leaveInputLost' : 'leaveDescription')}\n onClose={() => setPending(undefined)}\n actions={\n <>\n <Button onClick={() => setPending(undefined)}>{appText('stay')}</Button>\n <Button variant=\"primary\" onClick={leave}>\n {appText('leave')}\n </Button>\n </>\n }\n />\n )}\n </RouterContext.Provider>\n )\n}\n\n/** A link to a path below the base path, as `appPath` writes it, that the router follows without reloading the page. */\nexport const Link = ({ to, replace, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string; replace?: boolean }) => {\n const { navigate, basePath } = useRouter()\n return <RouteLink to={{ href: `${basePath}${to}`, onFollow: () => navigate(to, { replace }) }} {...rest} />\n}\n\n/**\n * While `active`, leaving the page asks first (in-app links, a reload and closing the tab), and so does changing a page\n * parameter whose content it sits in (`GuardedParams`).\n */\nexport const useNavigationGuard = (active: boolean, kind: GuardKind = 'draft-kept') => {\n const { registerGuard, reloadConfirmed } = useRouter()\n const params = useGuardedParams()\n useEffect(() => (active ? registerGuard(kind, params) : undefined), [active, kind, params, registerGuard])\n useEffect(() => {\n if (!active) return\n const warn = (event: BeforeUnloadEvent) => {\n if (!reloadConfirmed()) event.preventDefault()\n }\n window.addEventListener('beforeunload', warn)\n return () => window.removeEventListener('beforeunload', warn)\n }, [active, reloadConfirmed])\n}\n","import { encodeKey } from './keys'\nimport type { AppAddress, CalendarView, FilterLayout, MapView, TimelineView } from './model'\n\n/**\n * The words of the app's addresses. Only `appPath` and `readAppPath` write and read them, so the shape of an address\n * changes in this module alone.\n */\nexport const addressWords = {\n /** A named list of the resource (`.namedList(...)`), in place of its own list. */\n list: 'list',\n /** A list's filter (AIP-160), as the list API takes it. An empty `filter=` means no filter, in place of the view's default. */\n filter: 'filter',\n /** A list's order (AIP-132). */\n orderBy: 'order_by',\n /** The list display shown, when it is not the view's default. */\n display: 'display',\n /** Where a list's filters sit: `bar` (the default) or `panel`. */\n filterLayout: 'layout',\n /** Where a list's map display looks: `latitude,longitude,zoom`. */\n map: 'map',\n /** The month or week a list's calendar display shows: `month,YYYY-MM-DD` or `week,YYYY-MM-DD`. */\n calendar: 'calendar',\n /** The period a list's timeline display shows: `week,YYYY-MM-DD`, `month,YYYY-MM-DD` or `quarter,YYYY-MM-DD`. */\n timeline: 'timeline',\n /** The saved search a list was opened from, by its key. */\n savedSearch: 'saved_search',\n /** The second path segment that opens a resource's create form instead of a record. */\n create: 'new',\n /** A record's form, `edit=true`, on a view whose record page opens as a read view or locked. */\n edit: 'edit',\n /** A record page's open collapsed group, by title, once per group. */\n open: 'open',\n /** A record page's shown tab, by title. */\n tab: 'tab',\n /** A record's standard page, `standard=true`, on a view whose record page is a component of the app's own. */\n standard: 'standard',\n /** A record page that joins the record's call, `call=join`, as a ring's Accept and a call mark's Join open it. */\n call: 'call',\n /** A record's earlier saved version shown read-only, by number, as a field type that keeps versions draws it. */\n version: 'version',\n /** The run a workflow's page shows on its graph, by its key. */\n run: 'run',\n /** The panel a focus page opens with, by a name its surface knows. */\n panel: 'panel',\n /** A record's file field opened in the viewer for its media type, by field name. */\n file: 'file',\n} as const\n\nconst listWords = ['list', 'display', 'filter', 'orderBy', 'filterLayout', 'savedSearch'] as const\n\n// Five decimals of a degree are about a metre; two of a zoom are less than a pixel's difference.\nconst mapText = (view: MapView) => `${view.latitude.toFixed(5)},${view.longitude.toFixed(5)},${view.zoom.toFixed(2)}`\n\nconst inRange = (value: number, limit: number, low = -limit) => Number.isFinite(value) && value >= low && value <= limit\n\n// A map view as `mapText` writes it, or none for anything else\nconst readMap = (text: string | null): MapView | undefined => {\n const parts = text?.split(',')\n if (parts?.length !== 3 || parts.some((part) => part.trim() === '')) return undefined\n const [latitude, longitude, zoom] = parts.map(Number) as [number, number, number]\n return inRange(latitude, 90) && inRange(longitude, 180) && inRange(zoom, 22, 0) ? { latitude, longitude, zoom } : undefined\n}\n\nconst periodText = (view: CalendarView | TimelineView) => `${view.scale},${view.day}`\n\n// A real day as `YYYY-MM-DD`: one whose parts come back from `Date.UTC`, so 2026-02-30 is none\nconst isDay = (text: string) => {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return false\n const [year, month, day] = match.slice(1).map(Number) as [number, number, number]\n const date = new Date(Date.UTC(year, month - 1, day))\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n}\n\n// A period of one of `scales` as `periodText` writes it, or none for anything else\nconst readPeriod = <S extends string>(text: string | null, scales: readonly S[]): { scale: S; day: string } | undefined => {\n const parts = text?.split(',')\n if (parts?.length !== 2) return undefined\n const [scale, day] = parts as [S, string]\n return scales.includes(scale) && isDay(day) ? { scale, day } : undefined\n}\n\nconst listQuery = (address: Extract<AppAddress, { kind: 'list' }>) => {\n const query = new URLSearchParams()\n for (const name of listWords) {\n const value = address[name]\n if (value === undefined || (value === '' && name !== 'filter')) continue\n query.set(addressWords[name], value)\n }\n if (address.map) query.set(addressWords.map, mapText(address.map))\n if (address.calendar) query.set(addressWords.calendar, periodText(address.calendar))\n if (address.timeline) query.set(addressWords.timeline, periodText(address.timeline))\n const text = query.toString()\n return text ? `?${text}` : ''\n}\n\nconst recordQuery = (address: Extract<AppAddress, { kind: 'record' }>) => {\n const query = new URLSearchParams()\n if (address.edit) query.set(addressWords.edit, 'true')\n for (const title of address.open ?? []) query.append(addressWords.open, title)\n if (address.tab) query.set(addressWords.tab, address.tab)\n if (address.standard) query.set(addressWords.standard, 'true')\n if (address.call) query.set(addressWords.call, address.call)\n if (address.version !== undefined) query.set(addressWords.version, String(address.version))\n if (address.run) query.set(addressWords.run, address.run)\n if (address.panel) query.set(addressWords.panel, address.panel)\n if (address.file) query.set(addressWords.file, address.file)\n const text = query.toString()\n return text ? `?${text}` : ''\n}\n\n/** The path of `address` below `basePath` (such as `/admin`), every name and key encoded the one way the app reads them. */\nexport const appPath = (address: AppAddress, basePath = ''): string => {\n switch (address.kind) {\n case 'page':\n return `${basePath}/${encodeURIComponent(address.page)}${address.tab ? `/${encodeURIComponent(address.tab)}` : ''}${valuesQuery(address.params)}`\n case 'create':\n return `${basePath}/${encodeURIComponent(address.resource)}/${addressWords.create}${valuesQuery(address.values)}`\n case 'record':\n return `${basePath}/${encodeURIComponent(address.resource)}/${encodeURIComponent(encodeKey(address.key))}${recordQuery(address)}`\n case 'list':\n return `${basePath}/${encodeURIComponent(address.resource)}${listQuery(address)}`\n }\n}\n\nconst decodeSegments = (pathname: string) => {\n try {\n return pathname.split('/').filter(Boolean).map(decodeURIComponent)\n } catch (error) {\n if (error instanceof URIError) return undefined\n throw error\n }\n}\n\n// A create form's values, by field name, or a page's parameters, as the query.\nconst valuesQuery = (values: Readonly<Record<string, string>> = {}) => {\n const text = new URLSearchParams(Object.entries(values).filter(([, value]) => value !== '')).toString()\n return text ? `?${text}` : ''\n}\n\n// A version's number: a whole number from 1, or none for anything else\nconst readVersion = (text: string | null) => (text !== null && /^[1-9]\\d{0,8}$/.test(text) ? Number(text) : undefined)\n\nconst filterLayout = (value: string | null): FilterLayout | undefined => (value === 'bar' || value === 'panel' ? value : undefined)\n\n/**\n * The address `pathAndQuery` (below the base path) shows, or `undefined` for anything else: the root, the app's own\n * pages under `/-/`, or a path that is not one. A first segment in `pages` is a composed page, and a second one its\n * tab; otherwise it is a resource.\n */\nexport const readAppPath = (pathAndQuery: string, pages: ReadonlySet<string>): AppAddress | undefined => {\n const url = new URL(pathAndQuery, 'http://app')\n const segments = decodeSegments(url.pathname)\n if (!segments || segments.length === 0 || segments.length > 2) return undefined\n const [first, second] = segments as [string, string | undefined]\n if (first === '-') return undefined\n if (pages.has(first)) {\n // A page's query is its parameters alone, whatever their names, as its own SelectInputs name them\n const params = Object.fromEntries([...url.searchParams].filter(([, value]) => value !== ''))\n return { kind: 'page', page: first, ...(second !== undefined && { tab: second }), ...(Object.keys(params).length > 0 && { params }) }\n }\n if (second === addressWords.create) {\n const values = Object.fromEntries([...url.searchParams].filter(([, value]) => value !== ''))\n return { kind: 'create', resource: first, ...(Object.keys(values).length > 0 && { values }) }\n }\n if (second !== undefined) {\n const open = [...new Set(url.searchParams.getAll(addressWords.open).filter((title) => title !== ''))]\n const tab = url.searchParams.get(addressWords.tab) || undefined\n const standard = url.searchParams.get(addressWords.standard) === 'true'\n const call = url.searchParams.get(addressWords.call) === 'join'\n const version = readVersion(url.searchParams.get(addressWords.version))\n const run = url.searchParams.get(addressWords.run) || undefined\n const panel = url.searchParams.get(addressWords.panel) || undefined\n const file = url.searchParams.get(addressWords.file) || undefined\n return {\n kind: 'record',\n resource: first,\n key: second,\n ...(url.searchParams.get(addressWords.edit) === 'true' && { edit: true }),\n ...(open.length > 0 && { open }),\n ...(tab && { tab }),\n ...(standard && { standard }),\n ...(call && { call: 'join' as const }),\n ...(version !== undefined && { version }),\n ...(run && { run }),\n ...(panel && { panel }),\n ...(file && { file }),\n }\n }\n const params = url.searchParams\n const list = params.get(addressWords.list) || undefined\n const display = params.get(addressWords.display) || undefined\n const filter = params.get(addressWords.filter) ?? undefined\n const orderBy = params.get(addressWords.orderBy) || undefined\n const layout = filterLayout(params.get(addressWords.filterLayout))\n const map = readMap(params.get(addressWords.map))\n const calendar = readPeriod(params.get(addressWords.calendar), ['month', 'week'] as const)\n const timeline = readPeriod(params.get(addressWords.timeline), ['week', 'month', 'quarter'] as const)\n const savedSearch = params.get(addressWords.savedSearch) || undefined\n return {\n kind: 'list',\n resource: first,\n ...(list && { list }),\n ...(display && { display }),\n ...(filter !== undefined && { filter }),\n ...(orderBy && { orderBy }),\n ...(layout && { filterLayout: layout }),\n ...(map && { map }),\n ...(calendar && { calendar }),\n ...(timeline && { timeline }),\n ...(savedSearch && { savedSearch }),\n }\n}\n","import type { Client } from './client'\nimport type { ResourceRef } from './types'\n\nconst nameOf = (resource: ResourceRef) => (typeof resource === 'string' ? resource : resource.toModel().name)\n\n/**\n * One client over the app's own API and the sources it draws resources from: a call about a resource goes to the API\n * that serves it (`sourceOf` gives a source's client, or `undefined` for the app's own), and `meta`, `invoke`, the\n * public forms, `live`, the bridges and the user's devices, notifications and status go to the app's own. A batch goes to the one API all its writes are for; one that writes to two cannot be atomic, so it is\n * refused before anything is sent.\n */\nexport const routedClient = (own: Client, sourceOf: (resource: string) => Client | undefined): Client => {\n const to = (resource: ResourceRef) => sourceOf(nameOf(resource)) ?? own\n return {\n list: (resource, params) => to(resource).list(resource, params),\n search: (resource, params) => to(resource).search(resource, params),\n get: (resource, key) => to(resource).get(resource, key),\n create: (resource, body) => to(resource).create(resource, body),\n update: (resource, key, patch, etag) => to(resource).update(resource, key, patch, etag),\n remove: (resource, key, options) => to(resource).remove(resource, key, options),\n undelete: (resource, key) => to(resource).undelete(resource, key),\n generate: (resource, key, action) => to(resource).generate(resource, key, action),\n reveal: (resource, key, field) => to(resource).reveal(resource, key, field),\n history: (resource, key, options) => to(resource).history(resource, key, options),\n comments: (resource, key, options) => to(resource).comments(resource, key, options),\n comment: (resource, key, input) => to(resource).comment(resource, key, input),\n mentionable: (resource, key, query) => to(resource).mentionable(resource, key, query),\n batchWrite: (ops) => {\n const apis = [...new Set(ops.map((op) => to(op.resource)))]\n if (apis.length > 1) return Promise.reject(new Error(`A batch writes to one API, but these writes are for ${[...new Set(ops.map((op) => nameOf(op.resource)))].join(', ')}, which different APIs serve`))\n return (apis[0] ?? own).batchWrite(ops)\n },\n facets: (resource, field, options) => to(resource).facets(resource, field, options),\n aggregate: (resource, params) => to(resource).aggregate(resource, params),\n series: (resource, params) => to(resource).series(resource, params),\n histogram: (resource, field, options) => to(resource).histogram(resource, field, options),\n map: (resource, params) => to(resource).map(resource, params),\n seek: (resource, params) => to(resource).seek(resource, params),\n meta: (etag, options) => own.meta(etag, options),\n fileReadUrl: (resource, file) => to(resource).fileReadUrl(resource, file),\n invoke: (name, options) => own.invoke(name, options),\n upload: (resource, field, file, options) => to(resource).upload(resource, field, file, options),\n form: (name) => own.form(name),\n formChallenge: (name) => own.formChallenge(name),\n submitForm: (name, values, proof) => own.submitForm(name, values, proof),\n live: (handlers) => own.live(handlers),\n channel: (resource, key) => own.channel(resource, key),\n bridges: own.bridges,\n devices: own.devices,\n notifications: own.notifications,\n status: own.status,\n rings: own.rings,\n callGuests: own.callGuests,\n calls: (resource, key) => to(resource).calls(resource, key),\n watchCalls: (resource, key, handlers) => to(resource).watchCalls(resource, key, handlers),\n // The types are those of the API that serves the workflows\n workflowTypes: () => to('workflows').workflowTypes(),\n workflowRunTrace: (runId, held) => to('workflow_runs').workflowRunTrace(runId, held),\n runnerRegistration: (runner) => to('workflow_runners').runnerRegistration(runner),\n }\n}\n","// The recorders a typed layout is written with: `data.title` and `resources.tasks.count` are not values but records of\n// what the layout reads, which turn into today's `{{title}}` placeholders and AIP-160 text when the layout is built.\n\nconst recorded = Symbol('recorded')\n\n// A recorded path names the record it was read from by the child function that was given it, its scope, `0` for the\n// layout's own data. Which `../` or `@root` reaches that record depends on the records around the place it ends up,\n// which JSX builds inner elements first and so knows only once the whole tree is built: a path is written as a marker\n// of its scope, `{{~3~title}}`, and a condition's field as `~~3~status~~`, which `resolveScopes` rewrites.\n\n/** The scopes of the child functions running now, innermost last. */\nconst scopes: number[] = []\nlet lastScope = 0\n/** How many layouts are being built now, inside which a record block's child function may run. */\nlet building = 0\n\n/** Runs `build` as a typed layout builds, so its record blocks may take functions of their records. */\nexport const whileBuilding = <T>(build: () => T): T => {\n building += 1\n try {\n return build()\n } finally {\n building -= 1\n }\n}\n\n/** Runs `build` in a new scope, a record block's child function's, and gives the scope with what it built. */\nexport const inScope = <T>(build: (scope: number) => T): { scope: number; built: T } => {\n if (building === 0) throw new Error(\"A record block's children are a function of its record only inside a typed layout: layout(), recordLayout() or defineTemplate()\")\n lastScope += 1\n const scope = lastScope\n scopes.push(scope)\n try {\n return { scope, built: build(scope) }\n } finally {\n scopes.pop()\n }\n}\n\n/** The elements whose children a child function built, by its scope. */\nconst scopeOf = new WeakMap<object, number>()\n\n/** Notes that `node`'s children were built by the child function of `scope`. */\nexport const markScope = (node: object, scope: number) => {\n scopeOf.set(node, scope)\n}\n\n/** Gives `copy` the scope `node` was marked with, as an element held in a prop is copied into the tree. */\nexport const keepScope = (node: object, copy: object) => {\n const scope = scopeOf.get(node)\n if (scope !== undefined) scopeOf.set(copy, scope)\n}\n\ntype PathInfo = { path: string[]; scope: number }\n\n/** A filter value: written as it is in AIP-160 text. */\ntype Literal = string | number | boolean | null | Date\n\nconst durationPattern = /^\\d+[smhdw]$/\n\n/** A time relative to when the filter is read: `now()`, `now().plus('7d')`, `now().minus('1d')`. */\nexport class Now {\n constructor(readonly offset?: { sign: '+' | '-'; duration: string }) {}\n /** That long after now: `'7d'`, `'12h'`, `'30m'`, `'2w'`. */\n plus(duration: string) {\n return new Now({ sign: '+', duration: checkDuration(duration) })\n }\n /** That long before now. */\n minus(duration: string) {\n return new Now({ sign: '-', duration: checkDuration(duration) })\n }\n toString() {\n return this.offset ? `now() ${this.offset.sign} ${this.offset.duration}` : 'now()'\n }\n}\n\nconst checkDuration = (duration: string) => {\n if (!durationPattern.test(duration)) throw new Error(`\"${duration}\" is not a duration: write a number and s, m, h, d or w, such as '7d'`)\n return duration\n}\n\n/** The time a filter is read, which `plus` and `minus` move: `f.next_run_at.lt(now().plus('7d'))`. */\nexport const now = () => new Now()\n\n/** A condition: a filter of a block's records, or the `when` of a `Show`, written as AIP-160 text. */\nexport class Condition {\n /** @internal */\n constructor(\n /** @internal */\n readonly text: string,\n /** @internal */\n readonly op: 'and' | 'or' | 'term',\n ) {}\n /** Both hold: `a.and(b)`, written `a AND b`. */\n and(other: Condition) {\n return join('and', this, other)\n }\n /** Either holds: `a.or(b)`, written `a OR b`. */\n or(other: Condition) {\n return join('or', this, other)\n }\n toString() {\n return this.text\n }\n}\n\n// One AND or OR of two conditions, flattening a chain of the same operator and bracketing any other compound, as\n// AIP-160 binds OR closer than AND, which a reader does not expect\nconst join = (op: 'and' | 'or', left: Condition, right: Condition) => {\n const side = (part: Condition) => (part.op === 'term' || part.op === op ? part.text : `(${part.text})`)\n return new Condition(`${side(left)} ${op.toUpperCase()} ${side(right)}`, op)\n}\n\n/** The condition does not hold: `not(f.archived.eq(true))`, written `NOT (archived = true)`. */\nexport const not = (condition: Condition) => new Condition(`NOT ${condition.op === 'term' ? condition.text : `(${condition.text})`}`, 'term')\n\n/** Whether a value is a recorded path, such as `data.id`. */\nexport const isRecorded = (value: unknown): value is { [recorded]: PathInfo } => (typeof value === 'object' || typeof value === 'function') && value !== null && recorded in value\n\n/** The `{{…}}` placeholder of a recorded path, marked with its scope until `resolveScopes` writes where it reads from. */\nexport const placeholder = (value: { [recorded]: PathInfo }) => `{{~${value[recorded].scope}~${value[recorded].path.join('.')}}}`\n\n// A condition's field of a recorded record, marked with its scope as a placeholder is\nconst member = ({ path, scope }: PathInfo) => `~~${scope}~${path.join('.')}~~`\n\nconst valueMarker = /\\{\\{~(\\d+)~([^{}~]*)\\}\\}/g\nconst memberMarker = /~~(\\d+)~([^~]*)~~/g\n\n// The path a marked one is where `frames` are the scopes of the records around it, outermost first: by its name in\n// the nearest record, `@root` the layout's own data, `../` a record further out\nconst pathAt = (scope: number, path: string, frames: readonly (number | undefined)[]) => {\n const name = path === '' ? 'this' : path\n if (scope === 0) return frames.length === 0 ? name : path === '' ? '@root' : `@root.${path}`\n const at = frames.lastIndexOf(scope)\n if (at < 0) throw new Error(`\"${name}\" of a record is used outside the record block whose function gave it`)\n const up = frames.length - 1 - at\n return up === 0 ? name : `${'../'.repeat(up)}${name}`\n}\n\n// A condition names fields of the nearest record only\nconst memberAt = (scope: number, path: string, frames: readonly (number | undefined)[]) => {\n if ((scope === 0 && frames.length === 0) || (scope !== 0 && frames.at(-1) === scope)) return path\n throw new Error(`A condition compares \"${path}\" of a record further out than the nearest one around it, which a condition cannot name: compare it outside the inner record block, or in a filter`)\n}\n\nconst resolveText = (text: string, frames: readonly (number | undefined)[]) =>\n text.includes('~') ? text.replace(valueMarker, (_, scope: string, path: string) => `{{${pathAt(Number(scope), path, frames)}}}`).replace(memberMarker, (_, scope: string, path: string) => memberAt(Number(scope), path, frames)) : text\n\ntype Node = { type: string; props: Record<string, unknown>; children: unknown[]; fallback?: unknown[]; custom?: boolean }\n\nconst isNode = (value: unknown): value is Node => typeof value === 'object' && value !== null && !Array.isArray(value) && typeof (value as Node).type === 'string' && Array.isArray((value as Node).children)\n\n/** How an element places what it holds: the scope its children and its element props draw in, given its own. */\nexport type ScopeStep<S> = (node: Node, scope: S) => { children: S; slots: S; depth: (scope: S) => number }\n\n/**\n * The tree with every marked path written as it reads where it ends up, by the records around it: `step` gives the\n * scope an element's children and element props draw in, and how many records deep a scope is.\n */\nexport const resolveScopes = <T extends Node, S>(tree: T, start: S, step: ScopeStep<S>): T => {\n const visit = (node: Node, scope: S, frames: readonly (number | undefined)[]): Node => {\n const { children: inner, slots, depth } = step(node, scope)\n // A scope one record deeper than the element's own holds the record its child function gave, if it had one\n const framed = (next: S) => (depth(next) > depth(scope) ? [...frames, scopeOf.get(node)] : frames)\n const innerFrames = framed(inner)\n const slotFrames = framed(slots)\n const value = (item: unknown): unknown => {\n if (typeof item === 'string') return resolveText(item, frames)\n if (isNode(item)) return visit(item, slots, slotFrames)\n if (Array.isArray(item)) return item.map(value)\n if (typeof item === 'object' && item !== null) return Object.fromEntries(Object.entries(item).map(([key, entry]) => [key, value(entry)]))\n return item\n }\n const child = (at: S, atFrames: readonly (number | undefined)[]) => (entry: unknown) => (typeof entry === 'string' ? resolveText(entry, atFrames) : isNode(entry) ? visit(entry, at, atFrames) : entry)\n return {\n ...node,\n props: Object.fromEntries(Object.entries(node.props).map(([key, entry]) => [key, value(entry)])),\n children: node.children.map(child(inner, innerFrames)),\n ...(node.fallback && { fallback: node.fallback.map(child(scope, frames)) }),\n }\n }\n return visit(tree, start, []) as T\n}\n\n// A value in AIP-160: text quoted as JSON writes it, a recorded path as its placeholder, which the client fills as a\n// literal, and a time relative to now as written\nconst valueText = (value: unknown): string => {\n if (isRecorded(value)) return placeholder(value)\n if (value instanceof Now) return value.toString()\n if (value instanceof Date) return JSON.stringify(value.toISOString())\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean' || value === null) return String(value)\n throw new Error(`${String(value)} cannot be a filter value: compare with text, a number, true or false, null, now() or a recorded field`)\n}\n\nconst term = (text: string) => new Condition(text, 'term')\n\n/** What a field or a recorded path can be compared with. */\nconst comparisons = (name: string) => ({\n eq: (value: unknown) => term(value === null ? `isNull(${name})` : `${name} = ${valueText(value)}`),\n ne: (value: unknown) => term(value === null ? `NOT isNull(${name})` : `${name} != ${valueText(value)}`),\n lt: (value: unknown) => term(`${name} < ${valueText(value)}`),\n le: (value: unknown) => term(`${name} <= ${valueText(value)}`),\n gt: (value: unknown) => term(`${name} > ${valueText(value)}`),\n ge: (value: unknown) => term(`${name} >= ${valueText(value)}`),\n in: (values: readonly unknown[]) => term(`in(${name}, ${values.map(valueText).join(', ')})`),\n contains: (value: unknown) => term(`${name}:${valueText(value)}`),\n isNull: () => term(`isNull(${name})`),\n})\n\nconst comparisonNames = new Set(Object.keys(comparisons('')))\n\n/**\n * A recorder of the values in scope: each property read is a path, `data.plan.name`, which is its `{{plan.name}}`\n * placeholder where it ends up as text, and compares like a field in a condition, `data.status.eq('done')`.\n */\nexport const recorder = (path: string[] = [], scope = scopes.at(-1) ?? 0): unknown =>\n new Proxy({}, {\n get: (_, key) => {\n if (key === recorded) return { path, scope }\n if (key === Symbol.toPrimitive || key === 'toString' || key === 'toJSON') return () => placeholder({ [recorded]: { path, scope } })\n if (typeof key === 'symbol') return undefined\n if (comparisonNames.has(key)) return comparisons(member({ path, scope }))[key as keyof ReturnType<typeof comparisons>]\n return recorder([...path, key], scope)\n },\n has: (_, key) => key === recorded,\n })\n\n/** The fields of a resource as a filter's arrow is given them: `(f) => f.enabled.eq(true)`. A relation's field is `f.plan.name`. */\nexport const fieldRecorder = (path: string[] = []): unknown =>\n new Proxy(\n {},\n {\n get: (_, key) => {\n if (typeof key === 'symbol') return undefined\n if (comparisonNames.has(key) && path.length > 0) return comparisons(path.join('.'))[key as keyof ReturnType<typeof comparisons>]\n return fieldRecorder([...path, key])\n },\n },\n )\n\n/** The page's tables, each counted where a condition reads it: `resources.loop_held.count.gt(0)`, written `loop_held.count > 0`. */\nexport const resourcesRecorder = (): unknown =>\n new Proxy(\n {},\n {\n get: (_, name) => (typeof name === 'symbol' ? undefined : { count: comparisons(`${name}.count`) }),\n },\n )\n","import { isLayoutNode, type Block, type ComponentReads, type LayoutChild, type LayoutNode, type LayoutValue } from './node'\nimport { Condition, Now, fieldRecorder, inScope, isRecorded, keepScope, markScope, placeholder, recorder } from './typed/record'\n\nconst advice = 'Layouts are static data, sent to the browser as JSON: use <Action name=\"...\"> for behaviour, or register a custom component for React code.'\n\nconst describe = (value: unknown) => {\n if (typeof value === 'function') return 'a function'\n if (typeof value === 'number') return String(value)\n if (typeof value !== 'object' || value === null) return `a ${typeof value}`\n return `a ${value.constructor?.name ?? 'object without prototype'}`\n}\n\nconst isPlainObject = (value: object) => {\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/** Throws unless `value` is JSON-safe data: strings, finite numbers, booleans, null, arrays and plain objects of those. */\nexport const staticValue = (value: unknown, where: string): LayoutValue => {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n // What a typed layout records: a path read is its placeholder, a condition or a time its AIP-160 text\n if (isRecorded(value)) return placeholder(value)\n if (value instanceof Condition || value instanceof Now) return value.toString()\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (Array.isArray(value)) return value.map((item, index) => staticValue(item, `${where.slice(0, -1)}[${index}]>`))\n if (typeof value === 'object' && isPlainObject(value)) {\n const copy = Object.fromEntries(Object.entries(value).flatMap(([key, item]) => (item === undefined ? [] : [[key, staticValue(item, `${where.slice(0, -1)}.${key}>`)]])))\n // An element in a prop keeps the records its child function gave, which its paths are written by\n keepScope(value, copy)\n return copy\n }\n throw new Error(`${where} is ${describe(value)}. ${advice}`)\n}\n\n/** Flattens arrays and fragments, drops `null`, `undefined` and booleans, and turns numbers into text, like React. */\nexport const normalizeChildren = (children: unknown, where: string): LayoutChild[] => {\n if (children === undefined || children === null || typeof children === 'boolean') return []\n if (typeof children === 'string') return [children]\n if (isRecorded(children)) return [placeholder(children)]\n if (typeof children === 'number' && Number.isFinite(children)) return [String(children)]\n if (Array.isArray(children)) return children.flatMap((child) => normalizeChildren(child, where))\n if (isLayoutNode(children)) return children.type === fragmentName && !children.custom ? children.children : [children]\n throw new Error(`${where} has a child that is ${describe(children)}. ${advice}`)\n}\n\nexport const fragmentName = 'Fragment'\n\nconst isBlock = (type: unknown): type is Block<unknown> => typeof type === 'function' && typeof (type as Block<unknown>).blockName === 'string'\n\n/** The blocks that draw their children inside a record of their own, whose children may be a function of that record. */\nexport const recordChildBlocks = ['RecordCard', 'CardRow', 'ReferenceField', 'RecordsIterator']\n\n/** The props that are a condition on a block's own records, which a typed layout writes as an arrow of their fields. */\nconst conditionArrows = ['filter', 'edgeFilter', 'animated', 'dashed', 'dotted']\n\n// A typed layout's props as the static tree holds them: a filter's or condition's arrow called with the resource's\n// fields, and a sort's entries as one AIP-132 text\nconst builtProps = (name: string, props: Record<string, unknown>) => {\n const built = { ...props }\n for (const prop of conditionArrows) {\n const value = built[prop]\n if (typeof value === 'function') {\n const condition = (value as (fields: unknown) => unknown)(fieldRecorder())\n if (!(condition instanceof Condition)) throw new Error(`<${name} ${prop}> is an arrow that gives no condition: write (f) => f.status.eq('open'), or the ${prop} as AIP-160 text`)\n built[prop] = condition.text\n } else if (typeof value === 'object' && value !== null && !(value instanceof Condition)) {\n throw new Error(`<${name} ${prop}> is an object: write the ${prop} as an arrow, (f) => f.status.eq('open'), or as AIP-160 text`)\n }\n }\n if (built.sort !== undefined) {\n if (!Array.isArray(built.sort) || !built.sort.every((entry) => typeof entry === 'string')) throw new Error(`<${name} sort> takes a list of fields, each with asc or desc if it likes: sort={['next_run_at asc']}`)\n built.sort = built.sort.join(', ')\n }\n return built\n}\n\n// A record block's children: a function of its record, called once with a recorder of a scope of its own, which the\n// element is marked with, or the elements\nconst builtChildren = (name: string, children: unknown, where: string): { children: LayoutChild[]; scope?: number } => {\n if (typeof children !== 'function') return { children: normalizeChildren(children, where) }\n if (!recordChildBlocks.includes(name)) throw new Error(`<${name}> takes elements as children; only ${recordChildBlocks.join(', ')} take a function of their record`)\n const { scope, built } = inScope((own) => normalizeChildren((children as (record: unknown) => unknown)(recorder([], own)), where))\n return { children: built, scope }\n}\n\n/** The blocks with a prop of elements drawn once per record of their own, which may be a function of that record. */\nexport const recordPropBlocks: Readonly<Record<string, string>> = { Graph: 'node' }\n\n/** The built-in blocks that take a `fallback`, drawn where they cannot draw, which the element holds as a component's. */\nexport const fallbackBlocks: ReadonlySet<string> = new Set(['Graph'])\n\n// A prop of elements drawn once per record, a function of it called as a record block's children are: stored as one\n// element, itself or a Box around several, with the scope of the function that built it\nconst builtRecordProp = (name: string, prop: string, value: unknown): { value: unknown; scope?: number } => {\n const where = `<${name} ${prop}>`\n const one = (children: LayoutChild[]): LayoutNode => {\n const [only] = children\n return children.length === 1 && typeof only === 'object' ? only : { type: 'Box', props: {}, children }\n }\n if (typeof value !== 'function') return { value: value === undefined || isLayoutNode(value) ? value : one(normalizeChildren(value, where)) }\n const { scope, built } = inScope((own) => normalizeChildren((value as (record: unknown) => unknown)(recorder([], own)), where))\n return { value: one(built), scope }\n}\n\n/** The element for `<type {...props} />`: checks that every prop and child is static and returns plain data. */\nexport const createNode = (type: unknown, props: Record<string, unknown>): LayoutNode => {\n if (typeof type === 'string') throw new Error(`<${type}> is an HTML element, not a layout block: use the blocks from @protobase/layout or a custom component`)\n if (!isBlock(type)) {\n throw new Error(`<${typeof type === 'function' && type.name ? type.name : 'unknown'}> is not a layout block. Components in a layout are declared with component('Name') and implemented in the app; ${advice}`)\n }\n const name = type.blockName\n const { children, ...written } = props\n // A built-in block's fallback is the element's, as a component's is\n const ownFallback = !type.custom && fallbackBlocks.has(name)\n const { fallback, ...taken } = written\n const given = ownFallback ? taken : written\n const rest = type.custom ? given : builtProps(name, given)\n const recordProp = type.custom ? undefined : recordPropBlocks[name]\n const perRecord = recordProp === undefined ? undefined : builtRecordProp(name, recordProp, rest[recordProp])\n if (recordProp !== undefined) rest[recordProp] = perRecord!.value\n const built = type.custom ? { children: normalizeChildren(children, `<${name}>`) } : builtChildren(name, children, `<${name}>`)\n const node: LayoutNode = {\n type: name,\n props: Object.fromEntries(Object.entries(rest).flatMap(([key, value]) => (value === undefined ? [] : [[key, staticValue(value, `<${name} ${key}>`)]]))),\n children: built.children,\n }\n // One element holds the records of one function: its children's, or else its prop's\n const scope = built.scope ?? perRecord?.scope\n if (scope !== undefined) markScope(node, scope)\n if (type.custom) node.custom = true\n if (type.fallback) node.fallback = type.fallback\n if (ownFallback && fallback !== undefined) node.fallback = normalizeChildren(fallback, `<${name} fallback>`)\n if (type.reads) node.reads = type.reads\n return node\n}\n\n/**\n * Declares a block named `name`; `custom` marks a component the app implements in React, drawn as `fallback` where it\n * cannot be, and reading what `reads` names.\n */\nexport const defineBlock = <P>(name: string, custom: boolean, fallback?: LayoutChild[], reads?: ComponentReads): Block<P> => {\n const block: Block<P> = Object.assign((props: P) => createNode(block, props as Record<string, unknown>), { blockName: name, custom, ...(fallback && { fallback }), ...(reads && { reads }) })\n return block\n}\n","import type { FieldModel, ResourceModel } from '@protobase/schema'\n\n/** One step of a field path: the field, and the resource it belongs to. */\nexport type PathStep = { model: ResourceModel; field: FieldModel }\n\nexport type PathResolution = { ok: true; steps: PathStep[] } | { ok: false; message: string }\n\n/**\n * Resolves `plan.name` from `resource`: every name but the last must be a relation, and each next name a field of the\n * resource that relation points at. A missing resource or field is reported as unknown, never as hidden.\n */\nexport const resolveFieldPath = (models: Record<string, ResourceModel>, resource: string, path: string): PathResolution => {\n const steps: PathStep[] = []\n let model = models[resource]\n const names = path.split('.')\n for (const [index, name] of names.entries()) {\n if (!model) return { ok: false, message: `unknown resource \"${resource}\"` }\n const field = Object.hasOwn(model.fields, name) ? model.fields[name] : undefined\n if (!field) return { ok: false, message: `unknown field \"${names.slice(0, index + 1).join('.')}\" on ${model.name}` }\n steps.push({ model, field })\n if (index === names.length - 1) break\n if (field.type !== 'relation' || !field.relation) return { ok: false, message: `\"${names.slice(0, index + 1).join('.')}\" is not a relation, so \"${path}\" cannot go through it` }\n resource = field.relation.resource\n model = models[resource]\n }\n return { ok: true, steps }\n}\n","import { IntlMessageFormat } from 'intl-messageformat'\nimport { defineBlock } from './create-node'\nimport { isLayoutNode, type LayoutChild, type LayoutNode, type LayoutValue } from './node'\nimport type { Recorded, Register } from './typed/types'\n\n// The app's own texts in each of its languages, as ICU messages (the syntax `intl-messageformat` reads), and the\n// <Trans> element that shows one by its key, as react-i18next's <Trans i18nKey values components /> does.\n\n/** A language's texts as written: keys nested as deep as one likes, each message ICU text. */\nexport type TextTree = { readonly [key: string]: string | TextTree }\n\n/** The dotted keys of a tree of texts: `{ today: { title: '…' } }` has `today.title`. */\nexport type TextKeys<T> = { [K in keyof T & string]: T[K] extends string ? K : `${K}.${TextKeys<T[K]>}` }[keyof T & string]\n\n/** The app's texts in each of its languages, flattened by key, as `translations({ en, nl })` makes them. */\nexport type Translations<Keys extends string = string> = {\n readonly kind: 'translations'\n /** Each language's messages by dotted key; every language has every key. */\n readonly languages: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** The keys, for the compiler only; never set. */\n readonly $keys?: Keys\n}\n\nconst flatten = (tree: TextTree, at = ''): [string, string][] =>\n Object.entries(tree).flatMap(([key, value]) => (typeof value === 'string' ? [[`${at}${key}`, value] as [string, string]] : flatten(value, `${at}${key}.`)))\n\n/**\n * The app's texts in each of its languages, from one JSON file per language: `translations({ en, nl })`, exported from\n * `config/index.ts`. Every message must parse as ICU, every language must have the same keys, and each language must\n * be a BCP 47 tag, such as `en`, `nl` or `pt-BR`.\n */\nexport const translations = <const L extends Record<string, TextTree>>(languages: L): Translations<TextKeys<L[keyof L]>> => {\n const tags = Object.keys(languages)\n if (tags.length === 0) throw new Error('translations() takes at least one language, such as translations({ en })')\n const flat = Object.fromEntries(tags.map((tag) => [tag, Object.fromEntries(flatten(languages[tag]!))]))\n const problems: string[] = []\n for (const tag of tags) {\n try {\n Intl.getCanonicalLocales(tag)\n } catch {\n problems.push(`\"${tag}\" is not a language tag, such as en, nl or pt-BR`)\n continue\n }\n for (const [key, message] of Object.entries(flat[tag]!)) {\n try {\n new IntlMessageFormat(message, tag)\n } catch (error) {\n problems.push(`${tag}: \"${key}\" is not an ICU message: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n }\n const keys = new Set(tags.flatMap((tag) => Object.keys(flat[tag]!)))\n for (const tag of tags) {\n const missing = [...keys].filter((key) => !Object.hasOwn(flat[tag]!, key))\n if (missing.length > 0) problems.push(`${tag} lacks ${missing.map((key) => `\"${key}\"`).join(', ')}, which ${tags.filter((other) => other !== tag && missing.some((key) => Object.hasOwn(flat[other]!, key))).join(', ')} has`)\n }\n if (problems.length > 0) throw new Error(`The app's translations are not usable: ${problems.join('; ')}`)\n return { kind: 'translations', languages: flat }\n}\n\nexport const isTranslations = (value: unknown): value is Translations =>\n typeof value === 'object' && value !== null && (value as Translations).kind === 'translations' && typeof (value as Translations).languages === 'object'\n\n// The node types of a parsed ICU message (@formatjs/icu-messageformat-parser's TYPE), by what the checks read of them\nconst argumentTypes = new Set([1, 2, 3, 4, 5, 6])\nconst tagType = 8\ntype MessageElement = { type: number; value?: string; options?: Record<string, { value: MessageElement[] }>; children?: MessageElement[] }\n\nconst walk = (elements: readonly MessageElement[], found: { values: Set<string>; tags: Set<string> }) => {\n for (const element of elements) {\n if (argumentTypes.has(element.type) && element.value !== undefined) found.values.add(element.value)\n if (element.type === tagType && element.value !== undefined) found.tags.add(element.value)\n for (const option of Object.values(element.options ?? {})) walk(option.value, found)\n if (element.children) walk(element.children, found)\n }\n}\n\n/** The values a message formats (`{name}`, `{count, plural, …}`) and the tags it holds (`<b>…</b>`). */\nexport const messageParts = (message: string, language: string) => {\n const found = { values: new Set<string>(), tags: new Set<string>() }\n walk(new IntlMessageFormat(message, language).getAst() as unknown as MessageElement[], found)\n return { values: [...found.values], tags: [...found.tags] }\n}\n\n/** The texts a reader gets: their language and the messages by key, of the keys what they see uses. */\nexport type ReaderTexts = { locale: string; messages: Readonly<Record<string, string>> }\n\nconst compiled = new Map<string, IntlMessageFormat>()\n\n/**\n * A message formatted in the reader's language with `values`, or its key when the texts lack it, which the startup\n * check makes impossible in a valid app. Tags format through `tags`, each given the formatted text inside it.\n */\nexport const formatMessage = <T = string>(texts: ReaderTexts | undefined, key: string, values: Record<string, unknown> = {}, tags: Record<string, (chunks: unknown[]) => T> = {}): string | (string | T)[] => {\n const message = texts?.messages[key]\n if (message === undefined || !texts) return key\n const id = `${texts.locale}\\u0000${message}`\n let format = compiled.get(id)\n if (!format) {\n format = new IntlMessageFormat(message, texts.locale)\n compiled.set(id, format)\n }\n return format.format({ ...values, ...tags }) as string | (string | T)[]\n}\n\n/** A message as plain text: its tags' text kept, the tags themselves left out. */\nexport const formatText = (texts: ReaderTexts | undefined, key: string, values: Record<string, unknown> = {}) => {\n const tags = Object.fromEntries((texts?.messages[key] ? messageParts(texts.messages[key], texts.locale).tags : []).map((tag) => [tag, (chunks: unknown[]) => chunks.join('')]))\n const formatted = formatMessage(texts, key, values, tags)\n return Array.isArray(formatted) ? formatted.join('') : formatted\n}\n\ntype AppTexts = Register extends { app: infer A extends object } ? { [K in keyof A]: A[K] extends Translations<infer Keys> ? Keys : never }[keyof A] : never\n\n/** The keys of the app's texts, or any key without the generated types. */\nexport type TransKey = [AppTexts] extends [never] ? string : AppTexts\n\n/** A value a message formats: one of its own, or a recorded path of a typed layout, `data.title`. */\ntype TransValue = string | number | boolean | null | Recorded<unknown>\n\n/**\n * A text in the reader's language, by its key, as react-i18next's `<Trans i18nKey values components />`: ICU text\n * whose `{name}` takes `values.name`, here a value or a recorded path such as `data.title`, and whose tags, `<b>…</b>`,\n * draw as `components.b`. It goes where text goes, a child or a prop such as a `title`, `label` or `empty`.\n */\nexport const Trans = defineBlock<{ i18nKey: TransKey; values?: Record<string, TransValue>; components?: Record<string, LayoutNode> }>('Trans', false)\n\n/** Whether a value is a `<Trans>` element. */\nexport const isTrans = (value: LayoutValue | LayoutChild | undefined): value is LayoutNode => isLayoutNode(value) && value.type === 'Trans' && !value.custom\n\n/** Every key a tree's `<Trans>` elements name, in its children and its props. */\nexport const transKeys = (node: LayoutNode): string[] => {\n const own = isTrans(node) && typeof node.props.i18nKey === 'string' ? [node.props.i18nKey] : []\n const inProps = Object.values(node.props).flatMap((value) => (isLayoutNode(value) ? transKeys(value) : Array.isArray(value) ? value.flatMap((item) => (isLayoutNode(item) ? transKeys(item) : [])) : isObject(value) ? Object.values(value).flatMap((item) => (isLayoutNode(item) ? transKeys(item) : [])) : []))\n const inChildren = node.children.flatMap((child) => (typeof child === 'string' ? [] : transKeys(child)))\n return [...new Set([...own, ...inProps, ...inChildren, ...(node.fallback ?? []).flatMap((child) => (typeof child === 'string' ? [] : transKeys(child)))])]\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The language a reader gets of `languages`, the app's translations: the app's own when it sets one, else the first of\n * the reader's own (`Accept-Language`) the app has, by its full tag or its language, else the first the app has.\n */\nexport const readerLanguage = (languages: readonly string[], preferred: readonly string[], fixed?: string): string | undefined => {\n if (languages.length === 0) return\n if (fixed && languages.includes(fixed)) return fixed\n for (const tag of preferred) {\n const exact = languages.find((language) => language.toLowerCase() === tag.toLowerCase())\n if (exact) return exact\n const base = tag.split('-')[0]!.toLowerCase()\n const near = languages.find((language) => language.split('-')[0]!.toLowerCase() === base)\n if (near) return near\n }\n return languages.includes('en') ? 'en' : languages[0]\n}\n\n// Every <Trans> element of a tree, in its props and its children\nconst transNodes = (node: LayoutNode): LayoutNode[] => {\n const inValue = (value: unknown): LayoutNode[] =>\n isLayoutNode(value) ? transNodes(value) : Array.isArray(value) ? value.flatMap(inValue) : isObject(value) ? Object.values(value).flatMap(inValue) : []\n const children = [...node.children, ...(node.fallback ?? [])].flatMap((child) => (typeof child === 'string' ? [] : transNodes(child)))\n return [...(isTrans(node) ? [node] : []), ...Object.values(node.props).flatMap(inValue), ...children]\n}\n\n/**\n * What the `<Trans>` elements of the app's trees, by where each sits, ask that its translations lack: a key no language\n * has, a value its message formats in some language that the element does not give, or a tag with no component.\n */\nexport const translationProblems = (trees: readonly { at: string; tree: LayoutNode }[], given: Translations | undefined): string[] =>\n trees.flatMap(({ at, tree }) =>\n transNodes(tree).flatMap((node) => {\n const key = String(node.props.i18nKey)\n if (!given) return [`${at}: <Trans i18nKey=\"${key}\"> needs the app's texts: export translations({ en, ... }) from the config`]\n const languages = Object.entries(given.languages)\n if (!languages.some(([, messages]) => Object.hasOwn(messages, key))) return [`${at}: <Trans i18nKey=\"${key}\">: no language has \"${key}\"`]\n const values = new Set(Object.keys(isObject(node.props.values) ? node.props.values : {}))\n const components = new Set(Object.keys(isObject(node.props.components) ? node.props.components : {}))\n const parts = languages.map(([language, messages]) => messageParts(messages[key]!, language))\n const missing = [...new Set(parts.flatMap((part) => part.values))].filter((name) => !values.has(name))\n const untagged = [...new Set(parts.flatMap((part) => part.tags))].filter((name) => !components.has(name))\n return [\n ...(missing.length > 0 ? [`${at}: <Trans i18nKey=\"${key}\"> formats ${missing.map((name) => `{${name}}`).join(', ')}; give it in values`] : []),\n ...(untagged.length > 0 ? [`${at}: <Trans i18nKey=\"${key}\"> has the tag${untagged.length > 1 ? 's' : ''} ${untagged.map((name) => `<${name}>`).join(', ')}; give each an element in components`] : []),\n ]\n }),\n )\n","import { resolveFieldPath } from '@protobase/layout'\nimport type { ActionModel, FieldModel, GroupItemModel, LayoutItemModel, ResourceModel, TabItemModel, ViewModel } from '@protobase/schema'\nimport { addressErrors, followableRowButton } from '@protobase/schema/internal'\nimport type { Meta, ResourcePermissions, SourceRef } from './types'\n\n/** What the app draws of a source: the resources it lists that the user may see there, their views and what the user may do. */\nexport type SourceMeta = { resources: ResourceModel[]; views: ViewModel[]; permissions: Record<string, ResourcePermissions> }\n\n// A relation to a resource the app does not draw from the source shows its key: the app has no such resource, or one of\n// its own by that name, which is another resource.\nconst withinSource = (model: ResourceModel, drawn: Record<string, ResourceModel>): ResourceModel => ({\n ...model,\n fields: Object.fromEntries(\n Object.entries(model.fields).map(([name, field]): [string, FieldModel] => {\n if (!field.relation || Object.hasOwn(drawn, field.relation.resource)) return [name, field]\n const { relation: _outside, ...plain } = field\n return [name, plain]\n }),\n ),\n})\n\n// Related records of a resource the app does not draw go, and so do columns that go through a relation out of the source\n// and a row button's choices that lead out of it.\nconst keptLayoutItem = (item: LayoutItemModel, models: Record<string, ResourceModel>): LayoutItemModel[] => {\n if (item.kind === 'group') {\n const items = item.items.flatMap((inner) => keptLayoutItem(inner, models)) as GroupItemModel[]\n return items.length > 0 ? [{ ...item, items }] : []\n }\n if (item.kind === 'tab') {\n const items = item.items.flatMap((inner) => keptLayoutItem(inner, models)) as TabItemModel[]\n return items.length > 0 ? [{ ...item, items }] : []\n }\n if (item.kind !== 'related') return [item]\n if (!Object.hasOwn(models, item.resource) || (item.through && !Object.hasOwn(models, item.through.resource))) return []\n const { columns, button, ...rest } = item\n const kept = columns?.filter((column) => resolveFieldPath(models, item.resource, column).ok)\n const narrowed = kept && kept.length > 0 ? { ...rest, columns: kept } : rest\n const followable = button === undefined ? undefined : followableRowButton(button, models[item.resource]!, { models, pages: new Set() })\n return [followable === undefined ? narrowed : { ...narrowed, button: followable }]\n}\n\n// A link to an address in the app goes when it leads out of the source: to a page, or to a resource the app does not draw.\nconst keptAction = (action: ActionModel, model: ResourceModel, models: Record<string, ResourceModel>) =>\n action.run?.kind !== 'link' || !('to' in action.run) || addressErrors(action.run.to, { models, pages: new Set(), source: model }).length === 0\n\nconst withinSourceView = (view: ViewModel, models: Record<string, ResourceModel>): ViewModel => ({\n ...view,\n layout: view.layout.flatMap((item) => keptLayoutItem(item, models)),\n actions: view.actions.filter((action) => keptAction(action, models[view.resource]!, models)),\n})\n\n/**\n * The part of a source's `/meta` the app draws: the resources `source` lists, of those the source names to the user,\n * with their views and permissions. Nothing in them leads out of the source: a relation to a resource the app does not\n * draw from it shows its key, and related records of one, columns through one and links to one or to a page go.\n */\nexport const sourceMeta = (meta: Meta, source: SourceRef): SourceMeta => {\n const listed = meta.resources.filter((model) => source.resources.includes(model.name))\n const models: Record<string, ResourceModel> = Object.fromEntries(listed.map((model) => [model.name, model]))\n const resources = listed.map((model) => withinSource(model, models))\n const scoped = Object.fromEntries(resources.map((model) => [model.name, model]))\n const views = meta.views.filter((view) => Object.hasOwn(scoped, view.resource)).map((view) => withinSourceView(view, scoped))\n const permissions = Object.fromEntries(listed.flatMap((model) => (meta.permissions?.[model.name] ? [[model.name, meta.permissions[model.name]!]] : [])))\n return { resources, views, permissions }\n}\n","import type { MapLayerModel, PluginRef, ResourcePermissions, SourceRef } from '@protobase/client'\nimport type { PageModel } from '@protobase/layout'\nimport type { BottomBarModel, ResourceModel, SignInViewModel, UserMenuModel, ViewModel } from '@protobase/schema'\nimport type { Locale } from '@protobase/schema/internal'\n\nexport type MetaData = {\n etag: string\n /** The app's name, which ends the tab titles. */\n appName: string\n /** The Protobase version the server ran when this `/meta` was read. */\n protobaseVersion?: string\n /**\n * Set once the server runs another Protobase version than the page started with: `to` is that version, when the server\n * names one. The page keeps this `/meta` and stops reading it until it is reloaded (see `keepOnVersionChange`).\n */\n versionChange?: { to?: string }\n /** The path of the app's own icon, when the project has one, which the sidebar's logo draws. */\n appIcon?: string\n resources: Record<string, ResourceModel>\n views: Record<string, ViewModel>\n /** Composed pages by name. */\n pages: Record<string, PageModel>\n /** The signed-in user's account page, at `/-/account` (see `AccountPage`). */\n account?: PageModel\n permissions: Record<string, ResourcePermissions>\n userMenu?: UserMenuModel\n /** For a visitor, the resources they could use once signed in, by name, with what to tell them (see `SignInPrompt`). */\n signIn?: Record<string, SignInViewModel>\n /** The tabs of the user's bottom bar on phones, when one names their active role. */\n bottomBar?: Omit<BottomBarModel, 'roles'>\n /** The assistant backend, when the app has one and the user has the admin or ai role. */\n assistant?: { url: string }\n /** The runtime updates endpoint, when the app has one and the user has the admin role. */\n runtime?: { url: string }\n /** The error tracker the app sends its errors to, when the app reports them (see `startErrorReporting`). */\n errorReporting?: { dsn: string; environment?: string }\n /** The map style the app's maps are drawn with, and the layers they may switch to, when the app has one (see `MapSection`). */\n maps?: { style: string; layers?: MapLayerModel[] }\n /** Whether the top bar draws the notification bell: the app has notifications and their `ui` is not false (see `ShellBell`). */\n bell?: boolean\n /** Whether people set their own status and see those they share an organization with (see `useStatuses`). */\n status?: boolean\n /** Whether the app has calls, which ring people on any page they have open (see `CallRings`). */\n calls?: boolean\n /** The language the app's screens are in for everyone, when it sets one (see `AppLocale`). */\n locale?: Locale\n /** The app's own texts in the user's language, the messages their pages' `<Trans>` elements name (see `AppTexts`). */\n texts?: { locale: string; messages: Record<string, string> }\n /** The hosts besides the app's own whose images are drawn with the page's referrer (see `FileImage`). */\n files?: { trustedHosts: string[] }\n /** The plugins the app loads for the user (see `PluginGate`). */\n plugins?: PluginRef[]\n /** The other APIs the app draws resources from for the user, and how far their `/meta` has loaded (see `withSources`). */\n sources?: SourceStatus[]\n}\n\n/**\n * A source of resources and its `/meta`: `ready` once its resources are among the app's, `error` when it could not be\n * read, the reason in `error`.\n */\nexport type SourceStatus = { source: SourceRef; state: 'loading' | 'ready' } | { source: SourceRef; state: 'error'; error: Error }\n\nexport const allowEverything: ResourcePermissions = { create: true, update: true, delete: true, conditional: [] }\n","import { useQueries, useQueryClient, type UseQueryResult } from '@tanstack/react-query'\nimport { useMemo } from 'react'\nimport { sourceMeta, type Client, type SourceMeta, type SourceRef } from '@protobase/client'\nimport { keys } from './query-keys'\n\n/** A source's `/meta` as far as it has loaded: the part the app draws once it is `ready`. */\nexport type SourceResult = { source: SourceRef; state: 'loading' } | { source: SourceRef; state: 'ready'; meta: SourceMeta } | { source: SourceRef; state: 'error'; error: Error }\n\ntype Loaded = { etag: string; meta: SourceMeta }\n\n/** How long the app waits for a source's `/meta` before it shows the source's resources as unavailable. */\nexport const sourceTimeoutMs = 10_000\n\n// The combined results keep their identity while nothing changes, so what is merged from them does too.\nconst combine = (results: UseQueryResult<Loaded>[]) => results.map((result) => ({ data: result.data?.meta, error: result.error }))\n\n/**\n * Each source's `/meta`, read with the user's token from that API and scoped to the resources the app draws from it\n * (`sourceMeta`). Like the app's own, it is read again on window focus with `If-None-Match`, and a source that cannot be\n * read is an `error` without holding up the others or the app.\n */\nexport const useSourceMetas = (sources: readonly SourceRef[], clientOf: (source: SourceRef) => Client): SourceResult[] => {\n const queryClient = useQueryClient()\n const results = useQueries({\n queries: sources.map((source) => {\n const queryKey = keys.sourceMeta(source.url, source.resources)\n return {\n queryKey,\n staleTime: 0,\n refetchOnWindowFocus: 'always' as const,\n queryFn: async (): Promise<Loaded> => {\n const previous = queryClient.getQueryData<Loaded>(queryKey)\n const result = await clientOf(source).meta(previous?.etag, { signal: AbortSignal.timeout(sourceTimeoutMs) })\n if (result.status === 'unchanged') {\n if (!previous) throw new Error(`${source.label} answered 304 to a request without If-None-Match`)\n return previous\n }\n return { etag: result.etag, meta: sourceMeta(result.meta, source) }\n },\n }\n }),\n combine,\n })\n // A source read before keeps its resources when a later read fails, as the app's own `/meta` does.\n return useMemo(\n () =>\n sources.map((source, index): SourceResult => {\n const { data, error } = results[index]!\n if (data) return { source, state: 'ready', meta: data }\n if (error) return { source, state: 'error', error }\n return { source, state: 'loading' }\n }),\n [sources, results],\n )\n}\n","import type { MetaData, SourceStatus } from './meta-data'\nimport type { SourceResult } from './use-source-metas'\n\n/**\n * The app's `/meta` with the resources it draws from its sources: those of every source that is ready, with their views\n * and permissions, as if they were the app's own, and how far each source has loaded in `sources`. A source that is\n * loading or cannot be read adds no resources; the app shows its resources as unavailable (see `sourceStatusOf`).\n */\nexport const withSources = (meta: MetaData, results: readonly SourceResult[]): MetaData => {\n if (results.length === 0) return meta\n const ready = results.flatMap((result) => (result.state === 'ready' ? [result.meta] : []))\n const sources = results.map((result): SourceStatus => (result.state === 'error' ? { source: result.source, state: 'error', error: result.error } : { source: result.source, state: result.state }))\n return {\n ...meta,\n resources: { ...meta.resources, ...Object.fromEntries(ready.flatMap((part) => part.resources.map((model) => [model.name, model]))) },\n views: { ...meta.views, ...Object.fromEntries(ready.flatMap((part) => part.views.map((view) => [view.resource, view]))) },\n permissions: { ...meta.permissions, ...Object.assign({}, ...ready.map((part) => part.permissions)) },\n sources,\n }\n}\n\n/** The source the app draws `resource` from, with how far it has loaded; `undefined` for a resource of the app's own. */\nexport const sourceStatusOf = (meta: MetaData, resource: string) => meta.sources?.find((status) => status.source.resources.includes(resource))\n","import { Fragment, useEffect, type ReactNode } from 'react'\nimport type { Locale } from '@protobase/schema/internal'\nimport { activeLocale, setAppLocale } from './active-locale'\n\n/**\n * Puts the screens below in the language the app sets for everyone, from its `/meta`, or in the fallback when it sets\n * none; draws them anew when that changes, and tells the page which language it is in.\n */\nexport const AppLocale = ({ locale, children }: { locale: Locale | undefined; children: ReactNode }) => {\n setAppLocale(locale)\n const active = activeLocale()\n useEffect(() => {\n document.documentElement.lang = active\n }, [active])\n return <Fragment key={active}>{children}</Fragment>\n}\n","import { formatText, isTrans, type LayoutNode, type LayoutValue, type ReaderTexts } from '@protobase/layout'\nimport { createContext, useContext } from 'react'\n\n// The app's own texts in the user's language, from `/meta`, which a page's `<Trans>` elements format.\n\nexport const AppTexts = createContext<ReaderTexts | undefined>(undefined)\n\nexport const useAppTexts = () => useContext(AppTexts)\n\nconst isObject = (value: unknown): value is Record<string, LayoutValue> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A `<Trans>` as plain text in the user's language: what a prop drawn as text, a `title` or a `label`, shows. */\nexport const transText = (node: LayoutNode, texts: ReaderTexts | undefined) => formatText(texts, String(node.props.i18nKey), isObject(node.props.values) ? node.props.values : {})\n\nconst ownPropTexts = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutNode =>\n node.custom || !Object.values(node.props).some(isTrans) ? node : { ...node, props: Object.fromEntries(Object.entries(node.props).map(([name, value]) => [name, isTrans(value) ? transText(value, texts) : value])) }\n\n/**\n * The element with each `<Trans>` in its props as its text, so a block draws its `title` or `empty` as any text; a\n * `Tabs`' tabs' labels too, which it reads to draw its tab bar before each `Tab` draws.\n */\nexport const withPropTexts = (node: LayoutNode, texts: ReaderTexts | undefined): LayoutNode => {\n const own = ownPropTexts(node, texts)\n if (node.custom || node.type !== 'Tabs') return own\n const children = own.children.map((child) => (typeof child === 'string' ? child : ownPropTexts(child, texts)))\n return children.some((child, index) => child !== own.children[index]) ? { ...own, children } : own\n}\n","import type { ActionModel, FieldViewModel, LayoutItemModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { MetaData } from '../../data/meta-data'\nimport { catalogues, messages } from '../../locale/messages'\n\nconst namespace = 'app/built-in-views'\nconst text = messages(namespace)\ntype Id = Parameters<typeof text>[0]\n\n// The English catalogue names every text there is; the view's own text stays where it names none.\nconst translated = (id: string, given: string) => (Object.hasOwn(catalogues.en[namespace], id) ? text(id as Id) : given)\n\nconst field = (prefix: string, hints: FieldViewModel): FieldViewModel => ({\n ...hints,\n ...(hints.label !== undefined && { label: translated(`${prefix}.label`, hints.label) }),\n ...(hints.help !== undefined && { help: translated(`${prefix}.help`, hints.help) }),\n ...(hints.valueLabels && { valueLabels: Object.fromEntries(Object.entries(hints.valueLabels).map(([value, label]) => [value, translated(`${prefix}.values.${value}`, label)])) }),\n})\n\n// A top-level item's title, help and empty text, by its place in the layout.\nconst item = (prefix: string, shown: LayoutItemModel): LayoutItemModel => {\n const texts = shown as { title?: string; help?: string; empty?: string }\n return {\n ...shown,\n ...(texts.title !== undefined && { title: translated(`${prefix}.title`, texts.title) }),\n ...(texts.help !== undefined && { help: translated(`${prefix}.help`, texts.help) }),\n ...(texts.empty !== undefined && { empty: translated(`${prefix}.empty`, texts.empty) }),\n } as LayoutItemModel\n}\n\n// Activity's table sits in the events schema the app picks, `changes` unless it renames it, so it is keyed as `changes.history`.\nconst tableKey = (model: ResourceModel) =>\n model.name === 'record_history' && model.table.name === 'history' ? 'changes.history' : `${model.table.schema ?? 'public'}.${model.table.name}`\n\nconst action = (prefix: string, shown: ActionModel): ActionModel => ({\n ...shown,\n label: translated(`${prefix}.label`, shown.label),\n ...(shown.confirm !== undefined && { confirm: translated(`${prefix}.confirm`, shown.confirm) }),\n})\n\n/**\n * A built-in view with its texts in the active locale, from the `app/built-in-views` catalogue: its names, help, field\n * labels, help and value labels, the titles, help and empty texts of its top-level layout items, and its actions'\n * labels and questions, each keyed by the table of its resource and where the text sits, such as\n * `table_definitions.fields.fields.type.values.long_text`, so an app's own resource of the same name keeps its texts.\n * A text the catalogue does not name stays as `/meta` gives it.\n */\nexport const translatedView = (view: ViewModel, model: ResourceModel | undefined): ViewModel => {\n if (!model) return view\n const at = tableKey(model)\n return {\n ...view,\n ...(view.names && { names: { singular: translated(`${at}.names.singular`, view.names.singular), plural: translated(`${at}.names.plural`, view.names.plural) } }),\n ...(view.help !== undefined && { help: translated(`${at}.help`, view.help) }),\n fields: Object.fromEntries(Object.entries(view.fields).map(([name, hints]) => [name, field(`${at}.fields.${name}`, hints)])),\n layout: view.layout.map((shown, index) => item(`${at}.layout.${index}`, shown)),\n actions: view.actions.map((shown) => action(`${at}.actions.${shown.name}`, shown)),\n }\n}\n\n/** `/meta` with the texts of the built-in views the catalogue translates in the active locale (see `translatedView`). */\nexport const withTranslatedViews = (meta: MetaData): MetaData => ({ ...meta, views: Object.fromEntries(Object.entries(meta.views).map(([name, view]) => [name, translatedView(view, meta.resources[view.resource])])) })\n","import { createContext, useContext, useEffect, type ReactNode } from 'react'\n\n/** Keeps the launch splash up while a loading screen draws, and hides it once, when none does. */\nexport type SplashHold = {\n /** Holds the splash until the returned function releases it. */\n hold: () => () => void\n /** Marks the app as drawn: the splash hides as soon as nothing holds it. */\n start: () => void\n}\n\n/**\n * The hold on the launch splash: `hide` runs once, after `start`, as soon as no loading screen holds it. A screen that\n * replaces another in the same render holds it before the check, since the check waits for the end of that render's\n * effects, so the splash stays up from the auth check through `/meta` to the plugins without a gap.\n */\nexport const createSplashHold = (hide: () => void): SplashHold => {\n let holds = 0\n let started = false\n let hidden = false\n const settle = () =>\n queueMicrotask(() => {\n if (!started || hidden || holds > 0) return\n hidden = true\n hide()\n })\n return {\n hold: () => {\n holds += 1\n let released = false\n return () => {\n if (released) return\n released = true\n holds -= 1\n settle()\n }\n },\n start: () => {\n started = true\n settle()\n },\n }\n}\n\nexport const SplashHoldContext = createContext<SplashHold | undefined>(undefined)\n\nexport const SplashHoldProvider = ({ value, children }: { value: SplashHold; children: ReactNode }) => <SplashHoldContext.Provider value={value}>{children}</SplashHoldContext.Provider>\n\n/** Drawn by a loading screen: holds the launch splash while it shows. Nothing outside a `SplashHoldProvider`. */\nexport const HoldSplash = () => {\n const splash = useContext(SplashHoldContext)\n useEffect(() => splash?.hold(), [splash])\n return null\n}\n","import { messages } from '../locale/messages'\n\nexport const text = messages('app/meta-gate')\n","import { useContext, useMemo, type ReactNode } from 'react'\nimport { isApiError, routedClient } from '@protobase/client'\nimport { ClientProvider, useClient, useSourceClients } from '../data/api-provider'\nimport { MetaContext } from '../data/meta-context'\nimport { allowEverything, type MetaData } from '../data/meta-data'\nimport { useMeta } from '../data/use-meta'\nimport { useSourceMetas } from '../data/use-source-metas'\nimport { withSources } from '../data/with-sources'\nimport { AppLocale } from '../locale/app-locale'\nimport { AppTexts } from './pages/app-texts'\nimport { cn } from '../lib/cn'\nimport { revealLate } from '../primitives/skeleton'\nimport { Spinner } from '../primitives/spinner'\nimport { withTranslatedViews } from './built-in-views/translated-views'\nimport { HoldSplash } from './splash-hold'\nimport { text } from './meta-gate-messages'\n\nexport const useAdminMeta = () => {\n const meta = useContext(MetaContext)\n if (!meta) throw new Error('useAdminMeta must be used inside MetaGate')\n return meta\n}\n\nconst Notice = ({ title, children }: { title: string; children: ReactNode }) => (\n <div className=\"flex h-full min-h-48 flex-1 items-center justify-center p-8\">\n <div className=\"max-w-md text-center\">\n <h1 className=\"text-base font-semibold\">{title}</h1>\n <p className=\"mt-1 text-muted-foreground\">{children}</p>\n </div>\n </div>\n)\n\n/**\n * Draws the resources of the app's sources as its own: reads each source's `/meta`, merges what is ready into the app's,\n * translates the texts of the built-in views into the app's language (see `withTranslatedViews`), and gives what is below a client that sends each resource's calls to the API that serves it. The app does not wait\n * for a source; its resources join when it has loaded.\n */\nconst WithSources = ({ meta, children }: { meta: MetaData; children: ReactNode }) => {\n const own = useClient()\n const clientOf = useSourceClients()\n const declared = useMemo(() => (meta.sources ?? []).map((status) => status.source), [meta.sources])\n const results = useSourceMetas(declared, clientOf)\n const merged = useMemo(() => withSources(meta, results), [meta, results])\n const routing = useMemo(() => {\n const byResource = new Map(declared.flatMap((source) => source.resources.map((resource) => [resource, source] as const)))\n const resourceClient = (resource: string) => {\n const source = byResource.get(resource)\n return source && clientOf(source)\n }\n return { client: routedClient(own, resourceClient), resourceClient }\n }, [declared, own, clientOf])\n return (\n <ClientProvider client={routing.client} resourceClient={routing.resourceClient}>\n <AppLocale locale={meta.locale}>\n <AppTexts.Provider value={meta.texts}>\n <TranslatedMeta meta={merged}>{children}</TranslatedMeta>\n </AppTexts.Provider>\n </AppLocale>\n </ClientProvider>\n )\n}\n\n// Below `AppLocale`, which draws it anew when the language changes, so the built-in views read the language it sets.\nconst TranslatedMeta = ({ meta, children }: { meta: MetaData; children: ReactNode }) => {\n // `[meta]` is enough: `AppLocale` renders its children under `key={active}`, so a language switch remounts this\n // component and the memo runs again in the new language.\n const translated = useMemo(() => withTranslatedViews(meta), [meta])\n return <MetaContext.Provider value={translated}>{children}</MetaContext.Provider>\n}\n\n/**\n * Renders its children once `/meta` has loaded, with the resources of the app's sources as they load. The sources'\n * layer is always there, also without sources, so `/meta` gaining or losing them never draws the app anew.\n */\nexport const MetaGate = ({ children }: { children: ReactNode }) => {\n const meta = useMeta()\n if (meta.isPending) {\n return (\n <div className={cn('flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground', revealLate)}>\n <HoldSplash />\n <Spinner /> {text('loading')}\n </div>\n )\n }\n if (meta.error) {\n return <Notice title={text('cannotReach')}>{isApiError(meta.error) ? meta.error.message : text('noAnswer')}</Notice>\n }\n return <WithSources meta={meta.data}>{children}</WithSources>\n}\n\nexport { Notice }\n\n/** What the signed-in user may do with a resource; everything when the server does not say. */\nexport const usePermissions = (resource: string) => useAdminMeta().permissions[resource] ?? allowEverything\n","import { useSyncExternalStore } from 'react'\n\n/** Follows a CSS media query, for layout decisions that cannot be made with classes alone. */\nexport const useMediaQuery = (query: string) =>\n useSyncExternalStore(\n (onChange) => {\n const list = window.matchMedia(query)\n list.addEventListener('change', onChange)\n return () => list.removeEventListener('change', onChange)\n },\n () => window.matchMedia(query).matches,\n () => false,\n )\n\n/** The `md` breakpoint: where the sidebar stops being a drawer and tables stop squeezing. */\nexport const useIsDesktop = () => useMediaQuery('(min-width: 768px)')\n\n/** Below the `sm` breakpoint: a phone, where a list opens in its cards display. */\nexport const useIsXs = () => useMediaQuery('not all and (min-width: 640px)')\n","import type { CardPhotosModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport type { RecordPhotos } from '@protobase/client'\n\n/** Where a loaded row keeps its photos, beside its fields, as it keeps its `id`. */\nexport const photosKey = '$photos'\n\n/** The photos a list's rows load with: those its cards displays name, which the server checks they all share. */\nexport const listPhotos = (view: ViewModel | undefined): CardPhotosModel | undefined => {\n for (const display of view?.list?.displays ?? []) if (display.kind === 'cards' && display.photos) return display.photos\n return undefined\n}\n\n/** The rows, each with its record's photos from a list call's `photos`, when the call asked for them; none for a record it left out. */\nexport const withPhotos = (model: ResourceModel, rows: Array<Record<string, unknown>>, photos: RecordPhotos | undefined) => {\n if (photos === undefined || model.primaryKey.length !== 1) return rows\n const key = model.primaryKey[0]!\n return rows.map((row) => ({ ...row, [photosKey]: photos[String(row[key])] ?? [] }))\n}\n","/** The fields of `names` with a value in `record`: an empty one, null or an empty text, is left out, never shown as `—`. */\nexport const filledFields = (record: Record<string, unknown>, names: readonly string[]) => names.filter((name) => record[name] !== null && record[name] !== undefined && record[name] !== '')\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/displays')\n","import type { ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { enumLabel, printFilter, where } from '@protobase/schema'\nimport { isApiError } from '@protobase/client'\nimport { recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { text } from './messages'\n\nexport type BoardDisplayModel = Extract<ListDisplayModel, { kind: 'board' }>\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\n/** One column of a board: the value its records have, `null` for those without one, and its heading. */\nexport type BoardColumn = { value: string | null; label: string }\n\n/**\n * A board's columns: one per value of its enum field, in the order the field lists them, headed by the view's value\n * label; then, when the field may be empty, one for the records without a value.\n */\nexport const boardColumns = (model: ResourceModel, view: ViewModel | undefined, display: BoardDisplayModel): BoardColumn[] => {\n const field = model.fields[display.by]\n if (!field) return []\n const hints = view?.fields[display.by]\n const values = (field.enumValues ?? []).map((value) => ({ value, label: enumLabel(value, hints?.valueLabels) }))\n if (!field.nullable) return values\n return [...values, { value: null, label: text('noValue', { label: hints?.label ?? humanize(display.by) }) }]\n}\n\n/** The field a board orders each column by: the resource's `.position()`, when its records are ordered as one rather than within a parent. */\nexport const boardRank = (model: ResourceModel) => (model.position && model.position.within === undefined ? model.position.field : undefined)\n\n/** The list's filter, its search included, narrowed to the records of one column. */\nexport const columnFilter = (filter: string, by: string, value: string | null) => {\n const column = printFilter(value === null ? where.isNull(by) : where.eq(by, value))\n return filter === '' ? column : `(${filter}) AND ${column}`\n}\n\n/** The built-in card a board draws for each record: that of a cards display of the board's fields. */\nexport const boardCard = (model: ResourceModel, view: ViewModel | undefined, display: BoardDisplayModel): CardsDisplayModel => ({\n kind: 'cards',\n name: display.name,\n title: display.title ?? recordTitleField(model, view),\n ...(display.subtitle !== undefined && { subtitle: display.subtitle }),\n ...(display.badge !== undefined && { badge: display.badge }),\n ...(display.meta && { meta: display.meta }),\n})\n\n/** Why the server refused a move: the reasons it gives per field, such as a `validate` message, else its detail. */\nexport const refusalReason = (error: unknown) => {\n if (!isApiError(error)) return error instanceof Error ? error.message : text('somethingWrong')\n const reasons = error.errors.map((entry) => entry.message)\n return reasons.length > 0 ? reasons.join('; ') : error.message\n}\n","import type { FieldModel, FieldViewModel, ListDisplayModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { encodeKey, tableDisplay, textPlaceholders } from '@protobase/schema/internal'\nimport { listColumnNames } from '../../live/columns-from-model'\nimport { displayValue } from '../../live/display-value'\nimport { recordKey, recordTitleField } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { photosKey } from '../../live/row-photos'\nimport { filledFields } from '../filled-fields'\nimport { boardCard } from './board-columns'\nimport { text } from './messages'\n\n/** A row as a list display gets it: its key, the record as the list API gives it, and names of the records its relations point at. */\nexport type ListDisplayRow = {\n /** The record's key, in the text form the record API takes. */\n key: string\n record: Record<string, unknown>\n /** The name of the record a relation field points at, for the relations the list shows. */\n labels: Record<string, string>\n /** The files of its first photos, when the list loaded the photos its cards display names. */\n photos?: unknown[]\n}\n\n/** What a card component of a cards display (`d.cards(..., { card })`) gets: the record it draws, of the display's fields. */\nexport type RecordCardProps = { row: ListDisplayRow }\n\n/** One choice of the list's display switch: the table first, then the view's displays. */\nexport type DisplayChoice = { name: string; label: string; icon?: string }\n\ntype CardsDisplayModel = Extract<ListDisplayModel, { kind: 'cards' }>\n\nexport const displaysOf = (view: ViewModel | undefined): ListDisplayModel[] => view?.list?.displays ?? []\n\n/** The display a list is set to open in: `preferred`, such as a block's `display`, else the view's `default`, else none. */\nconst configuredDisplay = (view: ViewModel | undefined, preferred?: string) => preferred ?? view?.list?.default\n\n/**\n * The display a list opens in when its address names none: the one it is set to open in (`configuredDisplay`) on any\n * screen; with none set, the table, or below the `sm` breakpoint the list's first cards display when it has one.\n */\nexport const defaultDisplay = (view: ViewModel | undefined, xs: boolean, preferred?: string): string => {\n const configured = configuredDisplay(view, preferred)\n if (configured !== undefined) return configured\n if (!xs) return tableDisplay\n return displaysOf(view).find((display) => display.kind === 'cards')?.name ?? tableDisplay\n}\n\n/** The name of the list a phone shows for a list without a cards display. */\nexport const rowsDisplay = 'rows'\n\n/**\n * The list a phone shows for a list without a cards display, as a cards display of a row per record: the title, the\n * first enum column as a badge on the right, and the next two columns, booleans left out, on a muted line below.\n * `undefined` for a view with a cards display, or a display of its own named `rows`.\n */\nexport const phoneRows = (model: ResourceModel, view: ViewModel | undefined): CardsDisplayModel | undefined => {\n if (displaysOf(view).some((display) => display.kind === 'cards' || display.name === rowsDisplay)) return undefined\n const title = recordTitleField(model, view)\n const candidates = listColumnNames(model, view).filter((name) => name !== title && model.fields[name] !== undefined)\n const badge = candidates.find((name) => model.fields[name]!.type === 'enum')\n const footer = candidates.filter((name) => name !== badge && model.fields[name]!.type !== 'boolean').slice(0, 2)\n return { kind: 'cards', name: rowsDisplay, label: text('list'), icon: 'list', title, ...(badge !== undefined && { badge }), footer }\n}\n\nconst isPhoneRows = (view: ViewModel | undefined, display: ListDisplayModel) => display.name === rowsDisplay && !displaysOf(view).some((other) => other.name === rowsDisplay)\n\n/**\n * The display a list page opens in when its address names none: `defaultDisplay`, but below the `sm` breakpoint the\n * phone's rows (`phoneRows`) in place of a table the view is not set to open in.\n */\nexport const listDefaultDisplay = (model: ResourceModel, view: ViewModel | undefined, xs: boolean) => {\n const display = defaultDisplay(view, xs)\n return xs && configuredDisplay(view) === undefined && display === tableDisplay && phoneRows(model, view) ? rowsDisplay : display\n}\n\n/** The display a list page shows for the address's `name`: `shownDisplay`, or the phone's rows when it names them, on any screen. */\nexport const shownListDisplay = (model: ResourceModel, view: ViewModel | undefined, name: string): ListDisplayModel | undefined =>\n (name === rowsDisplay ? phoneRows(model, view) : undefined) ?? shownDisplay(view, name)\n\n/** The display a list shows for the address's `name`: `undefined` for the table, and the view's default for a name it does not have. */\nexport const shownDisplay = (view: ViewModel | undefined, name: string): ListDisplayModel | undefined => {\n if (name === tableDisplay) return undefined\n const named = (wanted: string | undefined) => displaysOf(view).find((display) => display.name === wanted)\n return named(name) ?? named(view?.list?.default)\n}\n\nconst defaultIcons: Partial<Record<ListDisplayModel['kind'], string>> = { cards: 'cards', map: 'map', board: 'kanban', calendar: 'calendar', timeline: 'timeline' }\n\nexport const displayChoices = (view: ViewModel | undefined): DisplayChoice[] => [\n { name: tableDisplay, label: text('table'), icon: 'table' },\n ...displaysOf(view).map((display) => ({ name: display.name, label: display.label ?? humanize(display.name), icon: display.icon ?? defaultIcons[display.kind] })),\n]\n\n/** The list page's display switch: `displayChoices`, and below the `sm` breakpoint the phone's rows when it has them. */\nexport const listDisplayChoices = (model: ResourceModel, view: ViewModel | undefined, xs: boolean): DisplayChoice[] => {\n const choices = displayChoices(view)\n return xs && phoneRows(model, view) ? [...choices, { name: rowsDisplay, label: text('list'), icon: 'list' }] : choices\n}\n\n/** The fields a cards display shows, its title the view's title field when it names none. */\nexport const cardFields = (model: ResourceModel, view: ViewModel | undefined, display: CardsDisplayModel) => ({\n image: display.image,\n title: display.title ?? recordTitleField(model, view),\n subtitle: display.subtitle,\n amount: display.amount ?? [],\n badge: display.badge,\n code: display.code,\n meta: display.meta ?? [],\n footer: display.footer ?? [],\n flags: display.flags ?? [],\n})\n\n/** The meta fields a card shows for a row: those with a value, so a listing for rent only shows no purchase price. */\nexport const filledMeta = (row: ListDisplayRow, meta: string[]) => filledFields(row.record, meta)\n\n/** The amount field a card shows for a row: the first with a value, so a listing for rent only shows its rent. */\nexport const filledAmount = (row: ListDisplayRow, amount: string[]): string | undefined => filledMeta(row, amount)[0]\n\n/** The code field a card shows for a row: the field when it has a value, so an empty one leaves no block behind. */\nexport const filledCode = (row: ListDisplayRow, code: string | undefined): string | undefined => (code === undefined ? undefined : filledMeta(row, [code])[0])\n\n/** A card's code as stored when its field is text, line breaks, spaces and markdown marks all; undefined for another type, which shows its display value. */\nexport const rawCode = (field: FieldModel | undefined, value: unknown) => (field?.type === 'text' && typeof value === 'string' ? value : undefined)\n\n/** A card's amount split for drawing: the number with its prefix, such as `€1,450`, apart from its suffix, such as ` /month`. */\nexport const amountParts = (field: FieldModel, value: unknown, hints: FieldViewModel = {}): { amount: string; suffix?: string } => {\n const { suffix, ...unsuffixed } = hints\n const numeric = field.type === 'decimal' || field.type === 'integer' || field.type === 'bigint'\n if (!numeric || suffix === undefined || hints.format === 'percent') return { amount: displayValue(field, value, hints) }\n return { amount: displayValue(field, value, unsuffixed), suffix }\n}\n\n/** The cards display whose card a map shows for a record: the one it names, else the list's first, else the title alone. */\nexport const mapCards = (view: ViewModel | undefined, display: Extract<ListDisplayModel, { kind: 'map' }>): CardsDisplayModel => {\n const cards = displaysOf(view).filter((other): other is CardsDisplayModel => other.kind === 'cards')\n const named = display.cards === undefined ? cards[0] : cards.find((other) => other.name === display.cards)\n return named ?? { kind: 'cards', name: display.name }\n}\n\n/** Every field a display shows, the fields its rows are loaded and labelled for. */\nexport const shownFields = (model: ResourceModel, view: ViewModel | undefined, display: ListDisplayModel): string[] => {\n if (display.kind === 'custom') return display.fields\n if (display.kind === 'map') return [display.latitude, display.longitude, ...shownFields(model, view, mapCards(view, display))]\n if (display.kind === 'board') {\n const card = boardCard(model, view, display)\n return [display.by, card.title, card.subtitle, card.badge, ...(card.meta ?? [])].filter((name): name is string => name !== undefined)\n }\n if (display.kind === 'calendar') return [display.start, display.end, display.title ?? recordTitleField(model, view)].filter((name): name is string => name !== undefined)\n if (display.kind === 'timeline') return [display.start, display.end, display.group, display.title ?? recordTitleField(model, view)].filter((name): name is string => name !== undefined)\n const { image, title, subtitle, amount, badge, code, meta, footer, flags } = cardFields(model, view, display)\n return [image, title, subtitle, ...amount, badge, code, ...meta, ...footer, ...flags].filter((name): name is string => name !== undefined)\n}\n\n// The fields the view's actions read from a row: each checklist's `from` field, which holds the row's own boxes.\nconst actionFields = (view: ViewModel | undefined) =>\n (view?.actions ?? []).flatMap((action) => (action.inputs ?? []).flatMap((input) => (input.from === undefined ? [] : [input.from])))\n\n// The fields the link texts of shown fields take from the row, such as a report's title for its url.\nconst linkTextFields = (view: ViewModel | undefined, shown: string[]) => shown.flatMap((name) => textPlaceholders(view?.fields[name]?.linkText ?? ''))\n\n/**\n * The fields to load the list's rows with: the table's columns, every display's, the fields their link texts name\n * and those the view's actions read, so one load serves them all.\n */\nexport const loadedFields = (model: ResourceModel, view: ViewModel | undefined, columns: string[]) => {\n const rows = phoneRows(model, view)\n const displays = rows ? [...displaysOf(view), rows] : displaysOf(view)\n const shown = [...columns, ...displays.flatMap((display) => shownFields(model, view, display))]\n return [...new Set([...shown, ...linkTextFields(view, shown), ...actionFields(view)])]\n}\n\n/**\n * The sortable fields a display shows, for the sort menu that stands in for column headers; for the phone's rows, those\n * of the table's columns and the title, as the table's headers sort by.\n */\nexport const sortFields = (model: ResourceModel, view: ViewModel | undefined, display: ListDisplayModel) => {\n const shown = isPhoneRows(view, display) ? [recordTitleField(model, view), ...listColumnNames(model, view)] : shownFields(model, view, display)\n return [...new Set(shown)].filter((name) => model.fields[name]?.sortable)\n}\n\nconst isLabelled = (value: unknown): value is { id: unknown; name: string } => typeof value === 'object' && value !== null && 'id' in value && 'name' in value\n\n/**\n * A loaded row, its relations as `{ id, name }`, split into the record as the API gives it, the relations' names and\n * the photos it was loaded with.\n */\nexport const displayRow = (model: ResourceModel, row: Record<string, unknown>): ListDisplayRow => {\n const record: Record<string, unknown> = {}\n const labels: Record<string, string> = {}\n const photos = Array.isArray(row[photosKey]) ? (row[photosKey] as unknown[]) : undefined\n for (const [name, value] of Object.entries(row)) {\n if ((name === 'id' || name === photosKey) && !Object.hasOwn(model.fields, name)) continue\n if (model.fields[name]?.type === 'relation' && isLabelled(value)) {\n record[name] = value.id\n labels[name] = value.name\n } else {\n record[name] = value\n }\n }\n return { key: encodeKey(recordKey(model, record)), record, labels, ...(photos && { photos }) }\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\n\nexport type Sort = { columnId: string; direction: 'asc' | 'desc' }\n\n/**\n * The order a list opens in: the view's sort, else the primary key's when it is sortable. Otherwise none, as the API\n * refuses a sort by a field that is not sortable and orders a list without one by its key anyway.\n */\nexport const defaultOrderBy = (model: ResourceModel, view: ViewModel | undefined) => {\n const sort = view?.list?.sort?.[0]\n if (sort) return `${sort[0]} ${sort[1]}`\n const key = model.primaryKey[0]!\n return model.fields[key]?.sortable ? `${key} asc` : ''\n}\n\nexport const parseSort = (orderBy: string): Sort => {\n const [columnId = '', direction] = orderBy.trim().split(/\\s+/)\n return { columnId, direction: direction === 'desc' ? 'desc' : 'asc' }\n}\n\nexport const sortToOrderBy = (sort: Sort) => `${sort.columnId} ${sort.direction}`\n","import type { AppAddress, CalendarView, FilterLayout, MapView, ResourceModel, TimelineView, ViewModel } from '@protobase/schema'\nimport { encodeKey, viewOfList } from '@protobase/schema/internal'\nimport { defaultDisplay, listDefaultDisplay } from './displays/list-displays'\nimport { defaultOrderBy } from './list-order'\n\n/**\n * A list as the app shows it: every value there, the view's default where the address names none; `map`, `calendar`,\n * `timeline` and `savedSearch`, the saved search it was opened from, have none.\n */\nexport type ListAddress = { kind: 'list'; resource: string; list?: string; display: string; filter: string; orderBy: string; filterLayout: FilterLayout; map?: MapView; calendar?: CalendarView; timeline?: TimelineView; savedSearch?: string }\n\n/** The address the app shows, as logical values. A record's key is in the text form the record API takes. */\nexport type CurrentAddress =\n | ListAddress\n | { kind: 'record'; resource: string; key: string; edit?: true; open?: readonly string[]; tab?: string; standard?: true; call?: 'join'; version?: number; run?: string; panel?: string; file?: string }\n | { kind: 'create'; resource: string; values?: Readonly<Record<string, string>> }\n | { kind: 'page'; page: string; tab?: string; params?: Readonly<Record<string, string>> }\n\n/** What can change about the list the app shows; `undefined` returns a value to its default. */\nexport type ListChange = Partial<Omit<ListAddress, 'kind' | 'resource' | 'list'>>\n\nexport type ListDefaults = Pick<ListAddress, 'display' | 'orderBy' | 'filterLayout' | 'filter'>\n\n/**\n * The resource whose records a list shows, with its view: the list's own, or, when its view has `listOf`, the resource\n * that relation points at, if the caller can see it.\n */\nexport const listedResource = (resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, resource: string, list?: string) => {\n const model = resources[resource]\n const own = viewOfList(views[resource], list)\n const listOf = own?.listOf\n const target = listOf === undefined ? undefined : model?.fields[listOf]?.relation?.resource\n return target !== undefined && resources[target] ? { model: resources[target], view: views[target], listOf: true } : { model, view: own, listOf: false }\n}\n\n/** What a list shows when its address names nothing: its default display for the screen, the list's sort, the filters in a bar. */\nexport const listDefaults = (model: ResourceModel | undefined, view: ViewModel | undefined, xs = false): ListDefaults => ({\n display: model ? listDefaultDisplay(model, view, xs) : defaultDisplay(view, xs),\n orderBy: model ? defaultOrderBy(model, view) : '',\n filterLayout: 'bar',\n filter: view?.list?.filter ?? '',\n})\n\n/** The address as read from the location, with a list's defaults filled in and a record's key as text. */\nexport const currentAddress = (read: AppAddress | undefined, defaults: (resource: string, list?: string) => ListDefaults): CurrentAddress | undefined => {\n if (read?.kind === 'record') return { kind: 'record', resource: read.resource, key: encodeKey(read.key), ...(read.edit && { edit: true as const }), ...(read.open && { open: read.open }), ...(read.tab && { tab: read.tab }), ...(read.standard && { standard: true as const }), ...(read.call && { call: read.call }), ...(read.version !== undefined && { version: read.version }), ...(read.run && { run: read.run }), ...(read.panel && { panel: read.panel }), ...(read.file && { file: read.file }) }\n if (read?.kind !== 'list') return read\n return { ...defaults(read.resource, read.list), ...read }\n}\n\n/** The list address after `change`, leaving out every value that is empty or its default (a cleared filter is written as an empty `filter=` when the default is not empty), so `/<resource>` stays clean. */\nexport const changedList = (read: Extract<AppAddress, { kind: 'list' }>, change: ListChange, defaults: ListDefaults): AppAddress => {\n const next = { ...read, ...change }\n const differs = (name: keyof ListDefaults) => next[name] !== undefined && next[name] !== defaults[name]\n return {\n kind: 'list',\n resource: read.resource,\n ...(read.list && { list: read.list }),\n ...(differs('filter') && { filter: next.filter }),\n ...(differs('display') && { display: next.display }),\n ...(differs('orderBy') && { orderBy: next.orderBy }),\n ...(differs('filterLayout') && { filterLayout: next.filterLayout }),\n ...(next.map && { map: next.map }),\n ...(next.calendar && { calendar: next.calendar }),\n ...(next.timeline && { timeline: next.timeline }),\n ...(next.savedSearch && { savedSearch: next.savedSearch }),\n }\n}\n","import { useCallback, useMemo, type AnchorHTMLAttributes } from 'react'\nimport { appPath, readAppPath, type AppAddress } from '@protobase/schema'\nimport { useIsXs } from '../lib/use-media-query'\nimport { changedList, currentAddress, listDefaults, listedResource, type ListChange } from './current-address'\nimport { useAdminMeta } from './meta-gate'\nimport { Link, useRouter, type NavigateOptions } from './router'\n\nexport type { CurrentAddress, ListAddress, ListChange } from './current-address'\n\n/**\n * The app's address as logical values, and the ways to change it: `set` changes the list in place, `listTo` is the\n * list after a change for a link to it, `go` moves to\n * another address, `href` is an address for an `<a href>`, `open` follows such an href and `back` goes back to one.\n * Every component reads and writes the address through this hook, never the query string or a path of its own.\n */\nexport const useAppAddress = () => {\n const { path, params, basePath, navigate, back: backTo } = useRouter()\n const { pages, resources, views } = useAdminMeta()\n const xs = useIsXs()\n const pageNames = useMemo(() => new Set(Object.keys(pages)), [pages])\n const query = params.toString()\n const read = useMemo(() => readAppPath(query ? `${path}?${query}` : path, pageNames), [path, query, pageNames])\n const defaults = useCallback(\n (resource: string, list?: string) => {\n const listed = listedResource(resources, views, resource, list)\n return listDefaults(listed.model, listed.view, xs)\n },\n [resources, views, xs],\n )\n const address = useMemo(() => currentAddress(read, defaults), [read, defaults])\n\n const go = useCallback((to: AppAddress, options?: NavigateOptions) => navigate(appPath(to), options), [navigate])\n\n const listTo = useCallback(\n (change: ListChange) => {\n if (read?.kind !== 'list') throw new Error('listTo and set change the list the app shows; use go to move to another address')\n return changedList(read, change, defaults(read.resource, read.list))\n },\n [read, defaults],\n )\n\n const set = useCallback((change: ListChange) => go(listTo(change), { replace: true }), [listTo, go])\n\n const href = useCallback((to: AppAddress) => appPath(to, basePath), [basePath])\n\n // The shell's links carry the base path, as hrefs must; the router takes the path below it.\n const below = useCallback((target: string) => (target.startsWith(`${basePath}/`) ? target.slice(basePath.length) : target), [basePath])\n const open = useCallback((target: string) => navigate(below(target)), [below, navigate])\n const back = useCallback((target: string) => backTo(below(target)), [below, backTo])\n\n return { address, set, listTo, go, href, open, back }\n}\n\n/** A link to an address in the app: an ordinary anchor that the router follows without reloading the page. */\nexport const AppLink = ({ to, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: AppAddress; replace?: boolean }) => <Link to={appPath(to)} {...rest} />\n"],"mappings":"+nCAEA,IAAaiF,GACX,EACA,EACA,EACA,KACiB,CAAE,OAAM,UAAS,OAAM,MAAK,GAIzCC,IAAY,EAAW,IAAc,CACzC,IAAIC,EAAM,MAAM,KAAK,CAAE,OAAQC,EAAE,OAAS,CAAE,GAAI,EAAG,IAAMC,CAAC,EAC1D,IAAK,IAAIA,EAAI,EAAGA,GAAKpD,EAAE,OAAQ,IAAK,CAClC,IAAMqD,EAAO,CAACD,CAAC,EACf,IAAK,IAAIE,EAAI,EAAGA,GAAKH,EAAE,OAAQ,IAAK,CAClC,IAAMI,EAAOvD,EAAEoD,EAAI,KAAOD,EAAEG,EAAI,GAAK,EAAI,EACzC,EAAKA,GAAK,KAAK,IAAIJ,EAAII,GAAM,EAAGD,EAAKC,EAAI,GAAM,EAAGJ,EAAII,EAAI,GAAMC,CAAI,CACtE,CACA,EAAMF,CACR,CACA,OAAOH,EAAIC,EAAE,OACf,EAEaK,IAAW,EAAc,IAAyB,CAC7D,IAAMC,EAAQC,EAAK,YAAY,EACzBC,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