@selvajs/selva 4.21.0-beta.12 → 4.21.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +2 -2
- package/build/client/_app/immutable/assets/0.DOeHn583.css +2 -0
- package/build/client/_app/immutable/assets/0.DOeHn583.css.br +0 -0
- package/build/client/_app/immutable/assets/0.DOeHn583.css.gz +0 -0
- package/build/client/_app/immutable/assets/rhino3dm.CWOyICcB.wasm +0 -0
- package/build/client/_app/immutable/assets/rhino3dm.CWOyICcB.wasm.br +0 -0
- package/build/client/_app/immutable/assets/rhino3dm.CWOyICcB.wasm.gz +0 -0
- package/build/client/_app/immutable/chunks/2rFska3d.js +1 -0
- package/build/client/_app/immutable/chunks/2rFska3d.js.br +1 -0
- package/build/client/_app/immutable/chunks/2rFska3d.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{BgqLT1eu.js → 5M5n6ftO.js} +57 -56
- package/build/client/_app/immutable/chunks/5M5n6ftO.js.br +0 -0
- package/build/client/_app/immutable/chunks/5M5n6ftO.js.gz +0 -0
- package/build/client/_app/immutable/chunks/71J-lVIC.js +7 -0
- package/build/client/_app/immutable/chunks/71J-lVIC.js.br +0 -0
- package/build/client/_app/immutable/chunks/71J-lVIC.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{BFXrROAz.js → BCbumNc2.js} +1 -1
- package/build/client/_app/immutable/chunks/BCbumNc2.js.br +0 -0
- package/build/client/_app/immutable/chunks/BCbumNc2.js.gz +0 -0
- package/build/client/_app/immutable/chunks/BEzPIk5e.js +1 -0
- package/build/client/_app/immutable/chunks/BEzPIk5e.js.br +0 -0
- package/build/client/_app/immutable/chunks/BEzPIk5e.js.gz +0 -0
- package/build/client/_app/immutable/chunks/B_4x1b7P.js +1 -0
- package/build/client/_app/immutable/chunks/B_4x1b7P.js.br +0 -0
- package/build/client/_app/immutable/chunks/B_4x1b7P.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{D-7q85bk.js → Bs2bQTgl.js} +1 -1
- package/build/client/_app/immutable/chunks/Bs2bQTgl.js.br +0 -0
- package/build/client/_app/immutable/chunks/Bs2bQTgl.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{C3KJF0qD.js → CzHxHvr2.js} +1 -1
- package/build/client/_app/immutable/chunks/CzHxHvr2.js.br +0 -0
- package/build/client/_app/immutable/chunks/CzHxHvr2.js.gz +0 -0
- package/build/client/_app/immutable/chunks/Db9exncB.js +1 -0
- package/build/client/_app/immutable/chunks/Db9exncB.js.br +0 -0
- package/build/client/_app/immutable/chunks/Db9exncB.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{BfaVYyF5.js → FIoX_cjM.js} +1 -1
- package/build/client/_app/immutable/chunks/FIoX_cjM.js.br +0 -0
- package/build/client/_app/immutable/chunks/FIoX_cjM.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{D1Hh95EK.js → aBYenH6-.js} +1 -1
- package/build/client/_app/immutable/chunks/aBYenH6-.js.br +0 -0
- package/build/client/_app/immutable/chunks/aBYenH6-.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.DkBodfd-.js → app.BP5swwM7.js} +2 -2
- package/build/client/_app/immutable/entry/app.BP5swwM7.js.br +0 -0
- package/build/client/_app/immutable/entry/app.BP5swwM7.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{1.rWI13pjK.js → 1.DmBjtFLw.js} +1 -1
- package/build/client/_app/immutable/nodes/1.DmBjtFLw.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.DmBjtFLw.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{2.BC_cXN9D.js → 2.CWOFnTAV.js} +1 -1
- package/build/client/_app/immutable/nodes/2.CWOFnTAV.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CWOFnTAV.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{20.BcDEIVaI.js → 20.4vwwwrQ_.js} +1 -1
- package/build/client/_app/immutable/nodes/20.4vwwwrQ_.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.4vwwwrQ_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.C1xtue6U.js +1 -0
- package/build/client/_app/immutable/nodes/21.C1xtue6U.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.C1xtue6U.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{25.BhiThFEd.js → 25.DR2ojPn5.js} +1 -1
- package/build/client/_app/immutable/nodes/25.DR2ojPn5.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.DR2ojPn5.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{3.BVyOvlCQ.js → 3.GtVSkcEP.js} +1 -1
- package/build/client/_app/immutable/nodes/3.GtVSkcEP.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.GtVSkcEP.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{30.B6pd-F-z.js → 30.Cd56Qv6o.js} +5 -6
- package/build/client/_app/immutable/nodes/30.Cd56Qv6o.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.Cd56Qv6o.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{5.Cf8uTJgI.js → 5.wbpOzblK.js} +1 -1
- package/build/client/_app/immutable/nodes/5.wbpOzblK.js.br +0 -0
- package/build/client/_app/immutable/nodes/5.wbpOzblK.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{6.DMoGaSJA.js → 6.B2HdJrZB.js} +1 -1
- package/build/client/_app/immutable/nodes/6.B2HdJrZB.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.B2HdJrZB.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{7.DTPvNOH_.js → 7.BuWU0YDv.js} +1 -1
- package/build/client/_app/immutable/nodes/7.BuWU0YDv.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.BuWU0YDv.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/.vite/manifest.json +17 -1
- package/build/server/_app/immutable/assets/_layout.DOeHn583.css +2 -0
- package/build/server/_app/immutable/assets/rhino3dm.CWOyICcB.wasm +0 -0
- package/build/server/chunks/grasshopper.js +17 -10
- package/build/server/chunks/grasshopper.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/localeContext.svelte.js +70 -0
- package/build/server/chunks/localeContext.svelte.js.map +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +42 -0
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/rhino3dm.js +5 -0
- package/build/server/chunks/rhino3dm.js.map +1 -0
- package/build/server/chunks/schema.js +1 -1
- package/build/server/chunks/schema.js.map +1 -1
- package/build/server/entries/hooks.server.js +29 -1
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/admin/organizations/_page.server.ts.js +4 -9
- package/build/server/entries/pages/admin/organizations/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +7219 -1202
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/team/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/team/members/_page.server.ts.js +4 -2
- package/build/server/entries/pages/team/members/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/team/members/_page.svelte.js +6 -5
- package/build/server/entries/pages/team/members/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/team/projects/_page.server.ts.js +4 -10
- package/build/server/entries/pages/team/projects/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/team/reclaim/_page.server.ts.js +6 -13
- package/build/server/entries/pages/team/reclaim/_page.server.ts.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/0.js +2 -2
- package/build/server/nodes/1.js +1 -1
- package/build/server/nodes/2.js +1 -1
- package/build/server/nodes/20.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/nodes/25.js +1 -1
- package/build/server/nodes/3.js +1 -1
- package/build/server/nodes/30.js +1 -1
- package/build/server/nodes/5.js +1 -1
- package/build/server/nodes/6.js +1 -1
- package/build/server/nodes/7.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +10 -10
- package/templates/.env.example +4 -1
- package/build/client/_app/immutable/assets/0.BNUTD3F8.css +0 -2
- package/build/client/_app/immutable/assets/0.BNUTD3F8.css.br +0 -0
- package/build/client/_app/immutable/assets/0.BNUTD3F8.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BFXrROAz.js.br +0 -0
- package/build/client/_app/immutable/chunks/BFXrROAz.js.gz +0 -0
- package/build/client/_app/immutable/chunks/BfaVYyF5.js.br +0 -0
- package/build/client/_app/immutable/chunks/BfaVYyF5.js.gz +0 -0
- package/build/client/_app/immutable/chunks/BgqLT1eu.js.br +0 -0
- package/build/client/_app/immutable/chunks/BgqLT1eu.js.gz +0 -0
- package/build/client/_app/immutable/chunks/C3KJF0qD.js.br +0 -0
- package/build/client/_app/immutable/chunks/C3KJF0qD.js.gz +0 -0
- package/build/client/_app/immutable/chunks/CUlE4Eja.js +0 -1
- package/build/client/_app/immutable/chunks/CUlE4Eja.js.br +0 -0
- package/build/client/_app/immutable/chunks/CUlE4Eja.js.gz +0 -0
- package/build/client/_app/immutable/chunks/D-7q85bk.js.br +0 -0
- package/build/client/_app/immutable/chunks/D-7q85bk.js.gz +0 -0
- package/build/client/_app/immutable/chunks/D1Hh95EK.js.br +0 -0
- package/build/client/_app/immutable/chunks/D1Hh95EK.js.gz +0 -0
- package/build/client/_app/immutable/chunks/HozuTQAd.js +0 -1
- package/build/client/_app/immutable/chunks/HozuTQAd.js.br +0 -1
- package/build/client/_app/immutable/chunks/HozuTQAd.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.DkBodfd-.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DkBodfd-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/1.rWI13pjK.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.rWI13pjK.js.gz +0 -0
- package/build/client/_app/immutable/nodes/2.BC_cXN9D.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.BC_cXN9D.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.BcDEIVaI.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.BcDEIVaI.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BVYhZ3RX.js +0 -1
- package/build/client/_app/immutable/nodes/21.BVYhZ3RX.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BVYhZ3RX.js.gz +0 -0
- package/build/client/_app/immutable/nodes/25.BhiThFEd.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.BhiThFEd.js.gz +0 -0
- package/build/client/_app/immutable/nodes/3.BVyOvlCQ.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.BVyOvlCQ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/30.B6pd-F-z.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.B6pd-F-z.js.gz +0 -0
- package/build/client/_app/immutable/nodes/5.Cf8uTJgI.js.br +0 -2
- package/build/client/_app/immutable/nodes/5.Cf8uTJgI.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.DMoGaSJA.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.DMoGaSJA.js.gz +0 -0
- package/build/client/_app/immutable/nodes/7.DTPvNOH_.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.DTPvNOH_.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.BNUTD3F8.css +0 -2
- /package/build/client/_app/immutable/nodes/{0.BQwy8qtV.js → 0.CXQcjMDK.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.BQwy8qtV.js.br → 0.CXQcjMDK.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.BQwy8qtV.js.gz → 0.CXQcjMDK.js.gz} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rhino3dm.js","names":[],"sources":["../../../../../node_modules/.pnpm/rhino3dm@8.35.0/node_modules/rhino3dm/rhino3dm.wasm?url"],"sourcesContent":["export default import.meta.ROLLDOWN_FILE_URL_VRAku6fjghkApIISiBWPzg"],"ignoreList":[0],"mappings":";AAAA,IAAA,mBAAe"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// ../schemas/src/generated/schema.ts
|
|
2
2
|
/** Current UISchema format version (from ui-schema.json's schemaVersion default). */
|
|
3
|
-
var UI_SCHEMA_VERSION = "2.
|
|
3
|
+
var UI_SCHEMA_VERSION = "2.22.0";
|
|
4
4
|
function isNumberWidget(item) {
|
|
5
5
|
return item.type === "input" && item.widgetType === "number";
|
|
6
6
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","names":[],"sources":["../../../../schemas/src/generated/schema.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * This file was automatically generated from packages/schemas/ui-schema.json.\n * DO NOT MODIFY IT BY HAND. Instead, modify the source JSON Schema file\n * and run `pnpm generate` at the repo root to regenerate it.\n */\n\nexport type ParamType =\n\t| 'number'\n\t| 'integer'\n\t| 'boolean'\n\t| 'text'\n\t| 'valueList'\n\t| 'dynamicValueList'\n\t| 'file'\n\t| 'color'\n\t| 'generic'\n\t| 'geometry'\n\t| 'point'\n\t| 'line'\n\t| 'plane';\nexport type InputNumberLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'number';\n\tconfig?: NumberWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputTextLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'text';\n\tconfig?: TextWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputDropdownLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'dropdown';\n\tconfig: DropdownWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputDynamicValueListLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'dynamicValueList';\n\tconfig?: DynamicValueListWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputCheckboxLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'checkbox';\n\tconfig?: CheckboxWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputFileLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'file';\n\tconfig?: FileInputWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputColorLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'color';\n\tconfig?: ColorWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputTextLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'text';\n\t[k: string]: unknown | undefined;\n};\nexport type OutputNumberLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'number';\n\t[k: string]: unknown | undefined;\n};\nexport type OutputFileLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'file';\n\tconfig?: FileWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputChartLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'chart';\n\tconfig?: ChartWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputImageLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'image';\n\tconfig?: ImageWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputDynamicValueListLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'dynamicValueList';\n\tconfig: DynamicValueListOutputConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type LayoutItem =\n\t| InputNumberLayoutItem\n\t| InputTextLayoutItem\n\t| InputDropdownLayoutItem\n\t| InputDynamicValueListLayoutItem\n\t| InputCheckboxLayoutItem\n\t| InputFileLayoutItem\n\t| InputColorLayoutItem\n\t| OutputTextLayoutItem\n\t| OutputNumberLayoutItem\n\t| OutputFileLayoutItem\n\t| OutputChartLayoutItem\n\t| OutputImageLayoutItem\n\t| OutputDynamicValueListLayoutItem\n\t| LineBreakLayoutItem;\nexport type LayoutConfig = TabbedLayoutConfig | FlatLayoutConfig;\nexport type InputStructure = 'item' | 'list' | 'tree';\n\n/**\n * Schema definitions for Selva UI configuration\n */\nexport interface SelvaUISchema {\n\t[k: string]: unknown | undefined;\n}\nexport interface VisibilityRule {\n\t/**\n\t * Parameter ID to watch for changes\n\t */\n\tparamId: string;\n\t/**\n\t * Comparison operator. 'contains', 'containsAny', 'isEmpty', 'isNotEmpty' apply to array-valued params (e.g., checklist value lists).\n\t */\n\toperator:\n\t\t| 'equals'\n\t\t| 'notEquals'\n\t\t| 'greaterThan'\n\t\t| 'lessThan'\n\t\t| 'greaterThanOrEqual'\n\t\t| 'lessThanOrEqual'\n\t\t| 'in'\n\t\t| 'notIn'\n\t\t| 'between'\n\t\t| 'matches'\n\t\t| 'contains'\n\t\t| 'containsAny'\n\t\t| 'isEmpty'\n\t\t| 'isNotEmpty';\n\t/**\n\t * Value to compare against (used for equals, notEquals, greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual)\n\t */\n\tvalue?: {\n\t\t[k: string]: unknown | undefined;\n\t};\n\t/**\n\t * Array of values (used for 'in', 'notIn' operators, or [min, max] for 'between')\n\t */\n\tvalues?: unknown[];\n}\nexport interface VisibilityCondition {\n\t/**\n\t * Evaluation mode: 'all' = AND (all rules must pass), 'any' = OR (at least one rule must pass)\n\t */\n\tmode?: 'all' | 'any';\n\t/**\n\t * List of rules to evaluate\n\t *\n\t * @minItems 1\n\t */\n\trules: [VisibilityRule, ...VisibilityRule[]];\n\t/**\n\t * Action to apply when condition is met: 'show' makes visible and enabled, 'hide' removes from view, 'disable' makes visible but greyed out and non-interactive\n\t */\n\taction?: 'show' | 'hide' | 'disable';\n\t/**\n\t * Default value to set for the parameter when condition is met. The value should be compatible with the parameter type (number, string, boolean, etc.)\n\t */\n\tdefaultValue?: {\n\t\t[k: string]: unknown | undefined;\n\t};\n}\nexport interface GroupVisibilityCondition {\n\t/**\n\t * Evaluation mode: 'all' = AND (all rules must pass), 'any' = OR (at least one rule must pass)\n\t */\n\tmode?: 'all' | 'any';\n\t/**\n\t * List of rules to evaluate\n\t *\n\t * @minItems 1\n\t */\n\trules: [VisibilityRule, ...VisibilityRule[]];\n\t/**\n\t * Action to apply when condition is met: 'show' makes group visible, 'hide' removes group from view\n\t */\n\taction?: 'show' | 'hide';\n}\nexport interface NumberWidgetConfig {\n\tminimum?: number;\n\tmaximum?: number;\n\tstepSize?: number;\n\tplaceholder?: string;\n\trenderAsSlider?: boolean;\n\t/**\n\t * Never show the min/max hint. Without it, a number box shows the hint beside its label while focused; sliders never show it.\n\t */\n\thideRange?: boolean;\n}\nexport interface TextWidgetConfig {\n\tplaceholder?: string;\n\trequired?: boolean;\n\t/**\n\t * Maximum character length for text input\n\t */\n\tmaxLength?: number;\n\t/**\n\t * Regex pattern for validation (e.g., email, phone)\n\t */\n\tpattern?: string;\n\t/**\n\t * Custom error message shown when pattern validation fails\n\t */\n\tcustomErrorMessage?: string;\n}\nexport interface OptionMedia {\n\t/**\n\t * Asset holding the option's icon (an OptionAsset with d).\n\t */\n\ticon?: string;\n\t/**\n\t * Asset holding the option's thumbnail (an OptionAsset with img).\n\t */\n\timage?: string;\n\t/**\n\t * Iconify name the icon was picked as (e.g. 'lucide:house'), so the builder can reopen the picker on it. Never rendered.\n\t */\n\ticonName?: string;\n}\nexport interface OptionAsset {\n\t/**\n\t * SVG path data on a 24x24 grid, drawn as a stroke (width 2, round caps and joins, no fill). Rendered as a path's d attribute, never as markup.\n\t */\n\td?: string;\n\t/**\n\t * Thumbnail as a base64 data URI. Only WebP, JPEG and PNG are accepted.\n\t */\n\timg?: string;\n\t/**\n\t * Thumbnail width in pixels\n\t */\n\tw?: number;\n\t/**\n\t * Thumbnail height in pixels\n\t */\n\th?: number;\n}\nexport interface DropdownWidgetConfig {\n\t/**\n\t * Key-value pairs for dropdown options\n\t */\n\toptions: {\n\t\t[k: string]: string | undefined;\n\t};\n\trequired?: boolean;\n\t/**\n\t * How to render the value list. 'dropdown' = single-select dropdown (value: string). 'checklist' = multi-select checkboxes (value: string[]); requires list access on the connected parameter. 'segmented' = single-select button row, shown as a dropdown when there are too many options to fit. 'tiles' = single-select grid of thumbnails.\n\t */\n\tdisplayAs?: 'dropdown' | 'checklist' | 'segmented' | 'tiles';\n\t/**\n\t * Icon and thumbnail per option, keyed by option name. Grasshopper owns options; this map is the author's and survives a re-sync.\n\t */\n\toptionMedia?: {\n\t\t[k: string]: OptionMedia | undefined;\n\t};\n}\nexport interface DynamicValueListWidgetConfig {\n\t/**\n\t * Author-provided seed list (name -> value). Shown until computed options replace it. Empty/absent means the input is empty until the first solve produces options.\n\t */\n\tdefaultOptions?: {\n\t\t[k: string]: string | undefined;\n\t};\n\t/**\n\t * What to render when there are no options yet (no defaultOptions and no computed options): 'hide' removes the field from view, 'show-empty' shows a disabled 'no options yet' control.\n\t */\n\temptyBehavior?: 'hide' | 'show-empty';\n\t/**\n\t * How to render the value list. 'dropdown' = single-select (value: string). 'checklist' = multi-select (value: string[]). 'segmented' = single-select button row, shown as a dropdown when there are too many options to fit. 'tiles' = single-select grid of thumbnails.\n\t */\n\tdisplayAs?: 'dropdown' | 'checklist' | 'segmented' | 'tiles';\n\t/**\n\t * Icon and thumbnail per option, keyed by option name. Names without an entry show text only.\n\t */\n\toptionMedia?: {\n\t\t[k: string]: OptionMedia | undefined;\n\t};\n}\nexport interface DynamicValueListOutputConfig {\n\t/**\n\t * The backend parameter's GUID (paramId) of the DynamicValueList input that this output's computed options populate.\n\t */\n\ttargetInputId: string;\n}\nexport interface CheckboxWidgetConfig {\n\t/**\n\t * 'checkbox' = a toggle whose value is sent with every solve. 'button' = a trigger: a press solves once with true, then the input goes back to false. A button holds no value in the form, so presets and value updates skip it.\n\t */\n\tdisplayAs?: 'checkbox' | 'button';\n}\nexport interface FileWidgetConfig {\n\tbuttonLabel?: string;\n\t/**\n\t * File format hint (e.g., '3dm') for setting download extension\n\t */\n\tfileFormat?: string;\n}\nexport interface FileInputWidgetConfig {\n\t/**\n\t * List of accepted file extensions (e.g., ['.3dm', '.step'])\n\t */\n\tacceptedFormats?: string[];\n\t/**\n\t * Which mode is active by default when both are allowed\n\t */\n\tdefaultInputMode?: 'upload' | 'url';\n\t/**\n\t * Which input modes the end user can choose from. If omitted, both are allowed.\n\t */\n\tallowedInputModes?: ('upload' | 'url')[];\n}\nexport interface ColorWidgetConfig {}\nexport interface LayoutItemBase {\n\t/**\n\t * Unique identifier for this layout item in the UI tree (not the parameter ID)\n\t */\n\tid: string;\n\t/**\n\t * References the backend parameter's GUID (Data Source)\n\t */\n\tparamId: string;\n\tdisplayName?: string;\n\tdescription?: string;\n\torder?: number;\n\tspan?: number;\n\t/**\n\t * Base visibility (static). If false, item is always hidden regardless of conditions.\n\t */\n\tvisible?: boolean;\n\tvisibilityCondition?: VisibilityCondition;\n\tsource?: InputSource;\n\t[k: string]: unknown | undefined;\n}\nexport interface InputSource {\n\t/**\n\t * Which data provider supplies the value. 'user' = the person types it into the form. 'client' = a browser app (e.g. a measurement/producer tool) fills it in before the form runs, not the person. 'server' = reserved for a server-side lookup that no host performs yet: the input solves with its default, a solve that posts a value for it is refused, and it is never shown in the form.\n\t */\n\tkind: 'user' | 'client' | 'server';\n\t/**\n\t * The address the host resolves to fill this input — opaque to Selva, interpreted by the host per 'kind'. For 'client' it names WHICH producer app supplies the value (e.g. 'line-app', 'file-upload') so the host pre-routes to it; for 'server' it names WHAT a resolver would fetch (e.g. 'capture.geometry'). Keys need not be unique: the same producer/fetch may fill several inputs. Ignored for kind='user'.\n\t */\n\tkey?: string;\n\t/**\n\t * How a client-sourced input appears in the form (only meaningful when kind='client'). Omitted = 'hidden': the value is prefilled silently and the input does not appear. 'slot' = Selva reserves the input's grid cell and lets the host render its own element there; Selva draws nothing itself and never interprets that element.\n\t */\n\tclient?: {\n\t\t/**\n\t\t * 'hidden' = no UI; the producer app prefills the value and the input does not appear. 'slot' = the host renders a custom element (e.g. an 'Edit JSON' button) in this input's place, referencing the producer named by 'key'.\n\t\t */\n\t\tpresentation?: 'hidden' | 'slot';\n\t};\n}\nexport interface ChartWidgetConfig {}\nexport interface ImageWidgetConfig {\n\t/**\n\t * Show a download button on the image viewer\n\t */\n\tallowDownload?: boolean;\n\t/**\n\t * Show a fullscreen toggle button on the image viewer\n\t */\n\tallowFullscreen?: boolean;\n\t/**\n\t * Optional background color shown behind the image (hex string, e.g. '#ffffff')\n\t */\n\tbackgroundColor?: string;\n}\nexport interface LineBreakLayoutItem {\n\t/**\n\t * Unique identifier for this layout item in the UI tree\n\t */\n\tid: string;\n\ttype: 'linebreak';\n}\nexport interface GroupConfig {\n\tid: string;\n\tlabel: string;\n\tdescription?: string;\n\torder?: number;\n\tcollapsed?: boolean;\n\tcolumns?: number;\n\titems: LayoutItem[];\n\tvisibilityCondition?: GroupVisibilityCondition;\n}\nexport interface TabConfig {\n\tid: string;\n\tlabel: string;\n\ticon?: string;\n\torder?: number;\n\tgroups: GroupConfig[];\n\t/**\n\t * Horizontal region where this tab should be positioned in multi-column layouts\n\t */\n\tposition?: 'left' | 'center' | 'right';\n\t/**\n\t * Base visibility (static). If false, the tab is always hidden. A tab whose groups are all hidden is hidden too.\n\t */\n\tvisible?: boolean;\n}\nexport interface TabbedLayoutConfig {\n\ttype: 'tabbed';\n\tgap?: number;\n\ttabs: TabConfig[];\n}\nexport interface FlatLayoutConfig {\n\ttype: 'flat';\n\tgap?: number;\n\tgroups: GroupConfig[];\n}\nexport interface SchemaInput {\n\t/**\n\t * Backend-specific parameter identifier (e.g. a Grasshopper InstanceGuid)\n\t */\n\tid: string;\n\tnickname: string;\n\tparamType: ParamType;\n\tdescription?: string;\n\tdefault?: unknown;\n\t/**\n\t * Data access mode: 'item' = single value, 'list' = flat list, 'tree' = branching data tree. Defaults to 'item'.\n\t */\n\tinputStructure?: 'item' | 'list' | 'tree';\n}\nexport interface SchemaOutput {\n\t/**\n\t * Backend-specific parameter identifier (e.g. a Grasshopper InstanceGuid)\n\t */\n\tid: string;\n\tnickname: string;\n\tdescription?: string;\n\t/**\n\t * Output display type\n\t */\n\ttype: 'text' | 'number' | 'file' | 'chart' | 'dynamicValueList';\n\t/**\n\t * For 'dynamicValueList' outputs: the instance GUID (paramId) of the DynamicValueList input that this output's computed options populate.\n\t */\n\ttargetInputId?: string;\n}\nexport interface ViewerOptions {\n\t/**\n\t * If true, the plugin streams display meshes to its local web preview, which then shows the 3D viewer. Selva ignores it.\n\t */\n\tenableLocal?: boolean;\n\t/**\n\t * If true, Selva draws the display meshes in the Rhino.Compute response and shows the 3D viewer. The plugin's local preview ignores it.\n\t */\n\tenableRemote?: boolean;\n\t/**\n\t * Background color for the 3D viewer as hex string (e.g., '#ffffff')\n\t */\n\tbackgroundColor?: string;\n\t/**\n\t * The viewer look a definition opens in. A viewer can still switch look from its display menu.\n\t */\n\tlook?:\n\t\t'technical' | 'studio' | 'showcase' | 'arctic' | 'xray' | 'lineart' | 'wireframe' | 'night';\n}\nexport interface LocalOptions {\n\t/**\n\t * If true, geometry picked in the Rhino viewport follows the Rhino objects it came from: editing or moving one re-solves with its new shape, deleting one drops it. If false, a pick is a snapshot.\n\t */\n\ttrackPickedObjects?: boolean;\n}\nexport interface UISchema {\n\tid: string;\n\tname: string;\n\tdescription?: string;\n\t/**\n\t * Grasshopper document file name (e.g., 'myfile.gh')\n\t */\n\tprojectFileName?: string;\n\t/**\n\t * Grasshopper document unique identifier (GUID)\n\t */\n\tdocumentId?: string;\n\t/**\n\t * Version of Selva plugin that created/last modified this schema\n\t */\n\tpluginVersion?: string;\n\t/**\n\t * Tags for the Selva library (e.g., ['architecture', 'facade']). Selva copies them into the definition when it is uploaded; after that the definition's own tags win. At most MAX_TAGS, none containing a comma.\n\t */\n\ttags?: string[];\n\t/**\n\t * Category for the Selva library (e.g., 'architecture', 'structural'). Selva copies it into the definition when it is uploaded; after that the definition's own category wins. At most MAX_CATEGORY_LENGTH characters.\n\t */\n\tcategory?: string;\n\t/**\n\t * User or organization who created the schema\n\t */\n\tauthor?: string;\n\t/**\n\t * Organization/company name\n\t */\n\torganization?: string;\n\t/**\n\t * Semantic version of the schema format (MAJOR.MINOR.PATCH)\n\t */\n\tschemaVersion: string;\n\t/**\n\t * Minimum plugin version required to load this schema\n\t */\n\tminPluginVersion?: string;\n\tcreated?: string;\n\t/**\n\t * Last modification timestamp\n\t */\n\tlastModified?: string;\n\tviewerOptions?: ViewerOptions1;\n\tlocalOptions?: LocalOptions;\n\t/**\n\t * If true, changes trigger immediate solving. If false, user must press Calculate button.\n\t */\n\tinstanceSolve?: boolean;\n\t/**\n\t * If true, edits solve as previews: file components that only feed a Download output are skipped, and a click on Download runs one full solve. If false or absent, every solve makes every file.\n\t */\n\tpreviewSolves?: boolean;\n\tinputs: SchemaInput[];\n\t/**\n\t * All output components (print, bake, file download)\n\t */\n\toutputs: SchemaOutput[];\n\tlayout: LayoutConfig;\n\t/**\n\t * Icons and thumbnails referenced by optionMedia, keyed by a hash of their content so a shared one is stored once.\n\t */\n\tassets?: {\n\t\t[k: string]: OptionAsset | undefined;\n\t};\n}\n/**\n * Configuration for the 3D viewer\n */\nexport interface ViewerOptions1 {\n\t/**\n\t * If true, the plugin streams display meshes to its local web preview, which then shows the 3D viewer. Selva ignores it.\n\t */\n\tenableLocal?: boolean;\n\t/**\n\t * If true, Selva draws the display meshes in the Rhino.Compute response and shows the 3D viewer. The plugin's local preview ignores it.\n\t */\n\tenableRemote?: boolean;\n\t/**\n\t * Background color for the 3D viewer as hex string (e.g., '#ffffff')\n\t */\n\tbackgroundColor?: string;\n\t/**\n\t * The viewer look a definition opens in. A viewer can still switch look from its display menu.\n\t */\n\tlook?:\n\t\t'technical' | 'studio' | 'showcase' | 'arctic' | 'xray' | 'lineart' | 'wireframe' | 'night';\n}\n\n// ============================================================================\n// CONSTANTS (from schema)\n// ============================================================================\n\nexport const ACCEPTED_FILE_FORMATS = [\n\t'.3dm',\n\t'.stp',\n\t'.step',\n\t'.fbx',\n\t'.obj',\n\t'.dxf',\n\t'.stl'\n] as const;\nexport const MAX_TAGS = 5 as const;\nexport const MAX_CATEGORY_LENGTH = 40 as const;\n\n/** Current UISchema format version (from ui-schema.json's schemaVersion default). */\nexport const UI_SCHEMA_VERSION = '2.20.0';\n\n// ============================================================================\n// TYPE ALIASES AND GUARDS (derived from the LayoutItem union)\n// ============================================================================\n\nexport type InputLayoutItem =\n\t| InputNumberLayoutItem\n\t| InputTextLayoutItem\n\t| InputDropdownLayoutItem\n\t| InputDynamicValueListLayoutItem\n\t| InputCheckboxLayoutItem\n\t| InputFileLayoutItem\n\t| InputColorLayoutItem;\nexport type OutputLayoutItem =\n\t| OutputTextLayoutItem\n\t| OutputNumberLayoutItem\n\t| OutputFileLayoutItem\n\t| OutputChartLayoutItem\n\t| OutputImageLayoutItem\n\t| OutputDynamicValueListLayoutItem;\nexport type SupportedTypes = string | number | boolean | string[];\n\nexport function isInputLayoutItem(item: LayoutItem): item is InputLayoutItem {\n\treturn item.type === 'input';\n}\n\nexport function isOutputLayoutItem(item: LayoutItem): item is OutputLayoutItem {\n\treturn item.type === 'output';\n}\n\nexport function isLineBreakLayoutItem(item: LayoutItem): item is LineBreakLayoutItem {\n\treturn item.type === 'linebreak';\n}\n\nexport function isNumberWidget(item: LayoutItem): item is InputNumberLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'number';\n}\n\nexport function isTextWidget(item: LayoutItem): item is InputTextLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'text';\n}\n\nexport function isDropdownWidget(item: LayoutItem): item is InputDropdownLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'dropdown';\n}\n\nexport function isDynamicValueListWidget(\n\titem: LayoutItem\n): item is InputDynamicValueListLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'dynamicValueList';\n}\n\nexport function isCheckboxWidget(item: LayoutItem): item is InputCheckboxLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'checkbox';\n}\n\nexport function isFileWidget(item: LayoutItem): item is InputFileLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'file';\n}\n\nexport function isColorWidget(item: LayoutItem): item is InputColorLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'color';\n}\n\nexport function isTextOutputWidget(item: LayoutItem): item is OutputTextLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'text';\n}\n\nexport function isNumberOutputWidget(item: LayoutItem): item is OutputNumberLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'number';\n}\n\nexport function isFileOutputWidget(item: LayoutItem): item is OutputFileLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'file';\n}\n\nexport function isChartOutputWidget(item: LayoutItem): item is OutputChartLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'chart';\n}\n\nexport function isImageOutputWidget(item: LayoutItem): item is OutputImageLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'image';\n}\n\nexport function isDynamicValueListOutputWidget(\n\titem: LayoutItem\n): item is OutputDynamicValueListLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'dynamicValueList';\n}\n"],"mappings":";;AA2kBA,IAAa,oBAAoB;AAmCjC,SAAgB,eAAe,MAAiD;CAC/E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,aAAa,MAA+C;CAC3E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,iBAAiB,MAAmD;CACnF,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,yBACf,MAC0C;CAC1C,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,iBAAiB,MAAmD;CACnF,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,aAAa,MAA+C;CAC3E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,cAAc,MAAgD;CAC7E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD"}
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../../../../schemas/src/generated/schema.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * This file was automatically generated from packages/schemas/ui-schema.json.\n * DO NOT MODIFY IT BY HAND. Instead, modify the source JSON Schema file\n * and run `pnpm generate` at the repo root to regenerate it.\n */\n\nexport type ParamType =\n\t| 'number'\n\t| 'integer'\n\t| 'boolean'\n\t| 'text'\n\t| 'valueList'\n\t| 'dynamicValueList'\n\t| 'file'\n\t| 'color'\n\t| 'generic'\n\t| 'geometry'\n\t| 'point'\n\t| 'line'\n\t| 'plane';\nexport type GeometryKind =\n\t| 'point'\n\t| 'pointCloud'\n\t| 'curve'\n\t| 'surface'\n\t| 'polysurface'\n\t| 'extrusion'\n\t| 'mesh'\n\t| 'subd'\n\t| 'block';\nexport type InputNumberLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'number';\n\tconfig?: NumberWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputTextLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'text';\n\tconfig?: TextWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputDropdownLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'dropdown';\n\tconfig: DropdownWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputDynamicValueListLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'dynamicValueList';\n\tconfig?: DynamicValueListWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputCheckboxLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'checkbox';\n\tconfig?: CheckboxWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputFileLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'file';\n\tconfig?: FileInputWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type InputColorLayoutItem = LayoutItemBase & {\n\ttype: 'input';\n\twidgetType: 'color';\n\tconfig?: ColorWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputTextLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'text';\n\t[k: string]: unknown | undefined;\n};\nexport type OutputNumberLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'number';\n\t[k: string]: unknown | undefined;\n};\nexport type OutputFileLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'file';\n\tconfig?: FileWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputChartLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'chart';\n\tconfig?: ChartWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputImageLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'image';\n\tconfig?: ImageWidgetConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type OutputDynamicValueListLayoutItem = LayoutItemBase & {\n\ttype: 'output';\n\twidgetType: 'dynamicValueList';\n\tconfig: DynamicValueListOutputConfig;\n\t[k: string]: unknown | undefined;\n};\nexport type LayoutItem =\n\t| InputNumberLayoutItem\n\t| InputTextLayoutItem\n\t| InputDropdownLayoutItem\n\t| InputDynamicValueListLayoutItem\n\t| InputCheckboxLayoutItem\n\t| InputFileLayoutItem\n\t| InputColorLayoutItem\n\t| OutputTextLayoutItem\n\t| OutputNumberLayoutItem\n\t| OutputFileLayoutItem\n\t| OutputChartLayoutItem\n\t| OutputImageLayoutItem\n\t| OutputDynamicValueListLayoutItem\n\t| LineBreakLayoutItem;\nexport type LayoutConfig = TabbedLayoutConfig | FlatLayoutConfig;\nexport type InputStructure = 'item' | 'list' | 'tree';\n\n/**\n * Schema definitions for Selva UI configuration\n */\nexport interface SelvaUISchema {\n\t[k: string]: unknown | undefined;\n}\nexport interface VisibilityRule {\n\t/**\n\t * Parameter ID to watch for changes\n\t */\n\tparamId: string;\n\t/**\n\t * Comparison operator. 'contains', 'containsAny', 'isEmpty', 'isNotEmpty' apply to array-valued params (e.g., checklist value lists).\n\t */\n\toperator:\n\t\t| 'equals'\n\t\t| 'notEquals'\n\t\t| 'greaterThan'\n\t\t| 'lessThan'\n\t\t| 'greaterThanOrEqual'\n\t\t| 'lessThanOrEqual'\n\t\t| 'in'\n\t\t| 'notIn'\n\t\t| 'between'\n\t\t| 'matches'\n\t\t| 'contains'\n\t\t| 'containsAny'\n\t\t| 'isEmpty'\n\t\t| 'isNotEmpty';\n\t/**\n\t * Value to compare against (used for equals, notEquals, greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual)\n\t */\n\tvalue?: {\n\t\t[k: string]: unknown | undefined;\n\t};\n\t/**\n\t * Array of values (used for 'in', 'notIn' operators, or [min, max] for 'between')\n\t */\n\tvalues?: unknown[];\n}\nexport interface VisibilityCondition {\n\t/**\n\t * Evaluation mode: 'all' = AND (all rules must pass), 'any' = OR (at least one rule must pass)\n\t */\n\tmode?: 'all' | 'any';\n\t/**\n\t * List of rules to evaluate\n\t *\n\t * @minItems 1\n\t */\n\trules: [VisibilityRule, ...VisibilityRule[]];\n\t/**\n\t * Action to apply when condition is met: 'show' makes visible and enabled, 'hide' removes from view, 'disable' makes visible but greyed out and non-interactive\n\t */\n\taction?: 'show' | 'hide' | 'disable';\n\t/**\n\t * Default value to set for the parameter when condition is met. The value should be compatible with the parameter type (number, string, boolean, etc.)\n\t */\n\tdefaultValue?: {\n\t\t[k: string]: unknown | undefined;\n\t};\n}\nexport interface GroupVisibilityCondition {\n\t/**\n\t * Evaluation mode: 'all' = AND (all rules must pass), 'any' = OR (at least one rule must pass)\n\t */\n\tmode?: 'all' | 'any';\n\t/**\n\t * List of rules to evaluate\n\t *\n\t * @minItems 1\n\t */\n\trules: [VisibilityRule, ...VisibilityRule[]];\n\t/**\n\t * Action to apply when condition is met: 'show' makes group visible, 'hide' removes group from view\n\t */\n\taction?: 'show' | 'hide';\n}\nexport interface NumberWidgetConfig {\n\tminimum?: number;\n\tmaximum?: number;\n\tstepSize?: number;\n\tplaceholder?: string;\n\trenderAsSlider?: boolean;\n\t/**\n\t * Unit shown after the value, e.g. \"mm\". Display only: the solve gets the bare number.\n\t */\n\tunit?: string;\n\t/**\n\t * Never show the min/max hint. Without it, a number box shows the hint beside its label while focused; sliders never show it.\n\t */\n\thideRange?: boolean;\n}\nexport interface TextWidgetConfig {\n\tplaceholder?: string;\n\trequired?: boolean;\n\t/**\n\t * Maximum character length for text input\n\t */\n\tmaxLength?: number;\n\t/**\n\t * Regex pattern for validation (e.g., email, phone)\n\t */\n\tpattern?: string;\n\t/**\n\t * Custom error message shown when pattern validation fails\n\t */\n\tcustomErrorMessage?: string;\n}\nexport interface OptionMedia {\n\t/**\n\t * Asset holding the option's icon (an OptionAsset with d).\n\t */\n\ticon?: string;\n\t/**\n\t * Asset holding the option's thumbnail (an OptionAsset with img).\n\t */\n\timage?: string;\n\t/**\n\t * Iconify name the icon was picked as (e.g. 'lucide:house'), so the builder can reopen the picker on it. Never rendered.\n\t */\n\ticonName?: string;\n}\nexport interface OptionAsset {\n\t/**\n\t * SVG path data on a 24x24 grid, drawn as a stroke (width 2, round caps and joins, no fill). Rendered as a path's d attribute, never as markup.\n\t */\n\td?: string;\n\t/**\n\t * Thumbnail as a base64 data URI. Only WebP, JPEG and PNG are accepted.\n\t */\n\timg?: string;\n\t/**\n\t * Thumbnail width in pixels\n\t */\n\tw?: number;\n\t/**\n\t * Thumbnail height in pixels\n\t */\n\th?: number;\n}\nexport interface DropdownWidgetConfig {\n\t/**\n\t * Key-value pairs for dropdown options\n\t */\n\toptions: {\n\t\t[k: string]: string | undefined;\n\t};\n\trequired?: boolean;\n\t/**\n\t * How to render the value list. 'dropdown' = single-select dropdown (value: string). 'checklist' = multi-select checkboxes (value: string[]); requires list access on the connected parameter. 'segmented' = single-select button row, shown as a dropdown when there are too many options to fit. 'tiles' = single-select grid of thumbnails.\n\t */\n\tdisplayAs?: 'dropdown' | 'checklist' | 'segmented' | 'tiles';\n\t/**\n\t * Icon and thumbnail per option, keyed by option name. Grasshopper owns options; this map is the author's and survives a re-sync.\n\t */\n\toptionMedia?: {\n\t\t[k: string]: OptionMedia | undefined;\n\t};\n}\nexport interface DynamicValueListWidgetConfig {\n\t/**\n\t * Author-provided seed list (name -> value). Shown until computed options replace it. Empty/absent means the input is empty until the first solve produces options.\n\t */\n\tdefaultOptions?: {\n\t\t[k: string]: string | undefined;\n\t};\n\t/**\n\t * What to render when there are no options yet (no defaultOptions and no computed options): 'hide' removes the field from view, 'show-empty' shows a disabled 'no options yet' control.\n\t */\n\temptyBehavior?: 'hide' | 'show-empty';\n\t/**\n\t * How to render the value list. 'dropdown' = single-select (value: string). 'checklist' = multi-select (value: string[]). 'segmented' = single-select button row, shown as a dropdown when there are too many options to fit. 'tiles' = single-select grid of thumbnails.\n\t */\n\tdisplayAs?: 'dropdown' | 'checklist' | 'segmented' | 'tiles';\n\t/**\n\t * Icon and thumbnail per option, keyed by option name. Names without an entry show text only.\n\t */\n\toptionMedia?: {\n\t\t[k: string]: OptionMedia | undefined;\n\t};\n}\nexport interface DynamicValueListOutputConfig {\n\t/**\n\t * The backend parameter's GUID (paramId) of the DynamicValueList input that this output's computed options populate.\n\t */\n\ttargetInputId: string;\n}\nexport interface CheckboxWidgetConfig {\n\t/**\n\t * 'checkbox' = a toggle whose value is sent with every solve. 'button' = a trigger: a press solves once with true, then the input goes back to false. A button holds no value in the form, so presets and value updates skip it.\n\t */\n\tdisplayAs?: 'checkbox' | 'button';\n}\nexport interface FileWidgetConfig {\n\tbuttonLabel?: string;\n\t/**\n\t * File format hint (e.g., '3dm') for setting download extension\n\t */\n\tfileFormat?: string;\n}\nexport interface FileInputWidgetConfig {\n\t/**\n\t * List of accepted file extensions (e.g., ['.3dm', '.step'])\n\t */\n\tacceptedFormats?: string[];\n\t/**\n\t * Which mode is active by default when both are allowed\n\t */\n\tdefaultInputMode?: 'upload' | 'url';\n\t/**\n\t * Which input modes the end user can choose from. If omitted, both are allowed.\n\t */\n\tallowedInputModes?: ('upload' | 'url')[];\n}\nexport interface ColorWidgetConfig {}\nexport interface LayoutItemBase {\n\t/**\n\t * Unique identifier for this layout item in the UI tree (not the parameter ID)\n\t */\n\tid: string;\n\t/**\n\t * References the backend parameter's GUID (Data Source)\n\t */\n\tparamId: string;\n\tdisplayName?: string;\n\tdescription?: string;\n\torder?: number;\n\tspan?: number;\n\t/**\n\t * Base visibility (static). If false, item is always hidden regardless of conditions.\n\t */\n\tvisible?: boolean;\n\tvisibilityCondition?: VisibilityCondition;\n\tsource?: InputSource;\n\t[k: string]: unknown | undefined;\n}\nexport interface InputSource {\n\t/**\n\t * Which data provider supplies the value. 'user' = the person types it into the form. 'client' = a browser app (e.g. a measurement/producer tool) fills it in before the form runs, not the person. 'server' = reserved for a server-side lookup that no host performs yet: the input solves with its default, a solve that posts a value for it is refused, and it is never shown in the form.\n\t */\n\tkind: 'user' | 'client' | 'server';\n\t/**\n\t * The address the host resolves to fill this input — opaque to Selva, interpreted by the host per 'kind'. For 'client' it names WHICH producer app supplies the value (e.g. 'line-app', 'file-upload') so the host pre-routes to it; for 'server' it names WHAT a resolver would fetch (e.g. 'capture.geometry'). Keys need not be unique: the same producer/fetch may fill several inputs. Ignored for kind='user'.\n\t */\n\tkey?: string;\n\t/**\n\t * How a client-sourced input appears in the form (only meaningful when kind='client'). Omitted = 'hidden': the value is prefilled silently and the input does not appear. 'slot' = Selva reserves the input's grid cell and lets the host render its own element there; Selva draws nothing itself and never interprets that element.\n\t */\n\tclient?: {\n\t\t/**\n\t\t * 'hidden' = no UI; the producer app prefills the value and the input does not appear. 'slot' = the host renders a custom element (e.g. an 'Edit JSON' button) in this input's place, referencing the producer named by 'key'.\n\t\t */\n\t\tpresentation?: 'hidden' | 'slot';\n\t};\n}\nexport interface ChartWidgetConfig {}\nexport interface ImageWidgetConfig {\n\t/**\n\t * Show a download button on the image viewer\n\t */\n\tallowDownload?: boolean;\n\t/**\n\t * Show a fullscreen toggle button on the image viewer\n\t */\n\tallowFullscreen?: boolean;\n\t/**\n\t * Optional background color shown behind the image (hex string, e.g. '#ffffff')\n\t */\n\tbackgroundColor?: string;\n}\nexport interface LineBreakLayoutItem {\n\t/**\n\t * Unique identifier for this layout item in the UI tree\n\t */\n\tid: string;\n\ttype: 'linebreak';\n}\nexport interface GroupConfig {\n\tid: string;\n\tlabel: string;\n\tdescription?: string;\n\torder?: number;\n\tcollapsed?: boolean;\n\tcolumns?: number;\n\titems: LayoutItem[];\n\tvisibilityCondition?: GroupVisibilityCondition;\n}\nexport interface TabConfig {\n\tid: string;\n\tlabel: string;\n\ticon?: string;\n\torder?: number;\n\tgroups: GroupConfig[];\n\t/**\n\t * Horizontal region where this tab should be positioned in multi-column layouts\n\t */\n\tposition?: 'left' | 'center' | 'right';\n\t/**\n\t * Base visibility (static). If false, the tab is always hidden. A tab whose groups are all hidden is hidden too.\n\t */\n\tvisible?: boolean;\n}\nexport interface TabbedLayoutConfig {\n\ttype: 'tabbed';\n\tgap?: number;\n\ttabs: TabConfig[];\n}\nexport interface FlatLayoutConfig {\n\ttype: 'flat';\n\tgap?: number;\n\tgroups: GroupConfig[];\n}\nexport interface SchemaInput {\n\t/**\n\t * Backend-specific parameter identifier (e.g. a Grasshopper InstanceGuid)\n\t */\n\tid: string;\n\tnickname: string;\n\tparamType: ParamType;\n\tdescription?: string;\n\tdefault?: unknown;\n\t/**\n\t * Data access mode: 'item' = single value, 'list' = flat list, 'tree' = branching data tree. Defaults to 'item'.\n\t */\n\tinputStructure?: 'item' | 'list' | 'tree';\n\t/**\n\t * For a 'geometry' input: what the Get Geometry's type filter allows, re-read from the param whenever the plugin validates the schema against the document. Empty or absent means the filter allows everything, or is unknown: a schema saved before 2.22.0 never has it, and other inputs carry none. A host without the document (Selva) reads it to decide whether the input takes curves.\n\t */\n\tgeometryTypes?: GeometryKind[];\n\t/**\n\t * For a geometry, point, line or plane input: the most objects the param takes, re-read from it like geometryTypes; 2147483647 is no limit. Absent on other inputs and on a schema saved before 2.22.0.\n\t */\n\tatMost?: number;\n}\nexport interface SchemaOutput {\n\t/**\n\t * Backend-specific parameter identifier (e.g. a Grasshopper InstanceGuid)\n\t */\n\tid: string;\n\tnickname: string;\n\tdescription?: string;\n\t/**\n\t * Output display type\n\t */\n\ttype: 'text' | 'number' | 'file' | 'chart' | 'dynamicValueList';\n\t/**\n\t * For 'dynamicValueList' outputs: the instance GUID (paramId) of the DynamicValueList input that this output's computed options populate.\n\t */\n\ttargetInputId?: string;\n}\nexport interface ViewerOptions {\n\t/**\n\t * If true, the plugin streams display meshes to its local web preview, which then shows the 3D viewer. Selva ignores it.\n\t */\n\tenableLocal?: boolean;\n\t/**\n\t * If true, Selva draws the display meshes in the Rhino.Compute response and shows the 3D viewer. The plugin's local preview ignores it.\n\t */\n\tenableRemote?: boolean;\n\t/**\n\t * Background color for the 3D viewer as hex string (e.g., '#ffffff')\n\t */\n\tbackgroundColor?: string;\n\t/**\n\t * The viewer look a definition opens in. A viewer can still switch look from its display menu.\n\t */\n\tlook?:\n\t\t'technical' | 'studio' | 'showcase' | 'arctic' | 'xray' | 'lineart' | 'wireframe' | 'night';\n}\nexport interface LocalOptions {\n\t/**\n\t * If true, geometry picked in the Rhino viewport follows the Rhino objects it came from: editing or moving one re-solves with its new shape, deleting one drops it. If false, a pick is a snapshot.\n\t */\n\ttrackPickedObjects?: boolean;\n}\nexport interface UISchema {\n\tid: string;\n\tname: string;\n\tdescription?: string;\n\t/**\n\t * Grasshopper document file name (e.g., 'myfile.gh')\n\t */\n\tprojectFileName?: string;\n\t/**\n\t * Grasshopper document unique identifier (GUID)\n\t */\n\tdocumentId?: string;\n\t/**\n\t * Version of Selva plugin that created/last modified this schema\n\t */\n\tpluginVersion?: string;\n\t/**\n\t * Tags for the Selva library (e.g., ['architecture', 'facade']). Selva copies them into the definition when it is uploaded; after that the definition's own tags win. At most MAX_TAGS, none containing a comma.\n\t */\n\ttags?: string[];\n\t/**\n\t * Category for the Selva library (e.g., 'architecture', 'structural'). Selva copies it into the definition when it is uploaded; after that the definition's own category wins. At most MAX_CATEGORY_LENGTH characters.\n\t */\n\tcategory?: string;\n\t/**\n\t * User or organization who created the schema\n\t */\n\tauthor?: string;\n\t/**\n\t * Organization/company name\n\t */\n\torganization?: string;\n\t/**\n\t * Semantic version of the schema format (MAJOR.MINOR.PATCH)\n\t */\n\tschemaVersion: string;\n\t/**\n\t * Minimum plugin version required to load this schema\n\t */\n\tminPluginVersion?: string;\n\tcreated?: string;\n\t/**\n\t * Last modification timestamp\n\t */\n\tlastModified?: string;\n\tviewerOptions?: ViewerOptions1;\n\tlocalOptions?: LocalOptions;\n\t/**\n\t * If true, changes trigger immediate solving. If false, user must press Calculate button.\n\t */\n\tinstanceSolve?: boolean;\n\t/**\n\t * If true, edits solve as previews: file components that only feed a Download output are skipped, and a click on Download runs one full solve. If false or absent, every solve makes every file.\n\t */\n\tpreviewSolves?: boolean;\n\tinputs: SchemaInput[];\n\t/**\n\t * All output components (print, bake, file download)\n\t */\n\toutputs: SchemaOutput[];\n\tlayout: LayoutConfig;\n\t/**\n\t * Icons and thumbnails referenced by optionMedia, keyed by a hash of their content so a shared one is stored once.\n\t */\n\tassets?: {\n\t\t[k: string]: OptionAsset | undefined;\n\t};\n}\n/**\n * Configuration for the 3D viewer\n */\nexport interface ViewerOptions1 {\n\t/**\n\t * If true, the plugin streams display meshes to its local web preview, which then shows the 3D viewer. Selva ignores it.\n\t */\n\tenableLocal?: boolean;\n\t/**\n\t * If true, Selva draws the display meshes in the Rhino.Compute response and shows the 3D viewer. The plugin's local preview ignores it.\n\t */\n\tenableRemote?: boolean;\n\t/**\n\t * Background color for the 3D viewer as hex string (e.g., '#ffffff')\n\t */\n\tbackgroundColor?: string;\n\t/**\n\t * The viewer look a definition opens in. A viewer can still switch look from its display menu.\n\t */\n\tlook?:\n\t\t'technical' | 'studio' | 'showcase' | 'arctic' | 'xray' | 'lineart' | 'wireframe' | 'night';\n}\n\n// ============================================================================\n// CONSTANTS (from schema)\n// ============================================================================\n\nexport const ACCEPTED_FILE_FORMATS = [\n\t'.3dm',\n\t'.stp',\n\t'.step',\n\t'.fbx',\n\t'.obj',\n\t'.dxf',\n\t'.stl'\n] as const;\nexport const MAX_TAGS = 5 as const;\nexport const MAX_CATEGORY_LENGTH = 40 as const;\n\n/** Current UISchema format version (from ui-schema.json's schemaVersion default). */\nexport const UI_SCHEMA_VERSION = '2.22.0';\n\n// ============================================================================\n// TYPE ALIASES AND GUARDS (derived from the LayoutItem union)\n// ============================================================================\n\nexport type InputLayoutItem =\n\t| InputNumberLayoutItem\n\t| InputTextLayoutItem\n\t| InputDropdownLayoutItem\n\t| InputDynamicValueListLayoutItem\n\t| InputCheckboxLayoutItem\n\t| InputFileLayoutItem\n\t| InputColorLayoutItem;\nexport type OutputLayoutItem =\n\t| OutputTextLayoutItem\n\t| OutputNumberLayoutItem\n\t| OutputFileLayoutItem\n\t| OutputChartLayoutItem\n\t| OutputImageLayoutItem\n\t| OutputDynamicValueListLayoutItem;\nexport type SupportedTypes = string | number | boolean | string[];\n\nexport function isInputLayoutItem(item: LayoutItem): item is InputLayoutItem {\n\treturn item.type === 'input';\n}\n\nexport function isOutputLayoutItem(item: LayoutItem): item is OutputLayoutItem {\n\treturn item.type === 'output';\n}\n\nexport function isLineBreakLayoutItem(item: LayoutItem): item is LineBreakLayoutItem {\n\treturn item.type === 'linebreak';\n}\n\nexport function isNumberWidget(item: LayoutItem): item is InputNumberLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'number';\n}\n\nexport function isTextWidget(item: LayoutItem): item is InputTextLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'text';\n}\n\nexport function isDropdownWidget(item: LayoutItem): item is InputDropdownLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'dropdown';\n}\n\nexport function isDynamicValueListWidget(\n\titem: LayoutItem\n): item is InputDynamicValueListLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'dynamicValueList';\n}\n\nexport function isCheckboxWidget(item: LayoutItem): item is InputCheckboxLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'checkbox';\n}\n\nexport function isFileWidget(item: LayoutItem): item is InputFileLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'file';\n}\n\nexport function isColorWidget(item: LayoutItem): item is InputColorLayoutItem {\n\treturn item.type === 'input' && item.widgetType === 'color';\n}\n\nexport function isTextOutputWidget(item: LayoutItem): item is OutputTextLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'text';\n}\n\nexport function isNumberOutputWidget(item: LayoutItem): item is OutputNumberLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'number';\n}\n\nexport function isFileOutputWidget(item: LayoutItem): item is OutputFileLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'file';\n}\n\nexport function isChartOutputWidget(item: LayoutItem): item is OutputChartLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'chart';\n}\n\nexport function isImageOutputWidget(item: LayoutItem): item is OutputImageLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'image';\n}\n\nexport function isDynamicValueListOutputWidget(\n\titem: LayoutItem\n): item is OutputDynamicValueListLayoutItem {\n\treturn item.type === 'output' && item.widgetType === 'dynamicValueList';\n}\n"],"mappings":";;AAimBA,IAAa,oBAAoB;AAmCjC,SAAgB,eAAe,MAAiD;CAC/E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,aAAa,MAA+C;CAC3E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,iBAAiB,MAAmD;CACnF,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,yBACf,MAC0C;CAC1C,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,iBAAiB,MAAmD;CACnF,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,aAAa,MAA+C;CAC3E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD;AAEA,SAAgB,cAAc,MAAgD;CAC7E,OAAO,KAAK,SAAS,WAAW,KAAK,eAAe;AACrD"}
|
|
@@ -561,7 +561,7 @@ function withoutShareToken(url) {
|
|
|
561
561
|
}
|
|
562
562
|
var handle = (input) => {
|
|
563
563
|
const { event } = input;
|
|
564
|
-
const run = () => requestMemo.run(event.request.method, () => gate(input));
|
|
564
|
+
const run = () => requestMemo.run(event.request.method, async () => withRequestIdInErrorBody(await gate(input), event.url.pathname));
|
|
565
565
|
if (isStaticAsset(event.url.pathname)) return run();
|
|
566
566
|
return requestTiming.timeRequest({
|
|
567
567
|
method: event.request.method,
|
|
@@ -715,9 +715,37 @@ function applyResponseHeaders(response, pathname, requestId) {
|
|
|
715
715
|
});
|
|
716
716
|
response.headers.set(REQUEST_ID_HEADER, requestId);
|
|
717
717
|
if (pathname.startsWith("/_app/")) response.headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
718
|
+
else if (pathname.startsWith("/api/v1/") && !response.headers.has("Cache-Control")) response.headers.set("Cache-Control", "private, no-store");
|
|
718
719
|
else if (pathname.startsWith("/favicon/") || pathname === "/favicon.svg" || pathname === "/robots.txt") response.headers.set("Cache-Control", "public, max-age=604800");
|
|
719
720
|
return response;
|
|
720
721
|
}
|
|
722
|
+
/**
|
|
723
|
+
* Copies the request id into an API error's JSON body, so a client that logs only the body still
|
|
724
|
+
* has the id an operator greps for. The header alone is lost by most HTTP client error paths.
|
|
725
|
+
*/
|
|
726
|
+
async function withRequestIdInErrorBody(response, pathname) {
|
|
727
|
+
if (response.status < 400 || !pathname.startsWith("/api/")) return response;
|
|
728
|
+
if (!response.headers.get("Content-Type")?.includes("application/json")) return response;
|
|
729
|
+
const requestId = response.headers.get(REQUEST_ID_HEADER);
|
|
730
|
+
if (!requestId) return response;
|
|
731
|
+
let body;
|
|
732
|
+
try {
|
|
733
|
+
body = await response.clone().json();
|
|
734
|
+
} catch {
|
|
735
|
+
return response;
|
|
736
|
+
}
|
|
737
|
+
if (!body || typeof body !== "object" || Array.isArray(body) || "requestId" in body) return response;
|
|
738
|
+
const headers = new Headers(response.headers);
|
|
739
|
+
headers.delete("Content-Length");
|
|
740
|
+
return new Response(JSON.stringify({
|
|
741
|
+
...body,
|
|
742
|
+
requestId
|
|
743
|
+
}), {
|
|
744
|
+
status: response.status,
|
|
745
|
+
statusText: response.statusText,
|
|
746
|
+
headers
|
|
747
|
+
});
|
|
748
|
+
}
|
|
721
749
|
var handleError = ({ kind, error, event }) => {
|
|
722
750
|
if (kind === "app") return error;
|
|
723
751
|
if (kind !== "unknown") return error.status === 404 ? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.server.js","names":[],"sources":["../../../../providers/supabase/src/upstream.ts","../../../../server/src/http/security-headers.ts","../../../../server/src/http/route-classifier.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/mcp/path.ts","../../../src/lib/server/requestTiming.server.ts","../../../src/lib/server/framing.ts","../../../src/hooks.server.ts"],"sourcesContent":["/**\n * Supabase serves every API under one origin; the path prefix names the service. For a\n * request-timing classifier (`createRequestTiming` in `@selvajs/server/http`): `db`, `auth` or\n * `storage`, and for the database the table or RPC a call reached (`db jobs`, `db rpc/x`).\n */\n\nconst SERVICES: [prefix: string, name: string][] = [\n\t['/rest/v1/', 'db'],\n\t['/auth/v1/', 'auth'],\n\t['/storage/v1/', 'storage']\n];\n\nexport function supabaseUpstream(url: URL): { key: string; target: string } | undefined {\n\tconst service = SERVICES.find(([prefix]) => url.pathname.startsWith(prefix));\n\tif (!service) return undefined;\n\tconst [first = '', second = ''] = url.pathname.slice(service[0].length).split('/');\n\treturn { key: service[1], target: `${service[1]} ${first === 'rpc' ? `rpc/${second}` : first}` };\n}\n","export interface SecurityHeaderOptions {\n\t/**\n\t * Set `Strict-Transport-Security`. Production only — pinning\n\t * http://localhost to HTTPS bricks local development. The caller decides\n\t * what \"production\" means (e.g. `NODE_ENV`).\n\t */\n\thsts: boolean;\n\t/**\n\t * Forbid framing this response. Off by default — Selva-engine app routes are\n\t * built to be embedded. Turn it on for operator surfaces (`/admin/*`,\n\t * `/setup`), where an authenticated session plus a framable page is a\n\t * UI-redress attack. `SameSite=Lax` blunts cross-site POST, not same-origin\n\t * redress, so the cookie flag is not a substitute.\n\t */\n\tdenyFraming?: boolean;\n}\n\n/**\n * Apply baseline browser-hardening headers to a response and return it for\n * chaining. Each is a cheap win that needs no UI verification:\n *\n * - X-Content-Type-Options: nosniff — disables MIME sniffing.\n * - Referrer-Policy: strict-origin-when-cross-origin — strips path and query\n * from cross-origin Referer headers. Matches modern browser defaults, but\n * pins the behavior in case a default drifts.\n * - Permissions-Policy: opts out of browser APIs Selva-engine apps don't use,\n * so XSS can't enable them.\n * - HSTS when `opts.hsts`.\n * - X-Frame-Options + `frame-ancestors 'none'` when `opts.denyFraming` — the\n * caller opts in per route, since embeddable app routes must stay framable.\n *\n * **Intentionally NOT set here:**\n * - A full Content-Security-Policy. Selva-engine apps are built for iframe\n * embedding, so a strict CSP needs validating against real consumer sites\n * before it can ship. `denyFraming` sets only the `frame-ancestors`\n * directive, which constrains nothing else the page loads.\n * - Cache-Control. Asset-path layout is app policy; set it in the caller.\n */\nexport function applySecurityHeaders(response: Response, opts: SecurityHeaderOptions): Response {\n\tresponse.headers.set('X-Content-Type-Options', 'nosniff');\n\tresponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n\tresponse.headers.set(\n\t\t'Permissions-Policy',\n\t\t'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'\n\t);\n\tif (opts.hsts) {\n\t\tresponse.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');\n\t}\n\tif (opts.denyFraming) {\n\t\tresponse.headers.set('X-Frame-Options', 'DENY');\n\t\tresponse.headers.set('Content-Security-Policy', \"frame-ancestors 'none'\");\n\t}\n\treturn response;\n}\n","/**\n * Deny-by-default route classification. A request is gated unless its path\n * matches one of the allowlists supplied here, so forgetting to list a new\n * route makes it gated — a loud 401/redirect, not silently public.\n *\n * The pattern is reusable; the values are app policy, supplied by the consuming\n * app. Matching is plain exact/prefix string comparison: cheap enough for the\n * hooks hot path, and no regex to get wrong.\n */\n\nexport interface RouteClassifierConfig {\n\t/** Exact-match pages needing no session (e.g. `/`, `/login`). */\n\tpublicPages?: Iterable<string>;\n\t/** Public path prefixes (e.g. `/auth/` — OAuth start and callback precede any session). */\n\tpublicPrefixes?: readonly string[];\n\t/**\n\t * Exact-match API endpoints that answer without a session (e.g. a\n\t * load-balancer health probe). Anything listed here is exposed to anonymous\n\t * callers.\n\t */\n\tpublicApis?: Iterable<string>;\n\t/**\n\t * Prefixes whose routes authorize each request themselves (e.g. a blob\n\t * proxy classifying per asset path, or a callback authenticated by a\n\t * per-request bearer). These classify as public so the hook attaches a\n\t * session best-effort and does not deny up front; the route makes the real\n\t * decision. Keep the list short — every other API route stays deny-by-default.\n\t */\n\tselfGatingPrefixes?: readonly string[];\n\t/** Single-prefix form of `selfGatingPrefixes`. */\n\tselfGatingPrefix?: string;\n\t/** Static-asset prefixes the adapter serves directly (e.g. `/_app/`). */\n\tstaticPrefixes?: readonly string[];\n\t/** Exact static-asset paths (e.g. `/favicon.svg`, `/robots.txt`). */\n\tstaticPaths?: Iterable<string>;\n}\n\nexport interface RouteClassifier {\n\t/** Matches `staticPaths`/`staticPrefixes`. These bypass auth gating entirely. */\n\tisStaticAsset(pathname: string): boolean;\n\t/** Matches `selfGatingPrefix`. The hook must not deny these — the route gates itself. */\n\tisSelfGatingApiRoute(pathname: string): boolean;\n\t/** Needs no session: a public page, API, prefix, or a self-gating route. */\n\tisPublicRoute(pathname: string): boolean;\n}\n\nexport function createRouteClassifier(config: RouteClassifierConfig): RouteClassifier {\n\tconst publicPages = new Set(config.publicPages ?? []);\n\tconst publicPrefixes = config.publicPrefixes ?? [];\n\tconst publicApis = new Set(config.publicApis ?? []);\n\tconst selfGatingPrefixes = [\n\t\t...(config.selfGatingPrefixes ?? []),\n\t\t...(config.selfGatingPrefix !== undefined ? [config.selfGatingPrefix] : [])\n\t];\n\tconst staticPrefixes = config.staticPrefixes ?? [];\n\tconst staticPaths = new Set(config.staticPaths ?? []);\n\n\tfunction isStaticAsset(pathname: string): boolean {\n\t\tif (staticPaths.has(pathname)) return true;\n\t\treturn staticPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isSelfGatingApiRoute(pathname: string): boolean {\n\t\treturn selfGatingPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isPublicRoute(pathname: string): boolean {\n\t\tif (publicPages.has(pathname)) return true;\n\t\tif (publicApis.has(pathname)) return true;\n\t\tif (isSelfGatingApiRoute(pathname)) return true;\n\t\treturn publicPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\treturn { isStaticAsset, isSelfGatingApiRoute, isPublicRoute };\n}\n","/**\n * Turns a session token into whatever a host attaches to a request, with the round trips that\n * cost cut to what the token needs.\n *\n * - The user's rows are read beside `verify`, keyed by the token's unverified subject, and kept\n * only when `verify` confirms that same user. `read` must be a read: it runs before the token\n * is checked, so it must not write anything for the subject it is handed.\n * - Requests carrying one token share one resolution while it runs.\n * - With `freshForMs`, a resolved session is reused for that long. Past it the session is still\n * answered, and resolved again behind the request; a re-check that refuses the token drops it,\n * so after a sign-out or disable the requests already in flight are the last to get through.\n * A session is never answered past its token's expiry, so row security never sees an expired\n * token mid-request.\n */\n\nimport type { AuthUser } from '@selvajs/platform';\n\nexport interface SessionResolverConfig<Rows, Session> {\n\t/** The token's user, or null for a token it refuses. */\n\tverify(token: string): Promise<AuthUser | null>;\n\t/** Everything the session needs that is keyed by the user id alone. Never a write. */\n\tread(userId: string): Promise<Rows>;\n\t/** The session from the verified user and its rows. Writes for the user belong here. */\n\tbuild(user: AuthUser, rows: Rows, token: string): Promise<Session> | Session;\n\t/**\n\t * How long a resolved session is reused before a request re-checks it behind its answer.\n\t * 0 (the default) keeps nothing between requests: every request resolves.\n\t */\n\tfreshForMs?: number;\n\t/** The cap on remembered sessions; the oldest go first. Default 5,000. */\n\tmaxEntries?: number;\n\t/** The token's subject, unverified: which rows to read ahead. Default: a JWT's `sub`. */\n\tsubjectOf?: (token: string) => string | null;\n\t/** The token's expiry in ms epoch, unverified. Default: a JWT's `exp`. Null: unknown. */\n\texpiresAtOf?: (token: string) => number | null;\n\t/** A background re-check that threw rather than refused. The session is kept. */\n\tonRefreshError?: (err: unknown) => void;\n\tnow?: () => number;\n}\n\nexport interface SessionResolver<Session> {\n\t/** The token's session, or null when `verify` refuses it. */\n\tresolve(token: string): Promise<Session | null>;\n\t/** Forget one token's session: after a sign-out, or a change to what it holds. */\n\tinvalidate(token: string): void;\n\t/** Forget every session of `userId`: after a change to their permissions or memberships. */\n\tinvalidateUser(userId: string): void;\n\tclear(): void;\n}\n\ninterface Entry<Session> {\n\tsession: Session;\n\tuserId: string;\n\tresolvedAt: number;\n\t/** Never answered at or past this: the token's expiry, else the end of the fresh window. */\n\tuntil: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 5_000;\n\nexport function createSessionResolver<Rows, Session>(\n\tconfig: SessionResolverConfig<Rows, Session>\n): SessionResolver<Session> {\n\tconst freshForMs = Math.max(0, config.freshForMs ?? 0);\n\tconst maxEntries = Math.max(1, config.maxEntries ?? DEFAULT_MAX_ENTRIES);\n\tconst subjectOf = config.subjectOf ?? jwtSubject;\n\tconst expiresAtOf = config.expiresAtOf ?? jwtExpiresAt;\n\tconst now = config.now ?? Date.now;\n\tconst entries = new Map<string, Entry<Session>>();\n\tconst inFlight = new Map<string, Promise<Entry<Session> | null>>();\n\n\tasync function build(token: string): Promise<Entry<Session> | null> {\n\t\tconst subject = subjectOf(token);\n\t\tconst ahead = subject ? config.read(subject) : null;\n\t\t// A token that fails verification never awaits its read-ahead.\n\t\tahead?.catch(() => {});\n\t\tconst user = await config.verify(token);\n\t\tif (!user) return null;\n\t\tconst rows = ahead && user.id === subject ? await ahead : await config.read(user.id);\n\t\tconst session = await config.build(user, rows, token);\n\t\tconst resolvedAt = now();\n\t\tconst expiresAt = expiresAtOf(token);\n\t\treturn {\n\t\t\tsession,\n\t\t\tuserId: user.id,\n\t\t\tresolvedAt,\n\t\t\tuntil: expiresAt ?? resolvedAt + freshForMs\n\t\t};\n\t}\n\n\tfunction remember(token: string, entry: Entry<Session>): void {\n\t\tif (freshForMs === 0 || entry.until <= now()) return;\n\t\tif (entries.size >= maxEntries) {\n\t\t\tconst at = now();\n\t\t\tfor (const [key, e] of entries) if (e.until <= at) entries.delete(key);\n\t\t\t// Map keeps insertion order, so the first key is the oldest.\n\t\t\twhile (entries.size >= maxEntries) entries.delete(entries.keys().next().value!);\n\t\t}\n\t\tentries.delete(token);\n\t\tentries.set(token, entry);\n\t}\n\n\tfunction start(token: string): Promise<Entry<Session> | null> {\n\t\tconst resolution = build(token).then((entry) => {\n\t\t\t// An invalidation while it ran dropped this resolution: what it read may be stale.\n\t\t\tif (inFlight.get(token) === resolution) {\n\t\t\t\tif (entry) remember(token, entry);\n\t\t\t\telse entries.delete(token);\n\t\t\t}\n\t\t\treturn entry;\n\t\t});\n\t\tinFlight.set(token, resolution);\n\t\tconst settle = () => {\n\t\t\tif (inFlight.get(token) === resolution) inFlight.delete(token);\n\t\t};\n\t\tresolution.then(settle, settle);\n\t\treturn resolution;\n\t}\n\n\treturn {\n\t\tasync resolve(token) {\n\t\t\tif (!token) return null;\n\t\t\tconst entry = entries.get(token);\n\t\t\tif (entry) {\n\t\t\t\tconst at = now();\n\t\t\t\tif (entry.until <= at) {\n\t\t\t\t\tentries.delete(token);\n\t\t\t\t} else {\n\t\t\t\t\tif (at - entry.resolvedAt >= freshForMs && !inFlight.has(token)) {\n\t\t\t\t\t\tstart(token).catch((err) => config.onRefreshError?.(err));\n\t\t\t\t\t}\n\t\t\t\t\treturn entry.session;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst resolved = await (inFlight.get(token) ?? start(token));\n\t\t\treturn resolved?.session ?? null;\n\t\t},\n\t\tinvalidate(token) {\n\t\t\tentries.delete(token);\n\t\t\tinFlight.delete(token);\n\t\t},\n\t\tinvalidateUser(userId) {\n\t\t\tfor (const [token, entry] of entries) if (entry.userId === userId) entries.delete(token);\n\t\t\t// A resolution under way may hold the user's old rows; none of them is kept.\n\t\t\tinFlight.clear();\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t\tinFlight.clear();\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Unverified JWT claims\n// ============================================================================\n\nfunction jwtClaims(token: string): Record<string, unknown> | null {\n\tconst parts = token.split('.');\n\tif (parts.length !== 3 || !parts[1]) return null;\n\ttry {\n\t\tconst claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));\n\t\treturn claims && typeof claims === 'object' ? claims : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction jwtSubject(token: string): string | null {\n\tconst sub = jwtClaims(token)?.sub;\n\treturn typeof sub === 'string' && sub ? sub : null;\n}\n\nfunction jwtExpiresAt(token: string): number | null {\n\tconst exp = jwtClaims(token)?.exp;\n\treturn typeof exp === 'number' ? exp * 1000 : null;\n}\n","/**\n * Per-request timing: where a request's wall time went, as named spans plus every outbound\n * fetch grouped by upstream. One AsyncLocalStorage store per request, opened by `timeRequest`\n * in the host's handle hook. The result goes out twice: a `Server-Timing` header on the\n * response, and one structured record through `log` for a request that is slow, sampled, or the\n * first the process served.\n *\n * Fetch time is time to response headers, not body: round-trip latency, which a chain of\n * sequential awaits multiplies. Parallel fetches overlap, so a bucket's `ms` is a sum and can\n * exceed the request's wall time.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\n/** Which upstream a fetch reached, and optionally the table or endpoint within it. */\nexport interface Upstream {\n\tkey: string;\n\ttarget?: string;\n}\n\nexport interface TimedRequest {\n\tmethod: string;\n\t/** The route id (`/s/[token]`), so records aggregate across ids; the path when unrouted. */\n\troute: string;\n\tisDataRequest?: boolean;\n}\n\nexport interface RequestTimingOptions {\n\t/** Writes one record. Fields are typed JSON; never put payload values in them. */\n\tlog: (message: string, fields: Record<string, unknown>) => void;\n\t/** Names the upstream of a fetch; unnamed ones bucket by host. */\n\tupstream?: (url: URL) => Upstream | undefined;\n\t/** A request at or over this is logged. Default 200 ms. */\n\tslowMs?: number;\n\t/**\n\t * This share of requests is logged whatever its time, marked `sampled`: slow-only records\n\t * lean toward whatever got slower, the sampled ones compare across a change. Default 0.1.\n\t */\n\tsampleRate?: number;\n\t/** Stamped on every record, e.g. the revision; `instance` is added per process. */\n\tlabels?: Record<string, string>;\n}\n\nexport interface RequestTiming {\n\t/**\n\t * Runs one request inside a timing store, stamps `Server-Timing` on its response and logs it\n\t * when due. A throw (a framework redirect included) is logged and rethrown.\n\t */\n\ttimeRequest(req: TimedRequest, fn: () => Promise<Response>): Promise<Response>;\n\t/** Times `fn` as a named span of the current request; outside a request it just runs. */\n\tspan<T>(name: string, fn: () => Promise<T> | T): Promise<T>;\n\t/** Attaches facts to the current request's record; a no-op outside a request. */\n\tfact(facts: Record<string, unknown>): void;\n\t/** Whether the current request is the first this process served. */\n\tisCold(): boolean;\n\t/** Called once the server can take requests: the cold-start record's `bootMs`. */\n\tmarkBooted(): void;\n\t/** Wraps the global `fetch` once; clients that look it up at call time are then timed. */\n\tinstrumentFetch(): void;\n}\n\n/** `calls` holds each call's ms, for the record's per-call median and max. */\ntype Bucket = { count: number; ms: number; calls: number[] };\n\ninterface Store {\n\tspans: { name: string; ms: number }[];\n\tupstream: Map<string, Bucket>;\n\ttargets: Map<string, number>;\n\t/** Attempts a client re-sent after a failed one (`X-Retry-Count`). */\n\tretries: number;\n\tfacts: Record<string, unknown>;\n\tcold: boolean;\n}\n\nconst round = (ms: number) => Math.round(ms);\n\nfunction median(values: number[]): number {\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = sorted.length >> 1;\n\treturn sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction urlOf(input: Parameters<typeof fetch>[0]): URL | undefined {\n\ttry {\n\t\treturn new URL(input instanceof Request ? input.url : String(input));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isRetry(init: Parameters<typeof fetch>[1]): boolean {\n\tconst headers = init?.headers;\n\tif (!headers) return false;\n\tif (headers instanceof Headers) return headers.has('x-retry-count');\n\tif (Array.isArray(headers)) return headers.some(([k]) => k.toLowerCase() === 'x-retry-count');\n\treturn Object.keys(headers).some((k) => k.toLowerCase() === 'x-retry-count');\n}\n\n/** Parses a `Server-Timing` value into `{ name: ms }`, a desc-only entry into `{ name: desc }`. */\nexport function parseServerTimingHeader(\n\theader: string | null | undefined\n): Record<string, number | string> {\n\tconst out: Record<string, number | string> = {};\n\tfor (const entry of header?.split(',') ?? []) {\n\t\tconst [name, ...params] = entry.trim().split(';');\n\t\tif (!name) continue;\n\t\tfor (const p of params) {\n\t\t\tconst [k, v = ''] = p.trim().split('=');\n\t\t\tif (k === 'dur') out[name] = round(Number(v));\n\t\t\telse if (k === 'desc' && !(name in out)) out[name] = v.replace(/^\"|\"$/g, '');\n\t\t}\n\t}\n\treturn out;\n}\n\nexport function createRequestTiming(options: RequestTimingOptions): RequestTiming {\n\tconst slowMs = options.slowMs ?? 200;\n\tconst sampleRate = options.sampleRate ?? 0.1;\n\tconst labels = { instance: randomUUID().slice(0, 8), ...options.labels };\n\tconst als = new AsyncLocalStorage<Store>();\n\tlet bootMs: number | null = null;\n\tlet served = false;\n\tlet installed = false;\n\n\tconst log = (message: string, fields: Record<string, unknown>) => {\n\t\ttry {\n\t\t\toptions.log(message, { ...labels, ...fields });\n\t\t} catch {\n\t\t\t// Telemetry never fails a request.\n\t\t}\n\t};\n\n\tfunction upstreamOf(url: URL | undefined): Upstream {\n\t\tif (!url) return { key: 'other' };\n\t\treturn options.upstream?.(url) ?? { key: url.host };\n\t}\n\n\t/** An upstream that times itself (`Server-Timing`) lands on the record by path. */\n\tfunction recordUpstreamTiming(store: Store, url: URL | undefined, response: Response): void {\n\t\tconst timing = response.headers.get('server-timing');\n\t\tif (!timing || !url) return;\n\t\tconst byPath = (store.facts.upstreamTiming as Record<string, unknown> | undefined) ?? {};\n\t\tbyPath[url.pathname] = parseServerTimingHeader(timing);\n\t\tstore.facts.upstreamTiming = byPath;\n\t}\n\n\tfunction serverTiming(store: Store, totalMs: number): string {\n\t\tconst parts = store.spans.map(\n\t\t\t(s) => `app_${s.name.replace(/[^\\w-]/g, '_')};dur=${s.ms.toFixed(1)}`\n\t\t);\n\t\tfor (const [key, b] of store.upstream) {\n\t\t\tparts.push(`up;desc=\"${key} x${b.count}\";dur=${b.ms.toFixed(1)}`);\n\t\t}\n\t\tif (store.retries > 0) parts.push(`retries;desc=\"${store.retries}\"`);\n\t\tparts.push(`app_total;dur=${totalMs.toFixed(1)}`);\n\t\treturn parts.join(', ');\n\t}\n\n\tfunction logTiming(\n\t\treq: TimedRequest,\n\t\tstatus: number | 'thrown',\n\t\ttotalMs: number,\n\t\tstore: Store,\n\t\tsampled: boolean\n\t): void {\n\t\tconst upstream = Object.fromEntries(\n\t\t\t[...store.upstream].map(([k, b]) => [\n\t\t\t\tk,\n\t\t\t\t{\n\t\t\t\t\tcount: b.count,\n\t\t\t\t\tms: round(b.ms),\n\t\t\t\t\tp50: round(median(b.calls)),\n\t\t\t\t\tmax: round(Math.max(...b.calls))\n\t\t\t\t}\n\t\t\t])\n\t\t);\n\t\t// A span name that ran more than once sums.\n\t\tconst spans: Record<string, number> = {};\n\t\tfor (const s of store.spans) spans[s.name] = round((spans[s.name] ?? 0) + s.ms);\n\t\tlog(\n\t\t\t`[timing] ${req.method} ${req.route}${req.isDataRequest ? ' (data)' : ''} ${status} ${round(totalMs)}ms`,\n\t\t\t{\n\t\t\t\ttiming: {\n\t\t\t\t\troute: req.route,\n\t\t\t\t\tmethod: req.method,\n\t\t\t\t\tdata: req.isDataRequest ?? false,\n\t\t\t\t\tstatus,\n\t\t\t\t\ttotalMs: round(totalMs),\n\t\t\t\t\t...(store.cold && { cold: true }),\n\t\t\t\t\t...(sampled && { sampled: true }),\n\t\t\t\t\tspans,\n\t\t\t\t\tupstream,\n\t\t\t\t\tcalls: Object.fromEntries(store.targets),\n\t\t\t\t\t...(store.retries > 0 && { retries: store.retries }),\n\t\t\t\t\t...store.facts\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\treturn {\n\t\tasync timeRequest(req, fn) {\n\t\t\tconst cold = !served;\n\t\t\tserved = true;\n\t\t\tconst store: Store = {\n\t\t\t\tspans: [],\n\t\t\t\tupstream: new Map(),\n\t\t\t\ttargets: new Map(),\n\t\t\t\tretries: 0,\n\t\t\t\tfacts: {},\n\t\t\t\tcold\n\t\t\t};\n\t\t\tconst start = performance.now();\n\t\t\tif (cold) {\n\t\t\t\t// Process start to `markBooted`, and to this request: their gap is idle time.\n\t\t\t\tlog(`[coldstart] ${req.method} ${req.route}`, {\n\t\t\t\t\tcoldstart: { bootMs, firstRequestMs: round(start), route: req.route }\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet status: number | 'thrown' = 'thrown';\n\t\t\ttry {\n\t\t\t\tconst response = await als.run(store, fn);\n\t\t\t\tstatus = response.status;\n\t\t\t\ttry {\n\t\t\t\t\tresponse.headers.append('Server-Timing', serverTiming(store, performance.now() - start));\n\t\t\t\t} catch {\n\t\t\t\t\t// Immutable headers (a fetched Response passed through): the record still has it.\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t} finally {\n\t\t\t\tconst totalMs = performance.now() - start;\n\t\t\t\tconst sampled = Math.random() < sampleRate;\n\t\t\t\t// The cold request always: a comparison across a change must be able to drop it.\n\t\t\t\tif (cold || sampled || totalMs >= slowMs) logTiming(req, status, totalMs, store, sampled);\n\t\t\t}\n\t\t},\n\n\t\tasync span(name, fn) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (!store) return fn();\n\t\t\tconst start = performance.now();\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} finally {\n\t\t\t\tstore.spans.push({ name, ms: performance.now() - start });\n\t\t\t}\n\t\t},\n\n\t\tfact(facts) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (store) Object.assign(store.facts, facts);\n\t\t},\n\n\t\tisCold: () => als.getStore()?.cold ?? false,\n\n\t\tmarkBooted() {\n\t\t\tbootMs ??= round(performance.now());\n\t\t},\n\n\t\tinstrumentFetch() {\n\t\t\tif (installed) return;\n\t\t\tinstalled = true;\n\t\t\tconst original = globalThis.fetch;\n\t\t\tglobalThis.fetch = async (input, init) => {\n\t\t\t\tconst store = als.getStore();\n\t\t\t\tif (!store) return original(input, init);\n\t\t\t\tconst start = performance.now();\n\t\t\t\tconst url = urlOf(input);\n\t\t\t\tconst { key, target } = upstreamOf(url);\n\t\t\t\tif (target) store.targets.set(target, (store.targets.get(target) ?? 0) + 1);\n\t\t\t\tif (isRetry(init)) store.retries += 1;\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await original(input, init);\n\t\t\t\t\trecordUpstreamTiming(store, url, response);\n\t\t\t\t\treturn response;\n\t\t\t\t} finally {\n\t\t\t\t\tconst bucket = store.upstream.get(key) ?? { count: 0, ms: 0, calls: [] };\n\t\t\t\t\tconst ms = performance.now() - start;\n\t\t\t\t\tbucket.count += 1;\n\t\t\t\t\tbucket.ms += ms;\n\t\t\t\t\tbucket.calls.push(ms);\n\t\t\t\t\tstore.upstream.set(key, bucket);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n","// Its own module: the hook needs the path on every request, and importing it from `server.ts`\n// would load the MCP SDK and the OpenAPI builder at boot.\nexport const MCP_PATH = '/mcp';\n","// Opened per request in hooks.server.ts: `Server-Timing` on every response, and a `[timing]`\n// record for a slow, sampled or cold request, with each upstream's calls.\nimport { createRequestTiming } from '@selvajs/server/http';\nimport { supabaseUpstream } from '@selvajs/supabase-provider';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\n\nexport const requestTiming = createRequestTiming({\n\tlog: (message, fields) => getLogger().info(message, fields),\n\tupstream: supabaseUpstream,\n\tlabels: env.SELVA_RELEASE ? { release: env.SELVA_RELEASE } : {}\n});\nrequestTiming.instrumentFetch();\n","// App routes stay framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces hold an authenticated admin session, where a framable page is a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\n/**\n * Whether a response to `pathname` must refuse framing. Kit routes on the decoded path, so\n * `/%61dmin` renders /admin: this matches what Kit matches, and a path that does not decode is\n * refused too.\n */\nexport function deniesFraming(pathname: string): boolean {\n\tlet path: string;\n\ttry {\n\t\tpath = pathname.split('%25').map(decodeURI).join('%25');\n\t} catch {\n\t\treturn true;\n\t}\n\treturn FRAME_DENIED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));\n}\n","import { redirect, type RequestEvent } from '@sveltejs/kit';\nimport type { ServerInit } from '@sveltejs/kit/hooks';\nimport { dev } from '$app/env';\nimport { isApiError } from '@selvajs/server/api';\nimport type { AuthUser } from '@selvajs/platform';\nimport { SYSTEM_CONTEXT, emptyProfile } from '@selvajs/platform';\nimport {\n\tapplySecurityHeaders,\n\tbuildRequestContext,\n\tcreateHolderVerdictCache,\n\tcreateRouteClassifier,\n\tcreateSessionRefresher,\n\tcreateSessionResolver,\n\tisCrossSiteFormSubmission,\n\tresolveApiToken\n} from '@selvajs/server/http';\nimport { renderThrown, resolveRequestId, REQUEST_ID_HEADER } from '@selvajs/server/logging';\nimport { resolveRetentionPolicy, startRetentionJanitor } from '@selvajs/server/ops';\nimport {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\n\tgetSolveMetricSink,\n\tlazyLogger\n} from '#lib/server/providers.server.js';\nimport { signInMaxAgeMs } from '#lib/server/signInMaxAge.server.js';\nimport { apiTokenCodec, apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { MCP_PATH } from '#lib/server/mcp/path.js';\nimport { readShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { looksLikeShareToken } from '#lib/server/shareLinks/token.server.js';\nimport { requestMemo } from '#lib/server/requestMemo.server.js';\nimport { requestTiming } from '#lib/server/requestTiming.server.js';\n\nconst OAUTH_TOKEN_PATH = '/oauth/token';\nconst holderVerdicts = createHolderVerdictCache();\nlazyLogger.info('Sign-in max age', { component: 'auth', maxAgeMs: signInMaxAgeMs ?? 'off' });\nconst refreshSession = createSessionRefresher(() => providers.auth.sessionRefresh, {\n\tsignInMaxAgeMs,\n\tauth: () => providers.auth\n});\nimport { getBootHealth } from '#lib/server/bootHealth.server.js';\nimport { checkConfigAtBoot } from '#lib/server/config/boot.server.js';\nimport { env } from '#lib/server/env.js';\nimport { deniesFraming } from '#lib/server/framing.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport { closeAllSolveEventStreams } from '#lib/server/solveEvents/sse.server.js';\nimport { findDeploymentDir, startUpdateOutcomeReconciler } from '#lib/server/selfUpdate.server.js';\nimport {\n\tbootstrapUserSession,\n\thasSetupProof,\n\tidentifyWithSetupProof,\n\twireHeaderAuthBootstrap\n} from '#lib/server/auth-bootstrap.server.js';\nimport {\n\tgetRefreshToken,\n\tsetSessionCookie,\n\tsetRefreshCookie,\n\tclearRefreshCookie\n} from '#lib/server/admin-auth.server.js';\n\n// Wired lazily on first real request, not at module import, so test files\n// that import helpers from this module don't trigger provider lookups\n// before their fake providers are installed.\nlet headerAuthBootstrapWired = false;\n\n// Same lazy-on-first-request reasoning as headerAuthBootstrapWired above.\n// Result is cached in bootHealth.server.ts; `/api/health` awaits that promise.\nlet bootHealthKicked = false;\n\n// One-shot per process: a user landing on /login under forward-auth with no\n// resolved identity is the clearest \"headers didn't arrive\" signal, worth a\n// single log line rather than one per anonymous request.\nlet proxyAuthLoginMissWarned = false;\n\n// Once at server start, never in tests that import this module for `handle`.\nexport const init: ServerInit = () => {\n\tcheckConfigAtBoot();\n\trequestTiming.markBooted();\n\t// Not in dev: Vite owns the signals there, and HMR would stack a listener per reload.\n\tif (!dev) {\n\t\tprocess.once('SIGINT', closeAllSolveEventStreams);\n\t\tprocess.once('SIGTERM', closeAllSolveEventStreams);\n\t\tprocess.once('sveltekit:shutdown', () => void exitAfterShutdown());\n\t}\n};\n\nconst SHUTDOWN_FLUSH_MS = 3000;\n\n/**\n * adapter-node closes the HTTP server on SIGINT or SIGTERM, emits this event and\n * then waits for the event loop to empty. Here it never does (limiter sweeps,\n * caches, the solve-event bus), so the process sat until pm2's kill timeout and\n * was SIGKILLed: ten seconds on every stop, restart and update, and the metric\n * sink's last batch lost. Bounded, so a dead database cannot hold the exit.\n */\nasync function exitAfterShutdown(): Promise<void> {\n\tconst sink = getSolveMetricSink() as { close?: () => Promise<void> };\n\ttry {\n\t\tawait Promise.race([\n\t\t\tsink.close?.(),\n\t\t\tnew Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_MS))\n\t\t]);\n\t} catch {\n\t\t// Exiting anyway: a failed flush is not a reason to wait for the SIGKILL.\n\t} finally {\n\t\tprocess.exit(0);\n\t}\n}\n\n// One-way transition (zero users → at least one). Once true, permanent —\n// caching it skips a per-request listUsers DB read after the first user exists.\nlet firstRunResolved = false;\n\nasync function isFirstRun(): Promise<boolean> {\n\tif (firstRunResolved) return false;\n\tconst usersPage = await providers.auth.listUsers({ limit: 1 });\n\tif (usersPage === null) {\n\t\t// OIDC-only provider, no listUsers support — the setup page falls back\n\t\t// to `permissions.hasInstanceAdmin` and first-run gating doesn't apply.\n\t\tfirstRunResolved = true;\n\t\treturn false;\n\t}\n\tif (usersPage.items.length === 0) return true;\n\tfirstRunResolved = true;\n\treturn false;\n}\n\n// `ensureUser` is idempotent and rows don't disappear mid-process, so once a\n// user is ensured, subsequent requests skip the data-layer round-trip (local:\n// a full `user-data.json` read+parse) for a `Set.has` check. Per-process only —\n// a second instance just ensures the same user once itself; safe since the\n// call is idempotent.\nconst ensuredUserIds = new Set<string>();\n\nasync function ensureUserOnce(userId: string): Promise<void> {\n\tif (ensuredUserIds.has(userId)) return;\n\tawait providers.data.ensureUser(SYSTEM_CONTEXT, userId);\n\tensuredUserIds.add(userId);\n}\n\ntype SessionRows = Awaited<ReturnType<typeof readSessionRows>>;\n\ninterface Session {\n\tuser: AuthUser;\n\tprofile: App.Locals['profile'];\n\tctx: App.Locals['ctx'];\n}\n\n/**\n * Profile, platform permissions and membership: independent and keyed only by the user id, so\n * they run together as SYSTEM_CONTEXT (`ctx` isn't built yet), and for a JWT session beside\n * `verifyToken`. Reads only: they run before the token is checked.\n */\nfunction readSessionRows(userId: string) {\n\treturn Promise.all([\n\t\tproviders.data.userProfile.getProfile(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.permissions.getFor(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.orgs.findUserMembership(SYSTEM_CONTEXT, userId)\n\t]);\n}\n\n/**\n * The acting org is the user's first membership, or an instance admin's fallback. `ensureUser`\n * is the local equivalent of Supabase's `handle_new_auth_user` trigger, memoized per process.\n * The rows may have been read before it seeded a brand-new user's row: each fails soft to\n * empty, the correct state for a user with nothing yet.\n */\nasync function buildSession(\n\tuser: AuthUser,\n\t[profile, platformPermissions, membership]: SessionRows,\n\t// Forwarded so adapters scoping by the upstream token (Supabase RLS) get it.\n\tsessionToken: string | undefined\n): Promise<Session> {\n\tawait ensureUserOnce(user.id);\n\treturn {\n\t\tuser,\n\t\tprofile: profile ?? emptyProfile(user.id),\n\t\tctx: await buildRequestContext(\n\t\t\t{ user, sessionToken, platformPermissions, membership: membership?.member ?? null },\n\t\t\t{ orgs: providers.data.orgs }\n\t\t)\n\t};\n}\n\n// No window: every request resolves its own session, since what it holds (stars, recent\n// runs, memberships) changes under many writes that don't invalidate. Requests carrying one\n// token at once still share one resolution, and a JWT's rows are read beside its check.\nconst sessions = createSessionResolver({\n\tverify: (token) => providers.auth.verifyToken(token),\n\tread: readSessionRows,\n\tbuild: buildSession\n});\n\n/** For a user identified without a session token (forward-auth headers). */\nasync function sessionFor(user: AuthUser, sessionToken: string | undefined): Promise<Session> {\n\treturn buildSession(user, await readSessionRows(user.id), sessionToken);\n}\n\nfunction attachSession(event: RequestEvent, session: Session): void {\n\tevent.locals.user = session.user;\n\tevent.locals.profile = session.profile;\n\tevent.locals.ctx = session.ctx;\n}\n\n// ============================================================================\n// Route classification\n// ============================================================================\n//\n// Auth gating is **deny-by-default**: the classifier (mechanics in\n// `@selvajs/server/http`) gates every request unless its path matches one of\n// the allowlists below. Adding a route is safe by default — forgetting to\n// list it makes it gated (401/redirect), not silently public. Named (not\n// inlined into the classifier config) because the best-effort session attach\n// below also needs it: public *pages* get locals populated for a signed-in\n// user, public prefixes/APIs don't.\nconst PUBLIC_PAGE_ROUTES: ReadonlySet<string> = new Set([\n\t'/', // guests see the landing page; authed users get redirected by +page.server.ts\n\t'/login',\n\t'/setup',\n\t'/accept-invite'\n]);\n\nconst routeClassifier = createRouteClassifier({\n\tpublicPages: PUBLIC_PAGE_ROUTES,\n\t// `/auth/` is the OAuth start + callback flow (no session yet by\n\t// definition). `/logout` is a form action that destroys the session then\n\t// redirects. `/docs/` is the API reference — reads no tenant data, and\n\t// gating it would hide it from callers deciding whether to integrate.\n\tpublicPrefixes: ['/auth/', '/logout', '/docs/'],\n\t// Must answer without a session: load-balancer liveness probe, and the\n\t// readiness probe the post-update poller waits on across a restart. The v1\n\t// spec is public for the same reason `/docs/` is. `/mcp` gates itself: it needs a\n\t// key and passes it through to `/api/v1`, which authenticates every call.\n\t// OAuth discovery, registration and token exchange are called server-to-server\n\t// by MCP clients, with no session.\n\tpublicApis: [\n\t\t'/api/health',\n\t\t'/api/health/ready',\n\t\t'/api/v1/openapi.json',\n\t\tMCP_PATH,\n\t\t'/.well-known/oauth-protected-resource',\n\t\t'/.well-known/oauth-protected-resource/mcp',\n\t\t'/.well-known/oauth-authorization-server',\n\t\t'/oauth/register',\n\t\tOAUTH_TOKEN_PATH\n\t],\n\t// Self-gating routes authorize each request themselves; the hook must not\n\t// deny them up front. `/api/files/[...path]` classifies each path against\n\t// the asset-class registry (public branding serves to anyone, org/project\n\t// assets 401 without a session). `/api/v1/solve-events` holds the SSE stream\n\t// (requires a session, checked in the route) and the Compute callback (no\n\t// session by nature — a per-solve bearer instead). The only other route that\n\t// authorizes a request itself is `/api/v1/compute` with a share token: see\n\t// `carriesShareToken`.\n\t//\n\t// No trailing slash on solve-events: the SSE route IS that path, with the\n\t// stream in a query param, so a trailing slash would deny the stream while\n\t// letting the callback (which has a solveId segment) through.\n\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events'],\n\t// Static-asset paths SvelteKit/adapter-node serves directly.\n\tstaticPrefixes: ['/_app/', '/favicon/'],\n\tstaticPaths: ['/favicon.svg', '/robots.txt']\n});\n\n// Exported for tests: these predicates are the deny-by-default policy, and a\n// bug in either is security-relevant.\nexport const { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = routeClassifier;\n\n// The only two routes that honour a share token. A share link is meant to work\n// without an account, so a request that carries one and has no session still\n// reaches the route, which accepts or refuses the token itself. The page serves\n// only the live pointer by token: a draft or version pick still needs a session.\nconst SHARE_TOKEN_API = '/api/v1/compute';\nconst SHARE_TOKEN_PAGE = /^\\/library\\/[^/]+$/;\n\nfunction carriesShareToken(request: Request, url: URL): boolean {\n\tconst onShareRoute =\n\t\turl.pathname === SHARE_TOKEN_API ||\n\t\t(SHARE_TOKEN_PAGE.test(url.pathname) &&\n\t\t\turl.searchParams.get('channel') !== 'draft' &&\n\t\t\t!url.searchParams.has('version'));\n\treturn onShareRoute && readShareToken(request, url) !== null;\n}\n\n// Kept out of `redirectTo`: the login URL lands in access logs and browser history.\nfunction withoutShareToken(url: URL): string {\n\tconst query = new URLSearchParams(\n\t\t[...url.searchParams].filter(([key, value]) => !(key === 'token' && looksLikeShareToken(value)))\n\t).toString();\n\treturn url.pathname + (query ? `?${query}` : '');\n}\n\n// Every request runs inside its read memo, so a layout and its page share repeated reads, and\n// inside its timing store; static assets skip the timing.\nexport const handle: import('@sveltejs/kit/hooks').Handle = (input) => {\n\tconst { event } = input;\n\tconst run = () => requestMemo.run(event.request.method, () => gate(input));\n\tif (isStaticAsset(event.url.pathname)) return run();\n\treturn requestTiming.timeRequest(\n\t\t{\n\t\t\tmethod: event.request.method,\n\t\t\troute: event.route.id ?? event.url.pathname,\n\t\t\tisDataRequest: event.isDataRequest\n\t\t},\n\t\tasync () => run()\n\t);\n};\n\nconst gate: import('@sveltejs/kit/hooks').Handle = async ({ event, resolve }) => {\n\tevent.locals.providers = providers;\n\n\t// Bound once per request; every downstream `locals.log` record inherits\n\t// these fields. `event.url.pathname`, never `.search` — query strings carry\n\t// share tokens, and a log record outlives the token's usefulness to an attacker.\n\tconst requestId = resolveRequestId(event.request.headers);\n\tevent.locals.requestId = requestId;\n\tevent.locals.log = getLogger().child({\n\t\trequestId,\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname\n\t});\n\n\tif (!headerAuthBootstrapWired) {\n\t\twireHeaderAuthBootstrap();\n\t\theaderAuthBootstrapWired = true;\n\t}\n\n\tif (!bootHealthKicked) {\n\t\tbootHealthKicked = true;\n\t\tvoid getBootHealth();\n\t\tstartRetentionJanitor({\n\t\t\tdata: providers.data,\n\t\t\tpolicy: resolveRetentionPolicy(env),\n\t\t\tlogger: getLogger()\n\t\t});\n\t\t// Reconciles a self-update that was in flight when this process came up\n\t\t// into the audit log. No-op when no pending-update state file exists —\n\t\t// see selfUpdate.server.ts for the full lifecycle.\n\t\tconst deploymentDir = findDeploymentDir(env);\n\t\tif (deploymentDir) {\n\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\tdeploymentDir,\n\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t});\n\t\t}\n\t}\n\n\tconst { pathname } = event.url;\n\n\t// SvelteKit's own check is off (vite.config.ts) because it can't exempt the\n\t// token endpoint or bearer requests; this is the same check with those exemptions.\n\tif (\n\t\t!dev &&\n\t\tisCrossSiteFormSubmission(event.request, {\n\t\t\texemptPaths: [OAUTH_TOKEN_PATH],\n\t\t\torigin: publicUrl(event.url).origin\n\t\t})\n\t) {\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(`Cross-site ${event.request.method} form submissions are forbidden`, {\n\t\t\t\tstatus: 403\n\t\t\t}),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\n\t// Static assets bypass every gate below — no auth, no first-run check.\n\tif (isStaticAsset(pathname)) {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// Probes answer before any gate runs — a fresh deployment with no users yet\n\t// is still live and ready, and the first-run 503 below would tell a load\n\t// balancer (or the post-update poller) the opposite.\n\tif (pathname === '/api/health' || pathname === '/api/health/ready') {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// A `selva_` key decides the request on its own: it never falls back to the\n\t// cookie, so a broken key can't quietly run as whoever is signed in.\n\t// `/mcp` carries a key but isn't under `/api/v1`, so the resolver would refuse it.\n\tconst tokenResult =\n\t\tpathname === MCP_PATH\n\t\t\t? ({ kind: 'none' } as const)\n\t\t\t: await resolveApiToken(event.request, {\n\t\t\t\t\tcodec: apiTokenCodec(),\n\t\t\t\t\tauth: providers.auth,\n\t\t\t\t\tdata: providers.data,\n\t\t\t\t\tflag,\n\t\t\t\t\tholderVerdicts,\n\t\t\t\t\tsignInMaxAgeMs,\n\t\t\t\t\tresolutionCache: apiTokenResolutions,\n\t\t\t\t\tlog: event.locals.log\n\t\t\t\t});\n\tif (tokenResult.kind === 'rejected') {\n\t\tconst { status, code, message } = tokenResult;\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (status === 401) headers['WWW-Authenticate'] = 'Bearer error=\"invalid_token\"';\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(JSON.stringify({ message, code }), { status, headers }),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\tif (tokenResult.kind === 'ok') {\n\t\tconst { user, ctx, token } = tokenResult;\n\t\tevent.locals.log = event.locals.log.child({ tokenId: token.id });\n\t\tevent.locals.user = user;\n\t\tevent.locals.ctx = ctx;\n\t\tevent.locals.profile =\n\t\t\t(await providers.data.userProfile.getProfile(SYSTEM_CONTEXT, user.id)) ??\n\t\t\temptyProfile(user.id);\n\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\tconst publicRoute = isPublicRoute(pathname);\n\t// All HTTP endpoints live under `/api/*` — distinguishes 401 JSON from a\n\t// 303 redirect.\n\tconst isJsonApiRoute = pathname.startsWith('/api/');\n\n\t// On first run (no users yet), redirect non-public traffic to /setup so a\n\t// fresh deployment lands on the bootstrap flow instead of a dead login\n\t// page. Public routes pass through unchanged.\n\tif (!publicRoute) {\n\t\tif (await isFirstRun()) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(JSON.stringify({ message: 'Setup required', code: 'SETUP_REQUIRED' }), {\n\t\t\t\t\t\tstatus: 503,\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t}),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\tredirect(303, '/setup');\n\t\t}\n\t}\n\n\t// Deny-by-default: any non-public, non-static path requires a valid session,\n\t// unless it carries a share token the route checks itself.\n\tconst needsAuth = !publicRoute;\n\tif (needsAuth) {\n\t\tlet token = event.cookies.get('admin_session') ?? '';\n\t\tlet session = await sessions.resolve(token);\n\n\t\t// When the access token expired but a refresh token is present (Supabase\n\t\t// OAuth flow), swap silently for a fresh pair and rotate the cookies.\n\t\t// Local/HMAC sessions never set a refresh cookie, so this is a no-op there.\n\t\tif (!session) {\n\t\t\tconst refreshToken = getRefreshToken(event.cookies);\n\t\t\tif (refreshToken && providers.auth.sessionRefresh) {\n\t\t\t\tconst refreshed = await refreshSession(refreshToken);\n\t\t\t\tif (refreshed) {\n\t\t\t\t\tsetSessionCookie(event.cookies, refreshed.sessionToken);\n\t\t\t\t\tsetRefreshCookie(event.cookies, refreshed.refreshToken);\n\t\t\t\t\ttoken = refreshed.sessionToken;\n\t\t\t\t\tsession = await sessions.resolve(token);\n\t\t\t\t} else {\n\t\t\t\t\t// Refresh failed — clear the stale cookie so the next request\n\t\t\t\t\t// goes through the login flow cleanly.\n\t\t\t\t\tclearRefreshCookie(event.cookies);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Forward-proxy fallback: providers that derive identity from trusted\n\t\t// upstream-proxy signals (Caddy forward_auth, oauth2-proxy, etc.) get a\n\t\t// chance to identify the request. See IProxyAuth for the trust contract.\n\t\tlet user = session?.user ?? null;\n\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\tif (!user && proxyAuth) {\n\t\t\tconst setupProven = hasSetupProof(event.cookies);\n\t\t\tuser = await identifyWithSetupProof(setupProven, () =>\n\t\t\t\tproxyAuth.identifyFromHeaders(event.request.headers)\n\t\t\t);\n\t\t\t// First-admin bootstrap for forward-auth deployments: OAuth and\n\t\t\t// email-link callbacks call `bootstrapUserSession` themselves, but the\n\t\t\t// proxy-auth path has no callback. Internally gated by `hasInstanceAdmin`\n\t\t\t// and a no-op once an admin exists, so safe on every authed request.\n\t\t\tif (user) await bootstrapUserSession(user, setupProven);\n\t\t}\n\n\t\tif (!user && carriesShareToken(event.request, event.url)) {\n\t\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t\t}\n\n\t\tif (!user) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmessage: 'Your session has expired. Sign in again to continue.',\n\t\t\t\t\t\t\tcode: 'UNAUTHORIZED'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\t// With the query: an OAuth authorize request is nothing without it.\n\t\t\tredirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);\n\t\t}\n\n\t\tattachSession(event, session ?? (await sessionFor(user, token)));\n\t} else {\n\t\t// Public page route (e.g. `/`): best-effort session attach. If a valid\n\t\t// session cookie is present, populate locals so the UI reflects authed\n\t\t// state (nav, user chip). Failure is silent — public pages keep\n\t\t// rendering for guests. Also applies to the self-gating files proxy,\n\t\t// which needs `locals.ctx` when a session is present so org/project\n\t\t// assets resolve, while still rendering guests' public branding.\n\t\tconst isPublicPage = PUBLIC_PAGE_ROUTES.has(pathname);\n\t\tconst wantsSessionAttach = isPublicPage || isSelfGatingApiRoute(pathname);\n\t\tconst token = wantsSessionAttach ? (event.cookies.get('admin_session') ?? '') : '';\n\t\tconst session = token ? await sessions.resolve(token) : null;\n\t\tlet user = session?.user ?? null;\n\t\tif (!user && wantsSessionAttach && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\n\n\t\t\tif (!user && pathname === '/login' && !proxyAuthLoginMissWarned) {\n\t\t\t\tproxyAuthLoginMissWarned = true;\n\t\t\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\t\t\tconst noHeaders = proxyAuth.hasNoIdentityHeaders(event.request.headers);\n\t\t\t\tconst configured = proxyAuth.configuredHeaderNames.join(', ');\n\t\t\t\tif (noHeaders) {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit and NONE of the configured identity headers arrived. The ' +\n\t\t\t\t\t\t\t'forward-auth proxy is not reaching this process, or is not forwarding the ' +\n\t\t\t\t\t\t\t'configured headers. See the @selvajs/header-auth-provider README ' +\n\t\t\t\t\t\t\t'\"Verification\" section.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit but the UPN header was missing or the user is not allowlisted. ' +\n\t\t\t\t\t\t\t'Some headers arrived but identification still failed — check that the UPN ' +\n\t\t\t\t\t\t\t'header is populated and that the user has been added to header-allowlist.json.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (user) attachSession(event, session ?? (await sessionFor(user, token)));\n\t}\n\n\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n};\n\n// ============================================================================\n// Response headers\n// ============================================================================\n//\n// Applied to every response — successful resolves and the 401/503\n// short-circuits above. The browser-hardening set (nosniff, Referrer-Policy,\n// Permissions-Policy, HSTS in production) lives in `@selvajs/server/http` —\n// see `applySecurityHeaders` there. Cache-control stays here: it encodes this\n// app's asset layout.\n//\n// Frame headers are the one route-dependent piece (`deniesFraming`).\n\nfunction applyResponseHeaders(response: Response, pathname: string, requestId: string): Response {\n\tapplySecurityHeaders(response, {\n\t\thsts: process.env.NODE_ENV === 'production',\n\t\tdenyFraming: deniesFraming(pathname)\n\t});\n\n\t// Echoed so a user reporting \"request X failed\" gives an operator the\n\t// exact key to grep logs with.\n\tresponse.headers.set(REQUEST_ID_HEADER, requestId);\n\n\t// Cache-control: hashed build assets are immutable; other static assets\n\t// get a short TTL.\n\tif (pathname.startsWith('/_app/')) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=31536000, immutable');\n\t} else if (\n\t\tpathname.startsWith('/favicon/') ||\n\t\tpathname === '/favicon.svg' ||\n\t\tpathname === '/robots.txt'\n\t) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=604800');\n\t}\n\n\treturn response;\n}\n\nexport const handleError: import('@sveltejs/kit/hooks').HandleServerError = ({\n\tkind,\n\terror,\n\tevent\n}) => {\n\t// `error(...)` bodies already carry `code`/`fields`, so they reach the client as thrown.\n\tif (kind === 'app') return error;\n\tif (kind !== 'unknown') {\n\t\treturn error.status === 404 ? { message: 'Page not found.', code: 'NOT_FOUND' } : error;\n\t}\n\t// Backstop only. `ApiError` reaching here means a page load called a guard\n\t// without going through `asHttpError()`.\n\tif (isApiError(error)) {\n\t\treturn {\n\t\t\tstatus: error.status,\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tfields: error.fields,\n\t\t\tdetails: error.details\n\t\t};\n\t}\n\t// SvelteKit's default logging drops `cause`, which is where provider\n\t// adapters tend to stash the real reason (Supabase network error, fs\n\t// EACCES, etc.) — kept as a separate field so the message still groups\n\t// cleanly while the stack stays searchable.\n\t//\n\t// `locals.log` already carries requestId/method/route, but handleError can\n\t// fire before `handle` populates locals (a throw in an earlier hook), so\n\t// fall back to the root logger and re-state the fields.\n\tconst log =\n\t\tevent.locals.log ??\n\t\tgetLogger().child({ method: event.request.method, route: event.url.pathname });\n\tlog.error('Unhandled error', {\n\t\tcomponent: 'handleError',\n\t\terr: renderThrown(error),\n\t\tcause: error instanceof Error && error.cause ? String(error.cause) : undefined\n\t});\n\t// Only reached for genuinely unexpected errors — intentional HTTP outcomes\n\t// (incl. the compute route's `apiError(500)` on a failed solve) are\n\t// `HttpError`s handled above. No-op unless SENTRY_DSN is configured.\n\tgetErrorReporter().capture(error, {\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname,\n\t\tuserId: event.locals.ctx?.userId || undefined,\n\t\torgId: event.locals.ctx?.actingOrgId\n\t});\n\treturn { message: 'An unexpected error occurred.', code: 'INTERNAL' };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAA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,CAC1E,MAAM,mBAAmB;EAC5B,WAAW;EACX,KAAK,aAAa,KAAK;EACvB,OAAO,iBAAiB,SAAS,MAAM,QAAQ,OAAO,MAAM,KAAK,IAAI,KAAA;CACtE,CAAC;CAID,iBAAiB,CAAC,CAAC,QAAQ,OAAO;EACjC,QAAQ,MAAM,QAAQ;EACtB,OAAO,MAAM,IAAI;EACjB,QAAQ,MAAM,OAAO,KAAK,UAAU,KAAA;EACpC,OAAO,MAAM,OAAO,KAAK;CAC1B,CAAC;CACD,OAAO;EAAE,SAAS;EAAiC,MAAM;CAAW;AACrE"}
|
|
1
|
+
{"version":3,"file":"hooks.server.js","names":[],"sources":["../../../../providers/supabase/src/upstream.ts","../../../../server/src/http/security-headers.ts","../../../../server/src/http/route-classifier.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/mcp/path.ts","../../../src/lib/server/requestTiming.server.ts","../../../src/lib/server/framing.ts","../../../src/hooks.server.ts"],"sourcesContent":["/**\n * Supabase serves every API under one origin; the path prefix names the service. For a\n * request-timing classifier (`createRequestTiming` in `@selvajs/server/http`): `db`, `auth` or\n * `storage`, and for the database the table or RPC a call reached (`db jobs`, `db rpc/x`).\n */\n\nconst SERVICES: [prefix: string, name: string][] = [\n\t['/rest/v1/', 'db'],\n\t['/auth/v1/', 'auth'],\n\t['/storage/v1/', 'storage']\n];\n\nexport function supabaseUpstream(url: URL): { key: string; target: string } | undefined {\n\tconst service = SERVICES.find(([prefix]) => url.pathname.startsWith(prefix));\n\tif (!service) return undefined;\n\tconst [first = '', second = ''] = url.pathname.slice(service[0].length).split('/');\n\treturn { key: service[1], target: `${service[1]} ${first === 'rpc' ? `rpc/${second}` : first}` };\n}\n","export interface SecurityHeaderOptions {\n\t/**\n\t * Set `Strict-Transport-Security`. Production only — pinning\n\t * http://localhost to HTTPS bricks local development. The caller decides\n\t * what \"production\" means (e.g. `NODE_ENV`).\n\t */\n\thsts: boolean;\n\t/**\n\t * Forbid framing this response. Off by default — Selva-engine app routes are\n\t * built to be embedded. Turn it on for operator surfaces (`/admin/*`,\n\t * `/setup`), where an authenticated session plus a framable page is a\n\t * UI-redress attack. `SameSite=Lax` blunts cross-site POST, not same-origin\n\t * redress, so the cookie flag is not a substitute.\n\t */\n\tdenyFraming?: boolean;\n}\n\n/**\n * Apply baseline browser-hardening headers to a response and return it for\n * chaining. Each is a cheap win that needs no UI verification:\n *\n * - X-Content-Type-Options: nosniff — disables MIME sniffing.\n * - Referrer-Policy: strict-origin-when-cross-origin — strips path and query\n * from cross-origin Referer headers. Matches modern browser defaults, but\n * pins the behavior in case a default drifts.\n * - Permissions-Policy: opts out of browser APIs Selva-engine apps don't use,\n * so XSS can't enable them.\n * - HSTS when `opts.hsts`.\n * - X-Frame-Options + `frame-ancestors 'none'` when `opts.denyFraming` — the\n * caller opts in per route, since embeddable app routes must stay framable.\n *\n * **Intentionally NOT set here:**\n * - A full Content-Security-Policy. Selva-engine apps are built for iframe\n * embedding, so a strict CSP needs validating against real consumer sites\n * before it can ship. `denyFraming` sets only the `frame-ancestors`\n * directive, which constrains nothing else the page loads.\n * - Cache-Control. Asset-path layout is app policy; set it in the caller.\n */\nexport function applySecurityHeaders(response: Response, opts: SecurityHeaderOptions): Response {\n\tresponse.headers.set('X-Content-Type-Options', 'nosniff');\n\tresponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n\tresponse.headers.set(\n\t\t'Permissions-Policy',\n\t\t'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'\n\t);\n\tif (opts.hsts) {\n\t\tresponse.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');\n\t}\n\tif (opts.denyFraming) {\n\t\tresponse.headers.set('X-Frame-Options', 'DENY');\n\t\tresponse.headers.set('Content-Security-Policy', \"frame-ancestors 'none'\");\n\t}\n\treturn response;\n}\n","/**\n * Deny-by-default route classification. A request is gated unless its path\n * matches one of the allowlists supplied here, so forgetting to list a new\n * route makes it gated — a loud 401/redirect, not silently public.\n *\n * The pattern is reusable; the values are app policy, supplied by the consuming\n * app. Matching is plain exact/prefix string comparison: cheap enough for the\n * hooks hot path, and no regex to get wrong.\n */\n\nexport interface RouteClassifierConfig {\n\t/** Exact-match pages needing no session (e.g. `/`, `/login`). */\n\tpublicPages?: Iterable<string>;\n\t/** Public path prefixes (e.g. `/auth/` — OAuth start and callback precede any session). */\n\tpublicPrefixes?: readonly string[];\n\t/**\n\t * Exact-match API endpoints that answer without a session (e.g. a\n\t * load-balancer health probe). Anything listed here is exposed to anonymous\n\t * callers.\n\t */\n\tpublicApis?: Iterable<string>;\n\t/**\n\t * Prefixes whose routes authorize each request themselves (e.g. a blob\n\t * proxy classifying per asset path, or a callback authenticated by a\n\t * per-request bearer). These classify as public so the hook attaches a\n\t * session best-effort and does not deny up front; the route makes the real\n\t * decision. Keep the list short — every other API route stays deny-by-default.\n\t */\n\tselfGatingPrefixes?: readonly string[];\n\t/** Single-prefix form of `selfGatingPrefixes`. */\n\tselfGatingPrefix?: string;\n\t/** Static-asset prefixes the adapter serves directly (e.g. `/_app/`). */\n\tstaticPrefixes?: readonly string[];\n\t/** Exact static-asset paths (e.g. `/favicon.svg`, `/robots.txt`). */\n\tstaticPaths?: Iterable<string>;\n}\n\nexport interface RouteClassifier {\n\t/** Matches `staticPaths`/`staticPrefixes`. These bypass auth gating entirely. */\n\tisStaticAsset(pathname: string): boolean;\n\t/** Matches `selfGatingPrefix`. The hook must not deny these — the route gates itself. */\n\tisSelfGatingApiRoute(pathname: string): boolean;\n\t/** Needs no session: a public page, API, prefix, or a self-gating route. */\n\tisPublicRoute(pathname: string): boolean;\n}\n\nexport function createRouteClassifier(config: RouteClassifierConfig): RouteClassifier {\n\tconst publicPages = new Set(config.publicPages ?? []);\n\tconst publicPrefixes = config.publicPrefixes ?? [];\n\tconst publicApis = new Set(config.publicApis ?? []);\n\tconst selfGatingPrefixes = [\n\t\t...(config.selfGatingPrefixes ?? []),\n\t\t...(config.selfGatingPrefix !== undefined ? [config.selfGatingPrefix] : [])\n\t];\n\tconst staticPrefixes = config.staticPrefixes ?? [];\n\tconst staticPaths = new Set(config.staticPaths ?? []);\n\n\tfunction isStaticAsset(pathname: string): boolean {\n\t\tif (staticPaths.has(pathname)) return true;\n\t\treturn staticPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isSelfGatingApiRoute(pathname: string): boolean {\n\t\treturn selfGatingPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isPublicRoute(pathname: string): boolean {\n\t\tif (publicPages.has(pathname)) return true;\n\t\tif (publicApis.has(pathname)) return true;\n\t\tif (isSelfGatingApiRoute(pathname)) return true;\n\t\treturn publicPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\treturn { isStaticAsset, isSelfGatingApiRoute, isPublicRoute };\n}\n","/**\n * Turns a session token into whatever a host attaches to a request, with the round trips that\n * cost cut to what the token needs.\n *\n * - The user's rows are read beside `verify`, keyed by the token's unverified subject, and kept\n * only when `verify` confirms that same user. `read` must be a read: it runs before the token\n * is checked, so it must not write anything for the subject it is handed.\n * - Requests carrying one token share one resolution while it runs.\n * - With `freshForMs`, a resolved session is reused for that long. Past it the session is still\n * answered, and resolved again behind the request; a re-check that refuses the token drops it,\n * so after a sign-out or disable the requests already in flight are the last to get through.\n * A session is never answered past its token's expiry, so row security never sees an expired\n * token mid-request.\n */\n\nimport type { AuthUser } from '@selvajs/platform';\n\nexport interface SessionResolverConfig<Rows, Session> {\n\t/** The token's user, or null for a token it refuses. */\n\tverify(token: string): Promise<AuthUser | null>;\n\t/** Everything the session needs that is keyed by the user id alone. Never a write. */\n\tread(userId: string): Promise<Rows>;\n\t/** The session from the verified user and its rows. Writes for the user belong here. */\n\tbuild(user: AuthUser, rows: Rows, token: string): Promise<Session> | Session;\n\t/**\n\t * How long a resolved session is reused before a request re-checks it behind its answer.\n\t * 0 (the default) keeps nothing between requests: every request resolves.\n\t */\n\tfreshForMs?: number;\n\t/** The cap on remembered sessions; the oldest go first. Default 5,000. */\n\tmaxEntries?: number;\n\t/** The token's subject, unverified: which rows to read ahead. Default: a JWT's `sub`. */\n\tsubjectOf?: (token: string) => string | null;\n\t/** The token's expiry in ms epoch, unverified. Default: a JWT's `exp`. Null: unknown. */\n\texpiresAtOf?: (token: string) => number | null;\n\t/** A background re-check that threw rather than refused. The session is kept. */\n\tonRefreshError?: (err: unknown) => void;\n\tnow?: () => number;\n}\n\nexport interface SessionResolver<Session> {\n\t/** The token's session, or null when `verify` refuses it. */\n\tresolve(token: string): Promise<Session | null>;\n\t/** Forget one token's session: after a sign-out, or a change to what it holds. */\n\tinvalidate(token: string): void;\n\t/** Forget every session of `userId`: after a change to their permissions or memberships. */\n\tinvalidateUser(userId: string): void;\n\tclear(): void;\n}\n\ninterface Entry<Session> {\n\tsession: Session;\n\tuserId: string;\n\tresolvedAt: number;\n\t/** Never answered at or past this: the token's expiry, else the end of the fresh window. */\n\tuntil: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 5_000;\n\nexport function createSessionResolver<Rows, Session>(\n\tconfig: SessionResolverConfig<Rows, Session>\n): SessionResolver<Session> {\n\tconst freshForMs = Math.max(0, config.freshForMs ?? 0);\n\tconst maxEntries = Math.max(1, config.maxEntries ?? DEFAULT_MAX_ENTRIES);\n\tconst subjectOf = config.subjectOf ?? jwtSubject;\n\tconst expiresAtOf = config.expiresAtOf ?? jwtExpiresAt;\n\tconst now = config.now ?? Date.now;\n\tconst entries = new Map<string, Entry<Session>>();\n\tconst inFlight = new Map<string, Promise<Entry<Session> | null>>();\n\n\tasync function build(token: string): Promise<Entry<Session> | null> {\n\t\tconst subject = subjectOf(token);\n\t\tconst ahead = subject ? config.read(subject) : null;\n\t\t// A token that fails verification never awaits its read-ahead.\n\t\tahead?.catch(() => {});\n\t\tconst user = await config.verify(token);\n\t\tif (!user) return null;\n\t\tconst rows = ahead && user.id === subject ? await ahead : await config.read(user.id);\n\t\tconst session = await config.build(user, rows, token);\n\t\tconst resolvedAt = now();\n\t\tconst expiresAt = expiresAtOf(token);\n\t\treturn {\n\t\t\tsession,\n\t\t\tuserId: user.id,\n\t\t\tresolvedAt,\n\t\t\tuntil: expiresAt ?? resolvedAt + freshForMs\n\t\t};\n\t}\n\n\tfunction remember(token: string, entry: Entry<Session>): void {\n\t\tif (freshForMs === 0 || entry.until <= now()) return;\n\t\tif (entries.size >= maxEntries) {\n\t\t\tconst at = now();\n\t\t\tfor (const [key, e] of entries) if (e.until <= at) entries.delete(key);\n\t\t\t// Map keeps insertion order, so the first key is the oldest.\n\t\t\twhile (entries.size >= maxEntries) entries.delete(entries.keys().next().value!);\n\t\t}\n\t\tentries.delete(token);\n\t\tentries.set(token, entry);\n\t}\n\n\tfunction start(token: string): Promise<Entry<Session> | null> {\n\t\tconst resolution = build(token).then((entry) => {\n\t\t\t// An invalidation while it ran dropped this resolution: what it read may be stale.\n\t\t\tif (inFlight.get(token) === resolution) {\n\t\t\t\tif (entry) remember(token, entry);\n\t\t\t\telse entries.delete(token);\n\t\t\t}\n\t\t\treturn entry;\n\t\t});\n\t\tinFlight.set(token, resolution);\n\t\tconst settle = () => {\n\t\t\tif (inFlight.get(token) === resolution) inFlight.delete(token);\n\t\t};\n\t\tresolution.then(settle, settle);\n\t\treturn resolution;\n\t}\n\n\treturn {\n\t\tasync resolve(token) {\n\t\t\tif (!token) return null;\n\t\t\tconst entry = entries.get(token);\n\t\t\tif (entry) {\n\t\t\t\tconst at = now();\n\t\t\t\tif (entry.until <= at) {\n\t\t\t\t\tentries.delete(token);\n\t\t\t\t} else {\n\t\t\t\t\tif (at - entry.resolvedAt >= freshForMs && !inFlight.has(token)) {\n\t\t\t\t\t\tstart(token).catch((err) => config.onRefreshError?.(err));\n\t\t\t\t\t}\n\t\t\t\t\treturn entry.session;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst resolved = await (inFlight.get(token) ?? start(token));\n\t\t\treturn resolved?.session ?? null;\n\t\t},\n\t\tinvalidate(token) {\n\t\t\tentries.delete(token);\n\t\t\tinFlight.delete(token);\n\t\t},\n\t\tinvalidateUser(userId) {\n\t\t\tfor (const [token, entry] of entries) if (entry.userId === userId) entries.delete(token);\n\t\t\t// A resolution under way may hold the user's old rows; none of them is kept.\n\t\t\tinFlight.clear();\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t\tinFlight.clear();\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Unverified JWT claims\n// ============================================================================\n\nfunction jwtClaims(token: string): Record<string, unknown> | null {\n\tconst parts = token.split('.');\n\tif (parts.length !== 3 || !parts[1]) return null;\n\ttry {\n\t\tconst claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));\n\t\treturn claims && typeof claims === 'object' ? claims : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction jwtSubject(token: string): string | null {\n\tconst sub = jwtClaims(token)?.sub;\n\treturn typeof sub === 'string' && sub ? sub : null;\n}\n\nfunction jwtExpiresAt(token: string): number | null {\n\tconst exp = jwtClaims(token)?.exp;\n\treturn typeof exp === 'number' ? exp * 1000 : null;\n}\n","/**\n * Per-request timing: where a request's wall time went, as named spans plus every outbound\n * fetch grouped by upstream. One AsyncLocalStorage store per request, opened by `timeRequest`\n * in the host's handle hook. The result goes out twice: a `Server-Timing` header on the\n * response, and one structured record through `log` for a request that is slow, sampled, or the\n * first the process served.\n *\n * Fetch time is time to response headers, not body: round-trip latency, which a chain of\n * sequential awaits multiplies. Parallel fetches overlap, so a bucket's `ms` is a sum and can\n * exceed the request's wall time.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\n/** Which upstream a fetch reached, and optionally the table or endpoint within it. */\nexport interface Upstream {\n\tkey: string;\n\ttarget?: string;\n}\n\nexport interface TimedRequest {\n\tmethod: string;\n\t/** The route id (`/s/[token]`), so records aggregate across ids; the path when unrouted. */\n\troute: string;\n\tisDataRequest?: boolean;\n}\n\nexport interface RequestTimingOptions {\n\t/** Writes one record. Fields are typed JSON; never put payload values in them. */\n\tlog: (message: string, fields: Record<string, unknown>) => void;\n\t/** Names the upstream of a fetch; unnamed ones bucket by host. */\n\tupstream?: (url: URL) => Upstream | undefined;\n\t/** A request at or over this is logged. Default 200 ms. */\n\tslowMs?: number;\n\t/**\n\t * This share of requests is logged whatever its time, marked `sampled`: slow-only records\n\t * lean toward whatever got slower, the sampled ones compare across a change. Default 0.1.\n\t */\n\tsampleRate?: number;\n\t/** Stamped on every record, e.g. the revision; `instance` is added per process. */\n\tlabels?: Record<string, string>;\n}\n\nexport interface RequestTiming {\n\t/**\n\t * Runs one request inside a timing store, stamps `Server-Timing` on its response and logs it\n\t * when due. A throw (a framework redirect included) is logged and rethrown.\n\t */\n\ttimeRequest(req: TimedRequest, fn: () => Promise<Response>): Promise<Response>;\n\t/** Times `fn` as a named span of the current request; outside a request it just runs. */\n\tspan<T>(name: string, fn: () => Promise<T> | T): Promise<T>;\n\t/** Attaches facts to the current request's record; a no-op outside a request. */\n\tfact(facts: Record<string, unknown>): void;\n\t/** Whether the current request is the first this process served. */\n\tisCold(): boolean;\n\t/** Called once the server can take requests: the cold-start record's `bootMs`. */\n\tmarkBooted(): void;\n\t/** Wraps the global `fetch` once; clients that look it up at call time are then timed. */\n\tinstrumentFetch(): void;\n}\n\n/** `calls` holds each call's ms, for the record's per-call median and max. */\ntype Bucket = { count: number; ms: number; calls: number[] };\n\ninterface Store {\n\tspans: { name: string; ms: number }[];\n\tupstream: Map<string, Bucket>;\n\ttargets: Map<string, number>;\n\t/** Attempts a client re-sent after a failed one (`X-Retry-Count`). */\n\tretries: number;\n\tfacts: Record<string, unknown>;\n\tcold: boolean;\n}\n\nconst round = (ms: number) => Math.round(ms);\n\nfunction median(values: number[]): number {\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = sorted.length >> 1;\n\treturn sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction urlOf(input: Parameters<typeof fetch>[0]): URL | undefined {\n\ttry {\n\t\treturn new URL(input instanceof Request ? input.url : String(input));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isRetry(init: Parameters<typeof fetch>[1]): boolean {\n\tconst headers = init?.headers;\n\tif (!headers) return false;\n\tif (headers instanceof Headers) return headers.has('x-retry-count');\n\tif (Array.isArray(headers)) return headers.some(([k]) => k.toLowerCase() === 'x-retry-count');\n\treturn Object.keys(headers).some((k) => k.toLowerCase() === 'x-retry-count');\n}\n\n/** Parses a `Server-Timing` value into `{ name: ms }`, a desc-only entry into `{ name: desc }`. */\nexport function parseServerTimingHeader(\n\theader: string | null | undefined\n): Record<string, number | string> {\n\tconst out: Record<string, number | string> = {};\n\tfor (const entry of header?.split(',') ?? []) {\n\t\tconst [name, ...params] = entry.trim().split(';');\n\t\tif (!name) continue;\n\t\tfor (const p of params) {\n\t\t\tconst [k, v = ''] = p.trim().split('=');\n\t\t\tif (k === 'dur') out[name] = round(Number(v));\n\t\t\telse if (k === 'desc' && !(name in out)) out[name] = v.replace(/^\"|\"$/g, '');\n\t\t}\n\t}\n\treturn out;\n}\n\nexport function createRequestTiming(options: RequestTimingOptions): RequestTiming {\n\tconst slowMs = options.slowMs ?? 200;\n\tconst sampleRate = options.sampleRate ?? 0.1;\n\tconst labels = { instance: randomUUID().slice(0, 8), ...options.labels };\n\tconst als = new AsyncLocalStorage<Store>();\n\tlet bootMs: number | null = null;\n\tlet served = false;\n\tlet installed = false;\n\n\tconst log = (message: string, fields: Record<string, unknown>) => {\n\t\ttry {\n\t\t\toptions.log(message, { ...labels, ...fields });\n\t\t} catch {\n\t\t\t// Telemetry never fails a request.\n\t\t}\n\t};\n\n\tfunction upstreamOf(url: URL | undefined): Upstream {\n\t\tif (!url) return { key: 'other' };\n\t\treturn options.upstream?.(url) ?? { key: url.host };\n\t}\n\n\t/** An upstream that times itself (`Server-Timing`) lands on the record by path. */\n\tfunction recordUpstreamTiming(store: Store, url: URL | undefined, response: Response): void {\n\t\tconst timing = response.headers.get('server-timing');\n\t\tif (!timing || !url) return;\n\t\tconst byPath = (store.facts.upstreamTiming as Record<string, unknown> | undefined) ?? {};\n\t\tbyPath[url.pathname] = parseServerTimingHeader(timing);\n\t\tstore.facts.upstreamTiming = byPath;\n\t}\n\n\tfunction serverTiming(store: Store, totalMs: number): string {\n\t\tconst parts = store.spans.map(\n\t\t\t(s) => `app_${s.name.replace(/[^\\w-]/g, '_')};dur=${s.ms.toFixed(1)}`\n\t\t);\n\t\tfor (const [key, b] of store.upstream) {\n\t\t\tparts.push(`up;desc=\"${key} x${b.count}\";dur=${b.ms.toFixed(1)}`);\n\t\t}\n\t\tif (store.retries > 0) parts.push(`retries;desc=\"${store.retries}\"`);\n\t\tparts.push(`app_total;dur=${totalMs.toFixed(1)}`);\n\t\treturn parts.join(', ');\n\t}\n\n\tfunction logTiming(\n\t\treq: TimedRequest,\n\t\tstatus: number | 'thrown',\n\t\ttotalMs: number,\n\t\tstore: Store,\n\t\tsampled: boolean\n\t): void {\n\t\tconst upstream = Object.fromEntries(\n\t\t\t[...store.upstream].map(([k, b]) => [\n\t\t\t\tk,\n\t\t\t\t{\n\t\t\t\t\tcount: b.count,\n\t\t\t\t\tms: round(b.ms),\n\t\t\t\t\tp50: round(median(b.calls)),\n\t\t\t\t\tmax: round(Math.max(...b.calls))\n\t\t\t\t}\n\t\t\t])\n\t\t);\n\t\t// A span name that ran more than once sums.\n\t\tconst spans: Record<string, number> = {};\n\t\tfor (const s of store.spans) spans[s.name] = round((spans[s.name] ?? 0) + s.ms);\n\t\tlog(\n\t\t\t`[timing] ${req.method} ${req.route}${req.isDataRequest ? ' (data)' : ''} ${status} ${round(totalMs)}ms`,\n\t\t\t{\n\t\t\t\ttiming: {\n\t\t\t\t\troute: req.route,\n\t\t\t\t\tmethod: req.method,\n\t\t\t\t\tdata: req.isDataRequest ?? false,\n\t\t\t\t\tstatus,\n\t\t\t\t\ttotalMs: round(totalMs),\n\t\t\t\t\t...(store.cold && { cold: true }),\n\t\t\t\t\t...(sampled && { sampled: true }),\n\t\t\t\t\tspans,\n\t\t\t\t\tupstream,\n\t\t\t\t\tcalls: Object.fromEntries(store.targets),\n\t\t\t\t\t...(store.retries > 0 && { retries: store.retries }),\n\t\t\t\t\t...store.facts\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\treturn {\n\t\tasync timeRequest(req, fn) {\n\t\t\tconst cold = !served;\n\t\t\tserved = true;\n\t\t\tconst store: Store = {\n\t\t\t\tspans: [],\n\t\t\t\tupstream: new Map(),\n\t\t\t\ttargets: new Map(),\n\t\t\t\tretries: 0,\n\t\t\t\tfacts: {},\n\t\t\t\tcold\n\t\t\t};\n\t\t\tconst start = performance.now();\n\t\t\tif (cold) {\n\t\t\t\t// Process start to `markBooted`, and to this request: their gap is idle time.\n\t\t\t\tlog(`[coldstart] ${req.method} ${req.route}`, {\n\t\t\t\t\tcoldstart: { bootMs, firstRequestMs: round(start), route: req.route }\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet status: number | 'thrown' = 'thrown';\n\t\t\ttry {\n\t\t\t\tconst response = await als.run(store, fn);\n\t\t\t\tstatus = response.status;\n\t\t\t\ttry {\n\t\t\t\t\tresponse.headers.append('Server-Timing', serverTiming(store, performance.now() - start));\n\t\t\t\t} catch {\n\t\t\t\t\t// Immutable headers (a fetched Response passed through): the record still has it.\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t} finally {\n\t\t\t\tconst totalMs = performance.now() - start;\n\t\t\t\tconst sampled = Math.random() < sampleRate;\n\t\t\t\t// The cold request always: a comparison across a change must be able to drop it.\n\t\t\t\tif (cold || sampled || totalMs >= slowMs) logTiming(req, status, totalMs, store, sampled);\n\t\t\t}\n\t\t},\n\n\t\tasync span(name, fn) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (!store) return fn();\n\t\t\tconst start = performance.now();\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} finally {\n\t\t\t\tstore.spans.push({ name, ms: performance.now() - start });\n\t\t\t}\n\t\t},\n\n\t\tfact(facts) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (store) Object.assign(store.facts, facts);\n\t\t},\n\n\t\tisCold: () => als.getStore()?.cold ?? false,\n\n\t\tmarkBooted() {\n\t\t\tbootMs ??= round(performance.now());\n\t\t},\n\n\t\tinstrumentFetch() {\n\t\t\tif (installed) return;\n\t\t\tinstalled = true;\n\t\t\tconst original = globalThis.fetch;\n\t\t\tglobalThis.fetch = async (input, init) => {\n\t\t\t\tconst store = als.getStore();\n\t\t\t\tif (!store) return original(input, init);\n\t\t\t\tconst start = performance.now();\n\t\t\t\tconst url = urlOf(input);\n\t\t\t\tconst { key, target } = upstreamOf(url);\n\t\t\t\tif (target) store.targets.set(target, (store.targets.get(target) ?? 0) + 1);\n\t\t\t\tif (isRetry(init)) store.retries += 1;\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await original(input, init);\n\t\t\t\t\trecordUpstreamTiming(store, url, response);\n\t\t\t\t\treturn response;\n\t\t\t\t} finally {\n\t\t\t\t\tconst bucket = store.upstream.get(key) ?? { count: 0, ms: 0, calls: [] };\n\t\t\t\t\tconst ms = performance.now() - start;\n\t\t\t\t\tbucket.count += 1;\n\t\t\t\t\tbucket.ms += ms;\n\t\t\t\t\tbucket.calls.push(ms);\n\t\t\t\t\tstore.upstream.set(key, bucket);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n","// Its own module: the hook needs the path on every request, and importing it from `server.ts`\n// would load the MCP SDK and the OpenAPI builder at boot.\nexport const MCP_PATH = '/mcp';\n","// Opened per request in hooks.server.ts: `Server-Timing` on every response, and a `[timing]`\n// record for a slow, sampled or cold request, with each upstream's calls.\nimport { createRequestTiming } from '@selvajs/server/http';\nimport { supabaseUpstream } from '@selvajs/supabase-provider';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\n\nexport const requestTiming = createRequestTiming({\n\tlog: (message, fields) => getLogger().info(message, fields),\n\tupstream: supabaseUpstream,\n\tlabels: env.SELVA_RELEASE ? { release: env.SELVA_RELEASE } : {}\n});\nrequestTiming.instrumentFetch();\n","// App routes stay framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces hold an authenticated admin session, where a framable page is a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\n/**\n * Whether a response to `pathname` must refuse framing. Kit routes on the decoded path, so\n * `/%61dmin` renders /admin: this matches what Kit matches, and a path that does not decode is\n * refused too.\n */\nexport function deniesFraming(pathname: string): boolean {\n\tlet path: string;\n\ttry {\n\t\tpath = pathname.split('%25').map(decodeURI).join('%25');\n\t} catch {\n\t\treturn true;\n\t}\n\treturn FRAME_DENIED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));\n}\n","import { redirect, type RequestEvent } from '@sveltejs/kit';\nimport type { ServerInit } from '@sveltejs/kit/hooks';\nimport { dev } from '$app/env';\nimport { isApiError } from '@selvajs/server/api';\nimport type { AuthUser } from '@selvajs/platform';\nimport { SYSTEM_CONTEXT, emptyProfile } from '@selvajs/platform';\nimport {\n\tapplySecurityHeaders,\n\tbuildRequestContext,\n\tcreateHolderVerdictCache,\n\tcreateRouteClassifier,\n\tcreateSessionRefresher,\n\tcreateSessionResolver,\n\tisCrossSiteFormSubmission,\n\tresolveApiToken\n} from '@selvajs/server/http';\nimport { renderThrown, resolveRequestId, REQUEST_ID_HEADER } from '@selvajs/server/logging';\nimport { resolveRetentionPolicy, startRetentionJanitor } from '@selvajs/server/ops';\nimport {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\n\tgetSolveMetricSink,\n\tlazyLogger\n} from '#lib/server/providers.server.js';\nimport { signInMaxAgeMs } from '#lib/server/signInMaxAge.server.js';\nimport { apiTokenCodec, apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { MCP_PATH } from '#lib/server/mcp/path.js';\nimport { readShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { looksLikeShareToken } from '#lib/server/shareLinks/token.server.js';\nimport { requestMemo } from '#lib/server/requestMemo.server.js';\nimport { requestTiming } from '#lib/server/requestTiming.server.js';\n\nconst OAUTH_TOKEN_PATH = '/oauth/token';\nconst holderVerdicts = createHolderVerdictCache();\nlazyLogger.info('Sign-in max age', { component: 'auth', maxAgeMs: signInMaxAgeMs ?? 'off' });\nconst refreshSession = createSessionRefresher(() => providers.auth.sessionRefresh, {\n\tsignInMaxAgeMs,\n\tauth: () => providers.auth\n});\nimport { getBootHealth } from '#lib/server/bootHealth.server.js';\nimport { checkConfigAtBoot } from '#lib/server/config/boot.server.js';\nimport { env } from '#lib/server/env.js';\nimport { deniesFraming } from '#lib/server/framing.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport { closeAllSolveEventStreams } from '#lib/server/solveEvents/sse.server.js';\nimport { findDeploymentDir, startUpdateOutcomeReconciler } from '#lib/server/selfUpdate.server.js';\nimport {\n\tbootstrapUserSession,\n\thasSetupProof,\n\tidentifyWithSetupProof,\n\twireHeaderAuthBootstrap\n} from '#lib/server/auth-bootstrap.server.js';\nimport {\n\tgetRefreshToken,\n\tsetSessionCookie,\n\tsetRefreshCookie,\n\tclearRefreshCookie\n} from '#lib/server/admin-auth.server.js';\n\n// Wired lazily on first real request, not at module import, so test files\n// that import helpers from this module don't trigger provider lookups\n// before their fake providers are installed.\nlet headerAuthBootstrapWired = false;\n\n// Same lazy-on-first-request reasoning as headerAuthBootstrapWired above.\n// Result is cached in bootHealth.server.ts; `/api/health` awaits that promise.\nlet bootHealthKicked = false;\n\n// One-shot per process: a user landing on /login under forward-auth with no\n// resolved identity is the clearest \"headers didn't arrive\" signal, worth a\n// single log line rather than one per anonymous request.\nlet proxyAuthLoginMissWarned = false;\n\n// Once at server start, never in tests that import this module for `handle`.\nexport const init: ServerInit = () => {\n\tcheckConfigAtBoot();\n\trequestTiming.markBooted();\n\t// Not in dev: Vite owns the signals there, and HMR would stack a listener per reload.\n\tif (!dev) {\n\t\tprocess.once('SIGINT', closeAllSolveEventStreams);\n\t\tprocess.once('SIGTERM', closeAllSolveEventStreams);\n\t\tprocess.once('sveltekit:shutdown', () => void exitAfterShutdown());\n\t}\n};\n\nconst SHUTDOWN_FLUSH_MS = 3000;\n\n/**\n * adapter-node closes the HTTP server on SIGINT or SIGTERM, emits this event and\n * then waits for the event loop to empty. Here it never does (limiter sweeps,\n * caches, the solve-event bus), so the process sat until pm2's kill timeout and\n * was SIGKILLed: ten seconds on every stop, restart and update, and the metric\n * sink's last batch lost. Bounded, so a dead database cannot hold the exit.\n */\nasync function exitAfterShutdown(): Promise<void> {\n\tconst sink = getSolveMetricSink() as { close?: () => Promise<void> };\n\ttry {\n\t\tawait Promise.race([\n\t\t\tsink.close?.(),\n\t\t\tnew Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_MS))\n\t\t]);\n\t} catch {\n\t\t// Exiting anyway: a failed flush is not a reason to wait for the SIGKILL.\n\t} finally {\n\t\tprocess.exit(0);\n\t}\n}\n\n// One-way transition (zero users → at least one). Once true, permanent —\n// caching it skips a per-request listUsers DB read after the first user exists.\nlet firstRunResolved = false;\n\nasync function isFirstRun(): Promise<boolean> {\n\tif (firstRunResolved) return false;\n\tconst usersPage = await providers.auth.listUsers({ limit: 1 });\n\tif (usersPage === null) {\n\t\t// OIDC-only provider, no listUsers support — the setup page falls back\n\t\t// to `permissions.hasInstanceAdmin` and first-run gating doesn't apply.\n\t\tfirstRunResolved = true;\n\t\treturn false;\n\t}\n\tif (usersPage.items.length === 0) return true;\n\tfirstRunResolved = true;\n\treturn false;\n}\n\n// `ensureUser` is idempotent and rows don't disappear mid-process, so once a\n// user is ensured, subsequent requests skip the data-layer round-trip (local:\n// a full `user-data.json` read+parse) for a `Set.has` check. Per-process only —\n// a second instance just ensures the same user once itself; safe since the\n// call is idempotent.\nconst ensuredUserIds = new Set<string>();\n\nasync function ensureUserOnce(userId: string): Promise<void> {\n\tif (ensuredUserIds.has(userId)) return;\n\tawait providers.data.ensureUser(SYSTEM_CONTEXT, userId);\n\tensuredUserIds.add(userId);\n}\n\ntype SessionRows = Awaited<ReturnType<typeof readSessionRows>>;\n\ninterface Session {\n\tuser: AuthUser;\n\tprofile: App.Locals['profile'];\n\tctx: App.Locals['ctx'];\n}\n\n/**\n * Profile, platform permissions and membership: independent and keyed only by the user id, so\n * they run together as SYSTEM_CONTEXT (`ctx` isn't built yet), and for a JWT session beside\n * `verifyToken`. Reads only: they run before the token is checked.\n */\nfunction readSessionRows(userId: string) {\n\treturn Promise.all([\n\t\tproviders.data.userProfile.getProfile(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.permissions.getFor(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.orgs.findUserMembership(SYSTEM_CONTEXT, userId)\n\t]);\n}\n\n/**\n * The acting org is the user's first membership, or an instance admin's fallback. `ensureUser`\n * is the local equivalent of Supabase's `handle_new_auth_user` trigger, memoized per process.\n * The rows may have been read before it seeded a brand-new user's row: each fails soft to\n * empty, the correct state for a user with nothing yet.\n */\nasync function buildSession(\n\tuser: AuthUser,\n\t[profile, platformPermissions, membership]: SessionRows,\n\t// Forwarded so adapters scoping by the upstream token (Supabase RLS) get it.\n\tsessionToken: string | undefined\n): Promise<Session> {\n\tawait ensureUserOnce(user.id);\n\treturn {\n\t\tuser,\n\t\tprofile: profile ?? emptyProfile(user.id),\n\t\tctx: await buildRequestContext(\n\t\t\t{ user, sessionToken, platformPermissions, membership: membership?.member ?? null },\n\t\t\t{ orgs: providers.data.orgs }\n\t\t)\n\t};\n}\n\n// No window: every request resolves its own session, since what it holds (stars, recent\n// runs, memberships) changes under many writes that don't invalidate. Requests carrying one\n// token at once still share one resolution, and a JWT's rows are read beside its check.\nconst sessions = createSessionResolver({\n\tverify: (token) => providers.auth.verifyToken(token),\n\tread: readSessionRows,\n\tbuild: buildSession\n});\n\n/** For a user identified without a session token (forward-auth headers). */\nasync function sessionFor(user: AuthUser, sessionToken: string | undefined): Promise<Session> {\n\treturn buildSession(user, await readSessionRows(user.id), sessionToken);\n}\n\nfunction attachSession(event: RequestEvent, session: Session): void {\n\tevent.locals.user = session.user;\n\tevent.locals.profile = session.profile;\n\tevent.locals.ctx = session.ctx;\n}\n\n// ============================================================================\n// Route classification\n// ============================================================================\n//\n// Auth gating is **deny-by-default**: the classifier (mechanics in\n// `@selvajs/server/http`) gates every request unless its path matches one of\n// the allowlists below. Adding a route is safe by default — forgetting to\n// list it makes it gated (401/redirect), not silently public. Named (not\n// inlined into the classifier config) because the best-effort session attach\n// below also needs it: public *pages* get locals populated for a signed-in\n// user, public prefixes/APIs don't.\nconst PUBLIC_PAGE_ROUTES: ReadonlySet<string> = new Set([\n\t'/', // guests see the landing page; authed users get redirected by +page.server.ts\n\t'/login',\n\t'/setup',\n\t'/accept-invite'\n]);\n\nconst routeClassifier = createRouteClassifier({\n\tpublicPages: PUBLIC_PAGE_ROUTES,\n\t// `/auth/` is the OAuth start + callback flow (no session yet by\n\t// definition). `/logout` is a form action that destroys the session then\n\t// redirects. `/docs/` is the API reference — reads no tenant data, and\n\t// gating it would hide it from callers deciding whether to integrate.\n\tpublicPrefixes: ['/auth/', '/logout', '/docs/'],\n\t// Must answer without a session: load-balancer liveness probe, and the\n\t// readiness probe the post-update poller waits on across a restart. The v1\n\t// spec is public for the same reason `/docs/` is. `/mcp` gates itself: it needs a\n\t// key and passes it through to `/api/v1`, which authenticates every call.\n\t// OAuth discovery, registration and token exchange are called server-to-server\n\t// by MCP clients, with no session.\n\tpublicApis: [\n\t\t'/api/health',\n\t\t'/api/health/ready',\n\t\t'/api/v1/openapi.json',\n\t\tMCP_PATH,\n\t\t'/.well-known/oauth-protected-resource',\n\t\t'/.well-known/oauth-protected-resource/mcp',\n\t\t'/.well-known/oauth-authorization-server',\n\t\t'/oauth/register',\n\t\tOAUTH_TOKEN_PATH\n\t],\n\t// Self-gating routes authorize each request themselves; the hook must not\n\t// deny them up front. `/api/files/[...path]` classifies each path against\n\t// the asset-class registry (public branding serves to anyone, org/project\n\t// assets 401 without a session). `/api/v1/solve-events` holds the SSE stream\n\t// (requires a session, checked in the route) and the Compute callback (no\n\t// session by nature — a per-solve bearer instead). The only other route that\n\t// authorizes a request itself is `/api/v1/compute` with a share token: see\n\t// `carriesShareToken`.\n\t//\n\t// No trailing slash on solve-events: the SSE route IS that path, with the\n\t// stream in a query param, so a trailing slash would deny the stream while\n\t// letting the callback (which has a solveId segment) through.\n\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events'],\n\t// Static-asset paths SvelteKit/adapter-node serves directly.\n\tstaticPrefixes: ['/_app/', '/favicon/'],\n\tstaticPaths: ['/favicon.svg', '/robots.txt']\n});\n\n// Exported for tests: these predicates are the deny-by-default policy, and a\n// bug in either is security-relevant.\nexport const { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = routeClassifier;\n\n// The only two routes that honour a share token. A share link is meant to work\n// without an account, so a request that carries one and has no session still\n// reaches the route, which accepts or refuses the token itself. The page serves\n// only the live pointer by token: a draft or version pick still needs a session.\nconst SHARE_TOKEN_API = '/api/v1/compute';\nconst SHARE_TOKEN_PAGE = /^\\/library\\/[^/]+$/;\n\nfunction carriesShareToken(request: Request, url: URL): boolean {\n\tconst onShareRoute =\n\t\turl.pathname === SHARE_TOKEN_API ||\n\t\t(SHARE_TOKEN_PAGE.test(url.pathname) &&\n\t\t\turl.searchParams.get('channel') !== 'draft' &&\n\t\t\t!url.searchParams.has('version'));\n\treturn onShareRoute && readShareToken(request, url) !== null;\n}\n\n// Kept out of `redirectTo`: the login URL lands in access logs and browser history.\nfunction withoutShareToken(url: URL): string {\n\tconst query = new URLSearchParams(\n\t\t[...url.searchParams].filter(([key, value]) => !(key === 'token' && looksLikeShareToken(value)))\n\t).toString();\n\treturn url.pathname + (query ? `?${query}` : '');\n}\n\n// Every request runs inside its read memo, so a layout and its page share repeated reads, and\n// inside its timing store; static assets skip the timing.\nexport const handle: import('@sveltejs/kit/hooks').Handle = (input) => {\n\tconst { event } = input;\n\tconst run = () =>\n\t\trequestMemo.run(event.request.method, async () =>\n\t\t\twithRequestIdInErrorBody(await gate(input), event.url.pathname)\n\t\t);\n\tif (isStaticAsset(event.url.pathname)) return run();\n\treturn requestTiming.timeRequest(\n\t\t{\n\t\t\tmethod: event.request.method,\n\t\t\troute: event.route.id ?? event.url.pathname,\n\t\t\tisDataRequest: event.isDataRequest\n\t\t},\n\t\tasync () => run()\n\t);\n};\n\nconst gate: import('@sveltejs/kit/hooks').Handle = async ({ event, resolve }) => {\n\tevent.locals.providers = providers;\n\n\t// Bound once per request; every downstream `locals.log` record inherits\n\t// these fields. `event.url.pathname`, never `.search` — query strings carry\n\t// share tokens, and a log record outlives the token's usefulness to an attacker.\n\tconst requestId = resolveRequestId(event.request.headers);\n\tevent.locals.requestId = requestId;\n\tevent.locals.log = getLogger().child({\n\t\trequestId,\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname\n\t});\n\n\tif (!headerAuthBootstrapWired) {\n\t\twireHeaderAuthBootstrap();\n\t\theaderAuthBootstrapWired = true;\n\t}\n\n\tif (!bootHealthKicked) {\n\t\tbootHealthKicked = true;\n\t\tvoid getBootHealth();\n\t\tstartRetentionJanitor({\n\t\t\tdata: providers.data,\n\t\t\tpolicy: resolveRetentionPolicy(env),\n\t\t\tlogger: getLogger()\n\t\t});\n\t\t// Reconciles a self-update that was in flight when this process came up\n\t\t// into the audit log. No-op when no pending-update state file exists —\n\t\t// see selfUpdate.server.ts for the full lifecycle.\n\t\tconst deploymentDir = findDeploymentDir(env);\n\t\tif (deploymentDir) {\n\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\tdeploymentDir,\n\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t});\n\t\t}\n\t}\n\n\tconst { pathname } = event.url;\n\n\t// SvelteKit's own check is off (vite.config.ts) because it can't exempt the\n\t// token endpoint or bearer requests; this is the same check with those exemptions.\n\tif (\n\t\t!dev &&\n\t\tisCrossSiteFormSubmission(event.request, {\n\t\t\texemptPaths: [OAUTH_TOKEN_PATH],\n\t\t\torigin: publicUrl(event.url).origin\n\t\t})\n\t) {\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(`Cross-site ${event.request.method} form submissions are forbidden`, {\n\t\t\t\tstatus: 403\n\t\t\t}),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\n\t// Static assets bypass every gate below — no auth, no first-run check.\n\tif (isStaticAsset(pathname)) {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// Probes answer before any gate runs — a fresh deployment with no users yet\n\t// is still live and ready, and the first-run 503 below would tell a load\n\t// balancer (or the post-update poller) the opposite.\n\tif (pathname === '/api/health' || pathname === '/api/health/ready') {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// A `selva_` key decides the request on its own: it never falls back to the\n\t// cookie, so a broken key can't quietly run as whoever is signed in.\n\t// `/mcp` carries a key but isn't under `/api/v1`, so the resolver would refuse it.\n\tconst tokenResult =\n\t\tpathname === MCP_PATH\n\t\t\t? ({ kind: 'none' } as const)\n\t\t\t: await resolveApiToken(event.request, {\n\t\t\t\t\tcodec: apiTokenCodec(),\n\t\t\t\t\tauth: providers.auth,\n\t\t\t\t\tdata: providers.data,\n\t\t\t\t\tflag,\n\t\t\t\t\tholderVerdicts,\n\t\t\t\t\tsignInMaxAgeMs,\n\t\t\t\t\tresolutionCache: apiTokenResolutions,\n\t\t\t\t\tlog: event.locals.log\n\t\t\t\t});\n\tif (tokenResult.kind === 'rejected') {\n\t\tconst { status, code, message } = tokenResult;\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (status === 401) headers['WWW-Authenticate'] = 'Bearer error=\"invalid_token\"';\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(JSON.stringify({ message, code }), { status, headers }),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\tif (tokenResult.kind === 'ok') {\n\t\tconst { user, ctx, token } = tokenResult;\n\t\tevent.locals.log = event.locals.log.child({ tokenId: token.id });\n\t\tevent.locals.user = user;\n\t\tevent.locals.ctx = ctx;\n\t\tevent.locals.profile =\n\t\t\t(await providers.data.userProfile.getProfile(SYSTEM_CONTEXT, user.id)) ??\n\t\t\temptyProfile(user.id);\n\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\tconst publicRoute = isPublicRoute(pathname);\n\t// All HTTP endpoints live under `/api/*` — distinguishes 401 JSON from a\n\t// 303 redirect.\n\tconst isJsonApiRoute = pathname.startsWith('/api/');\n\n\t// On first run (no users yet), redirect non-public traffic to /setup so a\n\t// fresh deployment lands on the bootstrap flow instead of a dead login\n\t// page. Public routes pass through unchanged.\n\tif (!publicRoute) {\n\t\tif (await isFirstRun()) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(JSON.stringify({ message: 'Setup required', code: 'SETUP_REQUIRED' }), {\n\t\t\t\t\t\tstatus: 503,\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t}),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\tredirect(303, '/setup');\n\t\t}\n\t}\n\n\t// Deny-by-default: any non-public, non-static path requires a valid session,\n\t// unless it carries a share token the route checks itself.\n\tconst needsAuth = !publicRoute;\n\tif (needsAuth) {\n\t\tlet token = event.cookies.get('admin_session') ?? '';\n\t\tlet session = await sessions.resolve(token);\n\n\t\t// When the access token expired but a refresh token is present (Supabase\n\t\t// OAuth flow), swap silently for a fresh pair and rotate the cookies.\n\t\t// Local/HMAC sessions never set a refresh cookie, so this is a no-op there.\n\t\tif (!session) {\n\t\t\tconst refreshToken = getRefreshToken(event.cookies);\n\t\t\tif (refreshToken && providers.auth.sessionRefresh) {\n\t\t\t\tconst refreshed = await refreshSession(refreshToken);\n\t\t\t\tif (refreshed) {\n\t\t\t\t\tsetSessionCookie(event.cookies, refreshed.sessionToken);\n\t\t\t\t\tsetRefreshCookie(event.cookies, refreshed.refreshToken);\n\t\t\t\t\ttoken = refreshed.sessionToken;\n\t\t\t\t\tsession = await sessions.resolve(token);\n\t\t\t\t} else {\n\t\t\t\t\t// Refresh failed — clear the stale cookie so the next request\n\t\t\t\t\t// goes through the login flow cleanly.\n\t\t\t\t\tclearRefreshCookie(event.cookies);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Forward-proxy fallback: providers that derive identity from trusted\n\t\t// upstream-proxy signals (Caddy forward_auth, oauth2-proxy, etc.) get a\n\t\t// chance to identify the request. See IProxyAuth for the trust contract.\n\t\tlet user = session?.user ?? null;\n\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\tif (!user && proxyAuth) {\n\t\t\tconst setupProven = hasSetupProof(event.cookies);\n\t\t\tuser = await identifyWithSetupProof(setupProven, () =>\n\t\t\t\tproxyAuth.identifyFromHeaders(event.request.headers)\n\t\t\t);\n\t\t\t// First-admin bootstrap for forward-auth deployments: OAuth and\n\t\t\t// email-link callbacks call `bootstrapUserSession` themselves, but the\n\t\t\t// proxy-auth path has no callback. Internally gated by `hasInstanceAdmin`\n\t\t\t// and a no-op once an admin exists, so safe on every authed request.\n\t\t\tif (user) await bootstrapUserSession(user, setupProven);\n\t\t}\n\n\t\tif (!user && carriesShareToken(event.request, event.url)) {\n\t\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t\t}\n\n\t\tif (!user) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmessage: 'Your session has expired. Sign in again to continue.',\n\t\t\t\t\t\t\tcode: 'UNAUTHORIZED'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\t// With the query: an OAuth authorize request is nothing without it.\n\t\t\tredirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);\n\t\t}\n\n\t\tattachSession(event, session ?? (await sessionFor(user, token)));\n\t} else {\n\t\t// Public page route (e.g. `/`): best-effort session attach. If a valid\n\t\t// session cookie is present, populate locals so the UI reflects authed\n\t\t// state (nav, user chip). Failure is silent — public pages keep\n\t\t// rendering for guests. Also applies to the self-gating files proxy,\n\t\t// which needs `locals.ctx` when a session is present so org/project\n\t\t// assets resolve, while still rendering guests' public branding.\n\t\tconst isPublicPage = PUBLIC_PAGE_ROUTES.has(pathname);\n\t\tconst wantsSessionAttach = isPublicPage || isSelfGatingApiRoute(pathname);\n\t\tconst token = wantsSessionAttach ? (event.cookies.get('admin_session') ?? '') : '';\n\t\tconst session = token ? await sessions.resolve(token) : null;\n\t\tlet user = session?.user ?? null;\n\t\tif (!user && wantsSessionAttach && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\n\n\t\t\tif (!user && pathname === '/login' && !proxyAuthLoginMissWarned) {\n\t\t\t\tproxyAuthLoginMissWarned = true;\n\t\t\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\t\t\tconst noHeaders = proxyAuth.hasNoIdentityHeaders(event.request.headers);\n\t\t\t\tconst configured = proxyAuth.configuredHeaderNames.join(', ');\n\t\t\t\tif (noHeaders) {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit and NONE of the configured identity headers arrived. The ' +\n\t\t\t\t\t\t\t'forward-auth proxy is not reaching this process, or is not forwarding the ' +\n\t\t\t\t\t\t\t'configured headers. See the @selvajs/header-auth-provider README ' +\n\t\t\t\t\t\t\t'\"Verification\" section.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit but the UPN header was missing or the user is not allowlisted. ' +\n\t\t\t\t\t\t\t'Some headers arrived but identification still failed — check that the UPN ' +\n\t\t\t\t\t\t\t'header is populated and that the user has been added to header-allowlist.json.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (user) attachSession(event, session ?? (await sessionFor(user, token)));\n\t}\n\n\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n};\n\n// ============================================================================\n// Response headers\n// ============================================================================\n//\n// Applied to every response — successful resolves and the 401/503\n// short-circuits above. The browser-hardening set (nosniff, Referrer-Policy,\n// Permissions-Policy, HSTS in production) lives in `@selvajs/server/http` —\n// see `applySecurityHeaders` there. Cache-control stays here: it encodes this\n// app's asset layout.\n//\n// Frame headers are the one route-dependent piece (`deniesFraming`).\n\nfunction applyResponseHeaders(response: Response, pathname: string, requestId: string): Response {\n\tapplySecurityHeaders(response, {\n\t\thsts: process.env.NODE_ENV === 'production',\n\t\tdenyFraming: deniesFraming(pathname)\n\t});\n\n\t// Echoed so a user reporting \"request X failed\" gives an operator the\n\t// exact key to grep logs with.\n\tresponse.headers.set(REQUEST_ID_HEADER, requestId);\n\n\t// Cache-control: hashed build assets are immutable; other static assets\n\t// get a short TTL.\n\tif (pathname.startsWith('/_app/')) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=31536000, immutable');\n\t} else if (pathname.startsWith('/api/v1/') && !response.headers.has('Cache-Control')) {\n\t\t// Authenticated JSON: no intermediary may keep a copy.\n\t\tresponse.headers.set('Cache-Control', 'private, no-store');\n\t} else if (\n\t\tpathname.startsWith('/favicon/') ||\n\t\tpathname === '/favicon.svg' ||\n\t\tpathname === '/robots.txt'\n\t) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=604800');\n\t}\n\n\treturn response;\n}\n\n/**\n * Copies the request id into an API error's JSON body, so a client that logs only the body still\n * has the id an operator greps for. The header alone is lost by most HTTP client error paths.\n */\nasync function withRequestIdInErrorBody(response: Response, pathname: string): Promise<Response> {\n\tif (response.status < 400 || !pathname.startsWith('/api/')) return response;\n\tif (!response.headers.get('Content-Type')?.includes('application/json')) return response;\n\tconst requestId = response.headers.get(REQUEST_ID_HEADER);\n\tif (!requestId) return response;\n\tlet body: unknown;\n\ttry {\n\t\tbody = await response.clone().json();\n\t} catch {\n\t\treturn response;\n\t}\n\tif (!body || typeof body !== 'object' || Array.isArray(body) || 'requestId' in body) {\n\t\treturn response;\n\t}\n\tconst headers = new Headers(response.headers);\n\theaders.delete('Content-Length');\n\treturn new Response(JSON.stringify({ ...body, requestId }), {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders\n\t});\n}\n\nexport const handleError: import('@sveltejs/kit/hooks').HandleServerError = ({\n\tkind,\n\terror,\n\tevent\n}) => {\n\t// `error(...)` bodies already carry `code`/`fields`, so they reach the client as thrown.\n\tif (kind === 'app') return error;\n\tif (kind !== 'unknown') {\n\t\treturn error.status === 404 ? { message: 'Page not found.', code: 'NOT_FOUND' } : error;\n\t}\n\t// Backstop only. `ApiError` reaching here means a page load called a guard\n\t// without going through `asHttpError()`.\n\tif (isApiError(error)) {\n\t\treturn {\n\t\t\tstatus: error.status,\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tfields: error.fields,\n\t\t\tdetails: error.details\n\t\t};\n\t}\n\t// SvelteKit's default logging drops `cause`, which is where provider\n\t// adapters tend to stash the real reason (Supabase network error, fs\n\t// EACCES, etc.) — kept as a separate field so the message still groups\n\t// cleanly while the stack stays searchable.\n\t//\n\t// `locals.log` already carries requestId/method/route, but handleError can\n\t// fire before `handle` populates locals (a throw in an earlier hook), so\n\t// fall back to the root logger and re-state the fields.\n\tconst log =\n\t\tevent.locals.log ??\n\t\tgetLogger().child({ method: event.request.method, route: event.url.pathname });\n\tlog.error('Unhandled error', {\n\t\tcomponent: 'handleError',\n\t\terr: renderThrown(error),\n\t\tcause: error instanceof Error && error.cause ? String(error.cause) : undefined\n\t});\n\t// Only reached for genuinely unexpected errors — intentional HTTP outcomes\n\t// (incl. the compute route's `apiError(500)` on a failed solve) are\n\t// `HttpError`s handled above. No-op unless SENTRY_DSN is configured.\n\tgetErrorReporter().capture(error, {\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname,\n\t\tuserId: event.locals.ctx?.userId || undefined,\n\t\torgId: event.locals.ctx?.actingOrgId\n\t});\n\treturn { message: 'An unexpected error occurred.', code: 'INTERNAL' };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,WAA6C;CAClD,CAAC,aAAa,IAAI;CAClB,CAAC,aAAa,MAAM;CACpB,CAAC,gBAAgB,SAAS;AAC3B;AAEA,SAAgB,iBAAiB,KAAuD;CACvF,MAAM,UAAU,SAAS,MAAM,CAAC,YAAY,IAAI,SAAS,WAAW,MAAM,CAAC;CAC3E,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,CAAC,QAAQ,IAAI,SAAS,MAAM,IAAI,SAAS,MAAM,QAAQ,EAAE,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG;CACjF,OAAO;EAAE,KAAK,QAAQ;EAAI,QAAQ,GAAG,QAAQ,GAAG,GAAG,UAAU,QAAQ,OAAO,WAAW;CAAQ;AAChG;;;;;;;;;;;;;;;;;;;;;;;ACqBA,SAAgB,qBAAqB,UAAoB,MAAuC;CAC/F,SAAS,QAAQ,IAAI,0BAA0B,SAAS;CACxD,SAAS,QAAQ,IAAI,mBAAmB,iCAAiC;CACzE,SAAS,QAAQ,IAChB,sBACA,+GACD;CACA,IAAI,KAAK,MACR,SAAS,QAAQ,IAAI,6BAA6B,qCAAqC;CAExF,IAAI,KA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,OAAO,OACb,UAAU,CAAC,CAAC,MAAM;EAAE,QAAQ,MAAM,QAAQ;EAAQ,OAAO,MAAM,IAAI;CAAS,CAAC,EAAA,CAC1E,MAAM,mBAAmB;EAC5B,WAAW;EACX,KAAK,aAAa,KAAK;EACvB,OAAO,iBAAiB,SAAS,MAAM,QAAQ,OAAO,MAAM,KAAK,IAAI,KAAA;CACtE,CAAC;CAID,iBAAiB,CAAC,CAAC,QAAQ,OAAO;EACjC,QAAQ,MAAM,QAAQ;EACtB,OAAO,MAAM,IAAI;EACjB,QAAQ,MAAM,OAAO,KAAK,UAAU,KAAA;EACpC,OAAO,MAAM,OAAO,KAAK;CAC1B,CAAC;CACD,OAAO;EAAE,SAAS;EAAiC,MAAM;CAAW;AACrE"}
|
|
@@ -11,15 +11,10 @@ var load = async ({ locals }) => {
|
|
|
11
11
|
let rows = [];
|
|
12
12
|
try {
|
|
13
13
|
const page = await orgs.listOrgs(SYSTEM_CONTEXT, { limit: 200 });
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} catch {}
|
|
19
|
-
return {
|
|
20
|
-
...org,
|
|
21
|
-
memberCount
|
|
22
|
-
};
|
|
14
|
+
const counts = await orgs.countOrgMembers(SYSTEM_CONTEXT, page.items.map((org) => org.id)).catch(() => /* @__PURE__ */ new Map());
|
|
15
|
+
rows = page.items.map((org) => ({
|
|
16
|
+
...org,
|
|
17
|
+
memberCount: counts.get(org.id) ?? 0
|
|
23
18
|
}));
|
|
24
19
|
} catch {}
|
|
25
20
|
return { orgs: rows };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../src/routes/admin/organizations/+page.server.ts"],"sourcesContent":["import { redirect } from '@sveltejs/kit';\nimport type { PageServerLoad } from './$types';\nimport type { Organization } from '@selvajs/platform';\nimport { hasPermission, SYSTEM_CONTEXT } from '@selvajs/platform';\nimport { getOrganizationProvider, getTenancy } from '#lib/server/providers.server.js';\n\nexport interface OrgRow extends Organization {\n\tmemberCount: number;\n}\n\nexport const load: PageServerLoad = async ({ locals }) => {\n\tconst ctx = locals.ctx;\n\tif (!ctx) redirect(303, '/login');\n\tif (!hasPermission(ctx, 'instance_admin')) redirect(303, '/admin');\n\tif (getTenancy() === 'single') redirect(303, '/admin');\n\n\tconst orgs = getOrganizationProvider();\n\n\tlet rows: OrgRow[] = [];\n\ttry {\n\t\tconst page = await orgs.listOrgs(SYSTEM_CONTEXT, { limit: 200 });\n\t\
|
|
1
|
+
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../src/routes/admin/organizations/+page.server.ts"],"sourcesContent":["import { redirect } from '@sveltejs/kit';\nimport type { PageServerLoad } from './$types';\nimport type { Organization } from '@selvajs/platform';\nimport { hasPermission, SYSTEM_CONTEXT } from '@selvajs/platform';\nimport { getOrganizationProvider, getTenancy } from '#lib/server/providers.server.js';\n\nexport interface OrgRow extends Organization {\n\tmemberCount: number;\n}\n\nexport const load: PageServerLoad = async ({ locals }) => {\n\tconst ctx = locals.ctx;\n\tif (!ctx) redirect(303, '/login');\n\tif (!hasPermission(ctx, 'instance_admin')) redirect(303, '/admin');\n\tif (getTenancy() === 'single') redirect(303, '/admin');\n\n\tconst orgs = getOrganizationProvider();\n\n\tlet rows: OrgRow[] = [];\n\ttry {\n\t\tconst page = await orgs.listOrgs(SYSTEM_CONTEXT, { limit: 200 });\n\t\tconst counts = await orgs\n\t\t\t.countOrgMembers(\n\t\t\t\tSYSTEM_CONTEXT,\n\t\t\t\tpage.items.map((org) => org.id)\n\t\t\t)\n\t\t\t.catch(() => new Map<string, number>());\n\t\trows = page.items.map((org) => ({ ...org, memberCount: counts.get(org.id) ?? 0 }));\n\t} catch {\n\t\t// listOrgs unavailable — show empty\n\t}\n\n\treturn { orgs: rows };\n};\n"],"mappings":";;;;AAUA,IAAa,OAAuB,OAAO,EAAE,aAAa;CACzD,MAAM,MAAM,OAAO;CACnB,IAAI,CAAC,KAAK,SAAS,KAAK,QAAQ;CAChC,IAAI,CAAC,cAAc,KAAK,gBAAgB,GAAG,SAAS,KAAK,QAAQ;CACjE,IAAI,WAAW,MAAM,UAAU,SAAS,KAAK,QAAQ;CAErD,MAAM,OAAO,wBAAwB;CAErC,IAAI,OAAiB,CAAC;CACtB,IAAI;EACH,MAAM,OAAO,MAAM,KAAK,SAAS,gBAAgB,EAAE,OAAO,IAAI,CAAC;EAC/D,MAAM,SAAS,MAAM,KACnB,gBACA,gBACA,KAAK,MAAM,KAAK,QAAQ,IAAI,EAAE,CAC/B,CAAC,CACA,4BAAY,IAAI,IAAoB,CAAC;EACvC,OAAO,KAAK,MAAM,KAAK,SAAS;GAAE,GAAG;GAAK,aAAa,OAAO,IAAI,IAAI,EAAE,KAAK;EAAE,EAAE;CAClF,QAAQ,CAER;CAEA,OAAO,EAAE,MAAM,KAAK;AACrB"}
|