@aglyn/aglyn 1.23.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/lib/app-utils/activity-presenter.d.ts +11 -0
- package/src/lib/app-utils/activity-presenter.js +9 -0
- package/src/lib/app-utils/activity-presenter.js.map +1 -1
- package/src/lib/app-utils/activity-search.d.ts +1 -0
- package/src/lib/app-utils/activity-search.js +1 -0
- package/src/lib/app-utils/activity-search.js.map +1 -1
- package/src/lib/app-utils/agent-api-catalog.d.ts +18 -0
- package/src/lib/app-utils/agent-api-catalog.js +8 -1
- package/src/lib/app-utils/agent-api-catalog.js.map +1 -1
- package/src/lib/app-utils/binding-token-catalog.d.ts +15 -0
- package/src/lib/app-utils/binding-token-catalog.js +16 -0
- package/src/lib/app-utils/binding-token-catalog.js.map +1 -1
- package/src/lib/app-utils/connector-discovery.d.ts +80 -0
- package/src/lib/app-utils/connector-discovery.js +107 -0
- package/src/lib/app-utils/connector-discovery.js.map +1 -0
- package/src/lib/app-utils/docs-help-sections.generated.js +4 -0
- package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +10 -4
- package/src/lib/app-utils/docs-help.generated.js +57 -3
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +129 -3
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/entity-picker-context.d.ts +6 -0
- package/src/lib/app-utils/entity-picker-context.js.map +1 -1
- package/src/lib/app-utils/expand-repeatables.js +25 -2
- package/src/lib/app-utils/expand-repeatables.js.map +1 -1
- package/src/lib/app-utils/native-app-association.d.ts +4 -2
- package/src/lib/app-utils/native-app-association.js +5 -2
- package/src/lib/app-utils/native-app-association.js.map +1 -1
- package/src/lib/app-utils/organizations.js +4 -2
- package/src/lib/app-utils/organizations.js.map +1 -1
- package/src/lib/app-utils/plugin-release-flags.generated.js +2 -2
- package/src/lib/app-utils/plugin-release-flags.generated.js.map +1 -1
- package/src/lib/plugin-manager/feature-plugins.d.ts +22 -0
- package/src/lib/plugin-manager/feature-plugins.js +9 -0
- package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
- package/src/lib/plugin-manager/plugin-contact-capture.d.ts +2 -0
- package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
|
@@ -9,6 +9,12 @@ export interface EntityOption {
|
|
|
9
9
|
* name rather than the id still matches by the name.
|
|
10
10
|
*/
|
|
11
11
|
name?: string;
|
|
12
|
+
/**
|
|
13
|
+
* For an entity's FIELD (`entityFields`), the named type it holds where it
|
|
14
|
+
* has one: `icon` for a record's icon (AGL-4190), which only an Icon
|
|
15
|
+
* picker may bind.
|
|
16
|
+
*/
|
|
17
|
+
customType?: string;
|
|
12
18
|
}
|
|
13
19
|
/**
|
|
14
20
|
* Edit-time option lists for id-based entity pickers in component
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/entity-picker-context.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Same placement rationale as screen-link-context.ts: lives in\n// @aglyn/aglyn without a 'use client' banner so canvas-rendering surfaces\n// share one module graph.\nimport { createContext } from 'react'\n\nexport interface EntityOption {\n /** Stable document id — the persisted reference (AGL-343/344). */\n id: string\n /** Current display name, resolved at edit time. */\n label: string\n /**\n * The entity's own name, where `label` says more than it (AGL-4047): two\n * of one name are labelled apart by their owner, and a node that stored the\n * name rather than the id still matches by the name.\n */\n name?: string\n}\n\n/**\n * Edit-time option lists for id-based entity pickers in component\n * attributes — every kind a plugin declares (a site's products, its forms,\n * the organization's datasets…). Names are display-only; nodes persist the id, so renames never break references —\n * the same contract as {@link ScreenLinkContext}. Provided by the\n * console's besigner/preview surfaces; absent on the tenant (the tenant\n * only resolves ids, never lists them).\n */\n/**\n * A kind of entity a picker lists, as the plugin that keeps it declares it\n * (`plugin-manager/plugin-entity-pickers`): `products`, `forms`, `datasets`…\n * Open, because the kinds are the plugins' to add (AGL-3080).\n */\nexport type EntityPickerKind = string\n\n/**\n * How much an empty list is worth believing.\n *\n * Every one of these renders as a dropdown with no entries, and an author\n * looking at four identical empty dropdowns cannot tell \"this site has no\n * forms yet\" from \"the read failed\" from \"this editor never lists forms at\n * all\". Only the first of those is a fact about their site; the other two\n * are the picker being broken, and a picker that cannot say which it is\n * sends the author looking for a form they already made.\n *\n * - `unavailable` — no provider is mounted, so nothing on this surface can\n * list entities. The tenant, and any editor outside a host.\n * - `loading` — a read is open or about to be, and no answer has arrived.\n * Also the state of a list nothing has asked for yet: demand is declared\n * on the same commit that would display it, so \"not asked\" and \"asked,\n * unanswered\" are the same beat.\n * - `ready` — the read settled. An empty list here IS the site's answer.\n * - `error` — the read failed. Empty means nothing.\n */\nexport type EntityListState = 'unavailable' | 'loading' | 'ready' | 'error'\n\n/**\n * How many documents a picker BROWSES.\n *\n * A picker is not a catalog viewer. It is a dropdown on a besigner surface\n * where the author is placing one element, and no table in the console offers\n * a page past `TABLE_PAGE_SIZE_OPTIONS` — a dropdown is the smaller surface of\n * the two, not the larger.\n *\n * The middle of that range rather than its floor: a table has a pager under it\n * and a dropdown does not, so the page a reader cannot advance is worth more\n * rows than the one they can.\n *\n * What makes this size SAFE is that browsing is the only job it does. A stored\n * value is named by {@link EntityPickerContextValue.resolve} — one keyed read\n * for the one document, exact at any catalog size — so nothing here has to be\n * wide enough to contain whatever an author picked last month. A window that\n * carried both jobs would have to be, and would still render a bound element\n * as unbound past its own width; widening this cannot fix that, only make it\n * rarer and more expensive.\n */\nexport const ENTITY_PICKER_BROWSE_LIMIT = 25\n\n/**\n * How many documents a server-side name search may return.\n *\n * The same size as the browse window, for the same reason: a reader who has\n * typed a query and still faces 25 rows narrows it further rather than\n * scrolling. Only the kinds in {@link EntityPickerContextValue.searchable}\n * spend this at all.\n */\nexport const ENTITY_PICKER_SEARCH_LIMIT = 25\n\nexport interface EntityPickerContextValue {\n /**\n * Each kind's browse list, id-first: the site's products for a\n * `PRODUCT_SELECT`, its form entities for a `FORM_SELECT`, and every other\n * kind a plugin declares, keyed by the kind.\n */\n options?: Readonly<Partial<Record<EntityPickerKind, EntityOption[]>>>\n /**\n * The fields an entity's documents declare, keyed by kind and then by\n * entity id, in the order the entity declares them: id = the stable field\n * id a node persists, label = its current display name (AGL-556).\n *\n * Only kinds whose documents carry a field model appear. Two surfaces read\n * it: a field picker that maps a value onto one of an entity's fields (a\n * form field's \"Maps to schema field\"), and the insert-token menu inside a\n * repeat, which offers `{{item.<field>}}` for each field of the entity the\n * repeat names (see `RepeatSource.entityKind`).\n */\n entityFields?: Partial<\n Record<EntityPickerKind, Readonly<Record<string, EntityOption[]>>>\n >\n /**\n * Declare that a picker of this kind is on screen (AGL-703).\n *\n * The provider reads these lists from Firestore, and it used to read ALL of\n * them the moment the besigner opened — up to 300 products, 200 catalog\n * collections, 200 categories and 200 datasets, on a site with a real\n * catalog, for pickers most editing sessions never open. Nothing about\n * moving a heading needs the product list.\n *\n * So the lists are demand-driven now, and the demand signal is the thing\n * that would DISPLAY one: a selected node whose schema declares a\n * `PRODUCT_SELECT`, a repeat bound to a dataset. Call this when that is\n * true and read the list on the render after; until then the list is\n * absent, exactly as it is for the beat before any listener syncs.\n *\n * Optional, and absent on the tenant — which resolves ids and never lists\n * them, so nothing there has a picker to ask for.\n */\n request?: (kind: EntityPickerKind) => void\n /**\n * Per-kind read state, so a picker can say WHY it has nothing to offer.\n * A kind the provider omits reads as `loading`; see {@link entityListState}.\n */\n status?: Partial<Record<EntityPickerKind, EntityListState>>\n /**\n * The browse window came back FULL for this kind, so the list above is a\n * page of the site's catalog and not the whole of it.\n *\n * Measured with a probe — the read asks for one document past\n * {@link ENTITY_PICKER_BROWSE_LIMIT} and the extra one is never offered —\n * so this is a fact about the collection rather than a guess from the\n * window being exactly full.\n *\n * A picker owes the reader this sentence for the same reason the inbox's\n * form filter does: \"not in the picker\" and \"does not exist\" are the same\n * empty dropdown, and only one of them is a fact about their site.\n */\n truncated?: Partial<Record<EntityPickerKind, boolean>>\n /**\n * This kind's documents carry the name-search keys, so a typed query\n * reaches the WHOLE collection rather than only the browse window.\n *\n * True for a kind its declaration marks `searchable`, whose documents carry\n * `nameTokens`/`nameLower` from the owner's own write path —\n * `hosts/{host}/resources` deliberately does not stamp them. A picker for a\n * kind that is absent here must say its search covers the window only —\n * claiming otherwise would let an unfound entity read as a nonexistent one.\n */\n searchable?: Partial<Record<EntityPickerKind, boolean>>\n /**\n * Narrow this kind's offered list to what somebody typed.\n *\n * Matching is the provider's, not the dropdown's: it is the only side that\n * can merge the window's own matches with the ones a server query found\n * past it, and it uses `scoreMatch` so a query matches a word ANYWHERE in a\n * name — the same rule the switchers and global search follow.\n *\n * Passing an empty string restores the browse window.\n */\n search?: (kind: EntityPickerKind, text: string) => void\n /**\n * Resolve ONE stored id to its current name, whatever the browse window\n * holds.\n *\n * Deliberately NOT a job for the browse list, though a bulk read could do\n * both. Sharing one read makes the list's width the limit on which stored\n * values can be named, and past that width a picker renders a bound element\n * as UNBOUND rather than as its label — an empty control on an element that\n * is set, which an author repairs by picking again. That is how a correct\n * reference gets replaced with a different one.\n *\n * One keyed `getDoc` for one document instead: exact at any catalog size,\n * and asked for only when a node actually carries a value. Results land in\n * {@link resolved} and are never re-read.\n */\n resolve?: (kind: EntityPickerKind, id: string) => void\n /**\n * What {@link resolve} found, keyed by kind and then by id.\n *\n * Three states, and the picker renders a different label for each: an\n * `EntityOption` is the resolved name, `null` is a settled read that found\n * NO such document, and an absent key is a resolution still in flight.\n * Absent must never render as missing — a picker that flashed \"unavailable\"\n * over every live reference for the beat before its read landed would teach\n * authors to ignore the one warning that matters.\n */\n resolved?: Partial<\n Record<EntityPickerKind, Readonly<Record<string, EntityOption | null>>>\n >\n}\n\n/**\n * What the picker for `kind` should believe about its own emptiness.\n *\n * `request` is the \"a provider is mounted\" signal — it is the one member the\n * contract already says is absent wherever nothing lists entities — so a\n * surface with no provider resolves to `unavailable` rather than passing an\n * empty list off as the site's answer.\n */\nexport function entityListState(\n context: EntityPickerContextValue | undefined,\n kind: EntityPickerKind,\n): EntityListState {\n if (!context?.request) return 'unavailable'\n return context.status?.[kind] ?? 'loading'\n}\n\n/**\n * The id whose label a picker still needs a keyed read to learn, if any.\n *\n * Part of the contract rather than of one screen, because two surfaces ask\n * it — the attributes panel about a node's picker value, and the insert-token\n * menu about the dataset a repeat is bound to — and an answer that differed\n * between them would be a second keyed read for a document one of them\n * already had.\n *\n * Four cases resolve to \"ask nobody\", and each is a read not spent: there is\n * no value; the browse window already carries it, which is the common case on\n * a small site; a resolution has already answered, including the answer that\n * the document is gone; or the browse read has not settled, so the window may\n * be about to supply it for free.\n *\n * The last is the one worth stating. Asking while the listener is still\n * loading would spend a keyed read on nearly every picker on every site,\n * which is the cost splitting these two jobs exists to remove rather than to\n * move.\n */\nexport function entityValueNeedsResolution(\n context: EntityPickerContextValue | undefined,\n kind: EntityPickerKind,\n value: unknown,\n): string | undefined {\n const id = typeof value === 'string' ? value.trim() : ''\n if (!id || !context?.resolve) return undefined\n if ((context.options?.[kind] ?? []).some((entity) => entity.id === id)) return undefined\n if (id in (context.resolved?.[kind] ?? {})) return undefined\n if (entityListState(context, kind) !== 'ready') return undefined\n return id\n}\n\nexport const EntityPickerContext = createContext<EntityPickerContextValue>({})\nEntityPickerContext.displayName = 'EntityPickerContext'\n"],"names":["createContext","ENTITY_PICKER_BROWSE_LIMIT","ENTITY_PICKER_SEARCH_LIMIT","entityListState","context","kind","request","status","entityValueNeedsResolution","value","id","trim","resolve","undefined","options","some","entity","resolved","EntityPickerContext","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD,+DAA+D;AAC/D,0EAA0E;AAC1E,0BAA0B;AAC1B,SAASA,aAAa,QAAQ,QAAO;AAmDrC;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,MAAMC,6BAA6B,GAAE;AAE5C;;;;;;;CAOC,GACD,OAAO,MAAMC,6BAA6B,GAAE;AAkH5C;;;;;;;CAOC,GACD,OAAO,SAASC,gBACdC,OAA6C,EAC7CC,IAAsB;;QAGfD;IADP,IAAI,EAACA,2BAAAA,QAASE,OAAO,GAAE,OAAO;IAC9B,gBAAOF,kBAAAA,QAAQG,MAAM,qBAAdH,eAAgB,CAACC,KAAK,mBAAI;AACnC;AAEA;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASG,2BACdJ,OAA6C,EAC7CC,IAAsB,EACtBI,KAAc;;QAITL,kBACMA;IAHX,MAAMM,KAAK,OAAOD,UAAU,WAAWA,MAAME,IAAI,KAAK;IACtD,IAAI,CAACD,MAAM,EAACN,2BAAAA,QAASQ,OAAO,GAAE,OAAOC;IACrC,IAAI,UAACT,mBAAAA,QAAQU,OAAO,qBAAfV,gBAAiB,CAACC,KAAK,mBAAI,EAAE,EAAEU,IAAI,CAAC,CAACC,SAAWA,OAAON,EAAE,KAAKA,KAAK,OAAOG;IAC/E,IAAIH,iBAAON,oBAAAA,QAAQa,QAAQ,qBAAhBb,iBAAkB,CAACC,KAAK,oBAAI,CAAC,IAAI,OAAOQ;IACnD,IAAIV,gBAAgBC,SAASC,UAAU,SAAS,OAAOQ;IACvD,OAAOH;AACT;AAEA,OAAO,MAAMQ,sBAAsBlB,cAAwC,CAAC,GAAE;AAC9EkB,oBAAoBC,WAAW,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/entity-picker-context.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Same placement rationale as screen-link-context.ts: lives in\n// @aglyn/aglyn without a 'use client' banner so canvas-rendering surfaces\n// share one module graph.\nimport { createContext } from 'react'\n\nexport interface EntityOption {\n /** Stable document id — the persisted reference (AGL-343/344). */\n id: string\n /** Current display name, resolved at edit time. */\n label: string\n /**\n * The entity's own name, where `label` says more than it (AGL-4047): two\n * of one name are labelled apart by their owner, and a node that stored the\n * name rather than the id still matches by the name.\n */\n name?: string\n /**\n * For an entity's FIELD (`entityFields`), the named type it holds where it\n * has one: `icon` for a record's icon (AGL-4190), which only an Icon\n * picker may bind.\n */\n customType?: string\n}\n\n/**\n * Edit-time option lists for id-based entity pickers in component\n * attributes — every kind a plugin declares (a site's products, its forms,\n * the organization's datasets…). Names are display-only; nodes persist the id, so renames never break references —\n * the same contract as {@link ScreenLinkContext}. Provided by the\n * console's besigner/preview surfaces; absent on the tenant (the tenant\n * only resolves ids, never lists them).\n */\n/**\n * A kind of entity a picker lists, as the plugin that keeps it declares it\n * (`plugin-manager/plugin-entity-pickers`): `products`, `forms`, `datasets`…\n * Open, because the kinds are the plugins' to add (AGL-3080).\n */\nexport type EntityPickerKind = string\n\n/**\n * How much an empty list is worth believing.\n *\n * Every one of these renders as a dropdown with no entries, and an author\n * looking at four identical empty dropdowns cannot tell \"this site has no\n * forms yet\" from \"the read failed\" from \"this editor never lists forms at\n * all\". Only the first of those is a fact about their site; the other two\n * are the picker being broken, and a picker that cannot say which it is\n * sends the author looking for a form they already made.\n *\n * - `unavailable` — no provider is mounted, so nothing on this surface can\n * list entities. The tenant, and any editor outside a host.\n * - `loading` — a read is open or about to be, and no answer has arrived.\n * Also the state of a list nothing has asked for yet: demand is declared\n * on the same commit that would display it, so \"not asked\" and \"asked,\n * unanswered\" are the same beat.\n * - `ready` — the read settled. An empty list here IS the site's answer.\n * - `error` — the read failed. Empty means nothing.\n */\nexport type EntityListState = 'unavailable' | 'loading' | 'ready' | 'error'\n\n/**\n * How many documents a picker BROWSES.\n *\n * A picker is not a catalog viewer. It is a dropdown on a besigner surface\n * where the author is placing one element, and no table in the console offers\n * a page past `TABLE_PAGE_SIZE_OPTIONS` — a dropdown is the smaller surface of\n * the two, not the larger.\n *\n * The middle of that range rather than its floor: a table has a pager under it\n * and a dropdown does not, so the page a reader cannot advance is worth more\n * rows than the one they can.\n *\n * What makes this size SAFE is that browsing is the only job it does. A stored\n * value is named by {@link EntityPickerContextValue.resolve} — one keyed read\n * for the one document, exact at any catalog size — so nothing here has to be\n * wide enough to contain whatever an author picked last month. A window that\n * carried both jobs would have to be, and would still render a bound element\n * as unbound past its own width; widening this cannot fix that, only make it\n * rarer and more expensive.\n */\nexport const ENTITY_PICKER_BROWSE_LIMIT = 25\n\n/**\n * How many documents a server-side name search may return.\n *\n * The same size as the browse window, for the same reason: a reader who has\n * typed a query and still faces 25 rows narrows it further rather than\n * scrolling. Only the kinds in {@link EntityPickerContextValue.searchable}\n * spend this at all.\n */\nexport const ENTITY_PICKER_SEARCH_LIMIT = 25\n\nexport interface EntityPickerContextValue {\n /**\n * Each kind's browse list, id-first: the site's products for a\n * `PRODUCT_SELECT`, its form entities for a `FORM_SELECT`, and every other\n * kind a plugin declares, keyed by the kind.\n */\n options?: Readonly<Partial<Record<EntityPickerKind, EntityOption[]>>>\n /**\n * The fields an entity's documents declare, keyed by kind and then by\n * entity id, in the order the entity declares them: id = the stable field\n * id a node persists, label = its current display name (AGL-556).\n *\n * Only kinds whose documents carry a field model appear. Two surfaces read\n * it: a field picker that maps a value onto one of an entity's fields (a\n * form field's \"Maps to schema field\"), and the insert-token menu inside a\n * repeat, which offers `{{item.<field>}}` for each field of the entity the\n * repeat names (see `RepeatSource.entityKind`).\n */\n entityFields?: Partial<\n Record<EntityPickerKind, Readonly<Record<string, EntityOption[]>>>\n >\n /**\n * Declare that a picker of this kind is on screen (AGL-703).\n *\n * The provider reads these lists from Firestore, and it used to read ALL of\n * them the moment the besigner opened — up to 300 products, 200 catalog\n * collections, 200 categories and 200 datasets, on a site with a real\n * catalog, for pickers most editing sessions never open. Nothing about\n * moving a heading needs the product list.\n *\n * So the lists are demand-driven now, and the demand signal is the thing\n * that would DISPLAY one: a selected node whose schema declares a\n * `PRODUCT_SELECT`, a repeat bound to a dataset. Call this when that is\n * true and read the list on the render after; until then the list is\n * absent, exactly as it is for the beat before any listener syncs.\n *\n * Optional, and absent on the tenant — which resolves ids and never lists\n * them, so nothing there has a picker to ask for.\n */\n request?: (kind: EntityPickerKind) => void\n /**\n * Per-kind read state, so a picker can say WHY it has nothing to offer.\n * A kind the provider omits reads as `loading`; see {@link entityListState}.\n */\n status?: Partial<Record<EntityPickerKind, EntityListState>>\n /**\n * The browse window came back FULL for this kind, so the list above is a\n * page of the site's catalog and not the whole of it.\n *\n * Measured with a probe — the read asks for one document past\n * {@link ENTITY_PICKER_BROWSE_LIMIT} and the extra one is never offered —\n * so this is a fact about the collection rather than a guess from the\n * window being exactly full.\n *\n * A picker owes the reader this sentence for the same reason the inbox's\n * form filter does: \"not in the picker\" and \"does not exist\" are the same\n * empty dropdown, and only one of them is a fact about their site.\n */\n truncated?: Partial<Record<EntityPickerKind, boolean>>\n /**\n * This kind's documents carry the name-search keys, so a typed query\n * reaches the WHOLE collection rather than only the browse window.\n *\n * True for a kind its declaration marks `searchable`, whose documents carry\n * `nameTokens`/`nameLower` from the owner's own write path —\n * `hosts/{host}/resources` deliberately does not stamp them. A picker for a\n * kind that is absent here must say its search covers the window only —\n * claiming otherwise would let an unfound entity read as a nonexistent one.\n */\n searchable?: Partial<Record<EntityPickerKind, boolean>>\n /**\n * Narrow this kind's offered list to what somebody typed.\n *\n * Matching is the provider's, not the dropdown's: it is the only side that\n * can merge the window's own matches with the ones a server query found\n * past it, and it uses `scoreMatch` so a query matches a word ANYWHERE in a\n * name — the same rule the switchers and global search follow.\n *\n * Passing an empty string restores the browse window.\n */\n search?: (kind: EntityPickerKind, text: string) => void\n /**\n * Resolve ONE stored id to its current name, whatever the browse window\n * holds.\n *\n * Deliberately NOT a job for the browse list, though a bulk read could do\n * both. Sharing one read makes the list's width the limit on which stored\n * values can be named, and past that width a picker renders a bound element\n * as UNBOUND rather than as its label — an empty control on an element that\n * is set, which an author repairs by picking again. That is how a correct\n * reference gets replaced with a different one.\n *\n * One keyed `getDoc` for one document instead: exact at any catalog size,\n * and asked for only when a node actually carries a value. Results land in\n * {@link resolved} and are never re-read.\n */\n resolve?: (kind: EntityPickerKind, id: string) => void\n /**\n * What {@link resolve} found, keyed by kind and then by id.\n *\n * Three states, and the picker renders a different label for each: an\n * `EntityOption` is the resolved name, `null` is a settled read that found\n * NO such document, and an absent key is a resolution still in flight.\n * Absent must never render as missing — a picker that flashed \"unavailable\"\n * over every live reference for the beat before its read landed would teach\n * authors to ignore the one warning that matters.\n */\n resolved?: Partial<\n Record<EntityPickerKind, Readonly<Record<string, EntityOption | null>>>\n >\n}\n\n/**\n * What the picker for `kind` should believe about its own emptiness.\n *\n * `request` is the \"a provider is mounted\" signal — it is the one member the\n * contract already says is absent wherever nothing lists entities — so a\n * surface with no provider resolves to `unavailable` rather than passing an\n * empty list off as the site's answer.\n */\nexport function entityListState(\n context: EntityPickerContextValue | undefined,\n kind: EntityPickerKind,\n): EntityListState {\n if (!context?.request) return 'unavailable'\n return context.status?.[kind] ?? 'loading'\n}\n\n/**\n * The id whose label a picker still needs a keyed read to learn, if any.\n *\n * Part of the contract rather than of one screen, because two surfaces ask\n * it — the attributes panel about a node's picker value, and the insert-token\n * menu about the dataset a repeat is bound to — and an answer that differed\n * between them would be a second keyed read for a document one of them\n * already had.\n *\n * Four cases resolve to \"ask nobody\", and each is a read not spent: there is\n * no value; the browse window already carries it, which is the common case on\n * a small site; a resolution has already answered, including the answer that\n * the document is gone; or the browse read has not settled, so the window may\n * be about to supply it for free.\n *\n * The last is the one worth stating. Asking while the listener is still\n * loading would spend a keyed read on nearly every picker on every site,\n * which is the cost splitting these two jobs exists to remove rather than to\n * move.\n */\nexport function entityValueNeedsResolution(\n context: EntityPickerContextValue | undefined,\n kind: EntityPickerKind,\n value: unknown,\n): string | undefined {\n const id = typeof value === 'string' ? value.trim() : ''\n if (!id || !context?.resolve) return undefined\n if ((context.options?.[kind] ?? []).some((entity) => entity.id === id)) return undefined\n if (id in (context.resolved?.[kind] ?? {})) return undefined\n if (entityListState(context, kind) !== 'ready') return undefined\n return id\n}\n\nexport const EntityPickerContext = createContext<EntityPickerContextValue>({})\nEntityPickerContext.displayName = 'EntityPickerContext'\n"],"names":["createContext","ENTITY_PICKER_BROWSE_LIMIT","ENTITY_PICKER_SEARCH_LIMIT","entityListState","context","kind","request","status","entityValueNeedsResolution","value","id","trim","resolve","undefined","options","some","entity","resolved","EntityPickerContext","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD,+DAA+D;AAC/D,0EAA0E;AAC1E,0BAA0B;AAC1B,SAASA,aAAa,QAAQ,QAAO;AAyDrC;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,MAAMC,6BAA6B,GAAE;AAE5C;;;;;;;CAOC,GACD,OAAO,MAAMC,6BAA6B,GAAE;AAkH5C;;;;;;;CAOC,GACD,OAAO,SAASC,gBACdC,OAA6C,EAC7CC,IAAsB;;QAGfD;IADP,IAAI,EAACA,2BAAAA,QAASE,OAAO,GAAE,OAAO;IAC9B,gBAAOF,kBAAAA,QAAQG,MAAM,qBAAdH,eAAgB,CAACC,KAAK,mBAAI;AACnC;AAEA;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,SAASG,2BACdJ,OAA6C,EAC7CC,IAAsB,EACtBI,KAAc;;QAITL,kBACMA;IAHX,MAAMM,KAAK,OAAOD,UAAU,WAAWA,MAAME,IAAI,KAAK;IACtD,IAAI,CAACD,MAAM,EAACN,2BAAAA,QAASQ,OAAO,GAAE,OAAOC;IACrC,IAAI,UAACT,mBAAAA,QAAQU,OAAO,qBAAfV,gBAAiB,CAACC,KAAK,mBAAI,EAAE,EAAEU,IAAI,CAAC,CAACC,SAAWA,OAAON,EAAE,KAAKA,KAAK,OAAOG;IAC/E,IAAIH,iBAAON,oBAAAA,QAAQa,QAAQ,qBAAhBb,iBAAkB,CAACC,KAAK,oBAAI,CAAC,IAAI,OAAOQ;IACnD,IAAIV,gBAAgBC,SAASC,UAAU,SAAS,OAAOQ;IACvD,OAAOH;AACT;AAEA,OAAO,MAAMQ,sBAAsBlB,cAAwC,CAAC,GAAE;AAC9EkB,oBAAoBC,WAAW,GAAG"}
|
|
@@ -24,7 +24,27 @@ import { readYesNoValue } from "./reusable-prop-values.js";
|
|
|
24
24
|
* the depth guard, so cycles can't recurse.
|
|
25
25
|
*/ const ITEM_TOKEN_PATTERN = /\{\{\s*item\.([A-Za-z][A-Za-z0-9_]*)(?:\.([A-Za-z][A-Za-z0-9_]*))?\s*\}\}/g;
|
|
26
26
|
/** Hard bound on rows a single repeatable renders, before `repeatLimit`. */ export const REPEAT_MAX_RECORDS = 100;
|
|
27
|
-
|
|
27
|
+
/**
|
|
28
|
+
* A plain object's part a token can name (AGL-4190): `{{item.icon.iconPath}}`
|
|
29
|
+
* reads the `iconPath` of a record's icon. Only text and numbers are parts;
|
|
30
|
+
* anything else is not something a page can print.
|
|
31
|
+
*/ function plainObjectPart(value, key) {
|
|
32
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
33
|
+
if (!Object.prototype.hasOwnProperty.call(value, key)) return null;
|
|
34
|
+
const part = value[key];
|
|
35
|
+
return typeof part === 'string' || typeof part === 'number' ? String(part) : null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A field's value as page text. A list is its entries, comma-joined. A map
|
|
39
|
+
* that names an icon (`{ iconId, iconPath }`, AGL-4190) is the icon's id,
|
|
40
|
+
* which is what an Icon element's icon holds; any other map is nothing,
|
|
41
|
+
* rather than the `[object Object]` a page would otherwise print.
|
|
42
|
+
*/ const displayValue = (value)=>{
|
|
43
|
+
var _plainObjectPart;
|
|
44
|
+
if (Array.isArray(value)) return value.join(', ');
|
|
45
|
+
if (value && typeof value === 'object') return (_plainObjectPart = plainObjectPart(value, 'iconId')) != null ? _plainObjectPart : '';
|
|
46
|
+
return String(value);
|
|
47
|
+
};
|
|
28
48
|
/** Resolves `{{item.ref.field}}`: FKey(s) → target document field value. */ function resolveReferenceHop(context, fieldId, targetFieldId) {
|
|
29
49
|
var _context_model_references, _context_model, _context_datasetsByKey;
|
|
30
50
|
const targetKey = (_context_model = context.model) == null ? void 0 : (_context_model_references = _context_model.references) == null ? void 0 : _context_model_references[fieldId];
|
|
@@ -48,7 +68,10 @@ function substituteValue(value, context) {
|
|
|
48
68
|
const unresolved = (token)=>context.missing === 'empty' ? '' : token;
|
|
49
69
|
return value.replace(ITEM_TOKEN_PATTERN, (token, field, hop)=>{
|
|
50
70
|
if (hop) {
|
|
51
|
-
|
|
71
|
+
var _resolveReferenceHop;
|
|
72
|
+
// A reference's target field first (AGL-180); otherwise a part of
|
|
73
|
+
// the field's own map, such as an icon's path (AGL-4190).
|
|
74
|
+
const resolved = (_resolveReferenceHop = resolveReferenceHop(context, field, hop)) != null ? _resolveReferenceHop : plainObjectPart(record[field], hop);
|
|
52
75
|
return resolved != null ? resolved : unresolved(token);
|
|
53
76
|
}
|
|
54
77
|
return record[field] != null ? displayValue(record[field]) : unresolved(token);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/expand-repeatables.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AglynNodeSchema, NodeId } from '../foundation'\nimport {\n applyRepeatQuery,\n parseRepeatFilter,\n parseRepeatSort,\n} from './repeat-query'\nimport {\n NODE_HIDE_IF_PROP,\n NODE_HIDE_UNLESS_PROP,\n} from './reusable-component-keys'\nimport { readYesNoValue } from './reusable-prop-values'\n\n/** Namespaces cloned template ids per container/record. */\nexport const REPEAT_NODE_ID_PREFIX = 'rep__'\n\n/**\n * `{{item.field}}` token, plus an optional single reference hop\n * (`{{item.author.name}}`, AGL-180). One hop only — the pattern itself is\n * the depth guard, so cycles can't recurse.\n */\nconst ITEM_TOKEN_PATTERN =\n /\\{\\{\\s*item\\.([A-Za-z][A-Za-z0-9_]*)(?:\\.([A-Za-z][A-Za-z0-9_]*))?\\s*\\}\\}/g\n\n/** Hard bound on rows a single repeatable renders, before `repeatLimit`. */\nexport const REPEAT_MAX_RECORDS = 100\n\n/**\n * What the expansion reads of the rows' field model (AGL-177, AGL-180): which\n * fields are references, each with the key its target's rows are answered\n * under (`datasetsByKey`). The model itself is the plugin's that keeps the\n * rows, and it states this much of it when it hands the rows over\n * (`plugin-manager/repeat-rows`, `repeat-sources`); a field it does not name\n * here hops nowhere, and its token is left as written.\n */\nexport interface RepeatRowsModel {\n /** Reference field id → the key of the rows it points into. */\n references?: Readonly<Record<string, string>>\n}\n\nexport interface RepeatableDataset {\n /**\n * Row value maps, in display order. Rows carry `$id` (needed to resolve\n * incoming references); values may be typed (AGL-177), stringified at\n * substitution.\n */\n records: Array<Record<string, unknown>>\n /** The rows' references; required for reference-hop bindings. */\n model?: RepeatRowsModel\n}\n\ninterface SubstituteContext {\n record: Record<string, unknown>\n /** The repeated rows' references (AGL-180). */\n model?: RepeatRowsModel\n /** All host datasets keyed by id (and name) for hop resolution. */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n /**\n * What a token whose field the record leaves empty becomes: `'token'` keeps\n * it as written (the besigner's canvas, where an author edits the template),\n * `'empty'` prints nothing (a rendered page, AGL-3616). A published page\n * never shows a visitor `{{item.venue}}` because one record has no venue.\n */\n missing?: 'token' | 'empty'\n}\n\nconst displayValue = (value: unknown): string =>\n Array.isArray(value) ? value.join(', ') : String(value)\n\n/** Resolves `{{item.ref.field}}`: FKey(s) → target document field value. */\nfunction resolveReferenceHop(\n context: SubstituteContext,\n fieldId: string,\n targetFieldId: string,\n): string | null {\n const targetKey = context.model?.references?.[fieldId]\n if (!targetKey) return null\n const target = context.datasetsByKey?.[targetKey]\n if (!target) return null\n const keys = context.record[fieldId]\n const ids = Array.isArray(keys) ? keys : keys != null ? [keys] : []\n const resolved = ids\n .map((id) => {\n const match = target.records.find((row) => row['$id'] === id)\n const value = match?.[targetFieldId]\n return value != null ? displayValue(value) : null\n })\n .filter((value): value is string => value != null)\n return resolved.length ? resolved.join(', ') : null\n}\n\nfunction substituteValue(\n value: unknown,\n context: SubstituteContext,\n): unknown {\n const { record } = context\n if (typeof value === 'string') {\n const unresolved = (token: string) =>\n context.missing === 'empty' ? '' : token\n return value.replace(\n ITEM_TOKEN_PATTERN,\n (token, field: string, hop?: string) => {\n if (hop) {\n const resolved = resolveReferenceHop(context, field, hop)\n return resolved != null ? resolved : unresolved(token)\n }\n return record[field] != null\n ? displayValue(record[field])\n : unresolved(token)\n },\n )\n }\n if (Array.isArray(value)) {\n return value.map((entry) => substituteValue(entry, context))\n }\n if (value && typeof value === 'object') {\n const next: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n next[key] = substituteValue(entry, context)\n }\n return next\n }\n return value\n}\n\n/** A text that is nothing but `{{item.*}}` tokens: a binding, not words. */\nconst WHOLE_BINDING = new RegExp(\n `^\\\\s*(?:${ITEM_TOKEN_PATTERN.source}\\\\s*)+$`,\n)\n\n/**\n * Whether a copy's element is a binding its record left empty (AGL-3616):\n * its text, `children`, or its picture, `src`, was only `{{item.*}}` tokens\n * and they printed nothing. The copy leaves the element out rather than\n * drawing an empty line (an eyebrow with no venue) or an empty frame (a card\n * whose record has no photo, AGL-3912), and a record that fills the field\n * draws it.\n */\nfunction isEmptyBinding(\n template: Record<string, unknown> | undefined,\n substituted: Record<string, unknown>,\n): boolean {\n return (['children', 'src'] as const).some((prop) => {\n const text = template?.[prop]\n if (typeof text !== 'string' || !WHOLE_BINDING.test(text)) return false\n const printed = substituted[prop]\n return typeof printed === 'string' && printed.trim() === ''\n })\n}\n\n/** One `{{item.*}}` token anywhere, without the global pattern's `lastIndex`. */\nconst ITEM_TOKEN_ANYWHERE = new RegExp(ITEM_TOKEN_PATTERN.source)\n\n/** Whether `text` holds a `{{item.*}}` token. */\nconst namesItemToken = (text: string): boolean => ITEM_TOKEN_ANYWHERE.test(text)\n\n/**\n * Whether a copy's element asks to be left out of it (AGL-4212): its\n * `hideIf` or `hideUnless` was bound to a `{{item.*}}` token, and this\n * record's value says so — `hideIf` a yes, `hideUnless` a no, an empty field\n * included. An owner's reply block bound `hideUnless: '{{item.reply}}'`\n * draws on the reviews that have one and on no other. A directive bound to\n * anything else is not the record's to answer, and is left to the graft and\n * the host prune that read it.\n */\nfunction isHiddenByRecord(\n template: Record<string, unknown> | undefined,\n substituted: Record<string, unknown>,\n): boolean {\n const reads = (prop: string, hiddenWhen: boolean) => {\n const bound = template?.[prop]\n return (\n typeof bound === 'string' &&\n namesItemToken(bound) &&\n readYesNoValue(substituted[prop]) === hiddenWhen\n )\n }\n return reads(NODE_HIDE_IF_PROP, true) || reads(NODE_HIDE_UNLESS_PROP, false)\n}\n\n/**\n * The prop a repeat over a plugin connection's synced record persists under\n * (AGL-4212): `<pluginIdentity>/<connectionId>` repeats once per item of the\n * record, `<pluginIdentity>/<connectionId>/fields` once for its summary\n * fields. Persisted — never rename.\n */\nexport const REPEAT_CONNECTION_PROP = 'repeatConnection'\n\n/**\n * What {@link repeatKey} puts before a {@link REPEAT_CONNECTION_PROP} value,\n * so a connection's key and a dataset's never name the same rows, and the\n * server's repeat-rows contract can route each to the plugin that answers it.\n */\nexport const REPEAT_CONNECTION_KEY_PREFIX = 'connection:'\n\n/**\n * The key a node repeats over, trimmed, or `''` when it repeats over nothing:\n * its `repeatDataset`, else {@link REPEAT_CONNECTION_KEY_PREFIX} and its\n * {@link REPEAT_CONNECTION_PROP} (AGL-4212).\n *\n * The one predicate every repeat question is asked through: the expansion, the\n * datasets-read gate below, the reusable-component graft that moves a\n * placement's repeat onto the element it becomes, and the besigner's preview\n * and badge. Two copies of it are how a `.trim()` on one side and not the\n * other becomes an empty list on a customer's page.\n */\nexport const repeatKey = (node: unknown): string => {\n const props = (node as { props?: Record<string, unknown> } | null)?.props\n const dataset = props?.['repeatDataset']\n const key = typeof dataset === 'string' ? dataset.trim() : ''\n if (key) return key\n const connection = props?.[REPEAT_CONNECTION_PROP]\n const value = typeof connection === 'string' ? connection.trim() : ''\n return value ? `${REPEAT_CONNECTION_KEY_PREFIX}${value}` : ''\n}\n\n/**\n * Makes an element that holds children repeat ITSELF, once per record, instead\n * of what is inside it (AGL-3111): a card whose contents are the design, rather\n * than a list whose contents are the item.\n *\n * Persisted in screen, layout and component documents — never rename. `'true'`\n * counts too, because a switch round-tripped through a text-shaped store comes\n * back as the string.\n */\nexport const REPEAT_SELF_PROP = 'repeatSelf'\n\n/**\n * Every prop that directs a repeat. They are instructions to the composition,\n * never attributes of the element: the expansion consumes them from every node\n * it expands and every copy it makes, so a published element never carries\n * one. Persisted — never rename.\n */\nexport const REPEAT_DIRECTIVE_PROPS: readonly string[] = [\n 'repeatDataset',\n REPEAT_CONNECTION_PROP,\n 'repeatLimit',\n 'repeatFilter',\n 'repeatSort',\n REPEAT_SELF_PROP,\n]\n\n/**\n * What a repeating node copies once per record (AGL-3111).\n *\n * - `children` — what is inside it. The node stays one element around the\n * copies: the list, grid or gallery they fill. This is how a Stack has\n * always repeated (AGL-103), and a stored Stack names neither scope.\n * - `self` — the node itself, with everything inside it. What a leaf and a\n * component instance repeat, and what any element carrying\n * {@link REPEAT_SELF_PROP} repeats.\n */\nexport type RepeatScope = 'self' | 'children'\n\n/**\n * Which scope a repeating node has, read off the node alone so the published\n * page's composition and the besigner decide it identically.\n *\n * {@link REPEAT_SELF_PROP} decides it whenever the node carries one, which is\n * every repeat the Attributes panel writes. Without one the node's own shape\n * decides, and it decides CONSERVATIVELY: anything that holds a child list —\n * a Stack, empty or not — keeps repeating its children, and only a node with\n * no child list at all repeats itself. A stored repeat predates the prop, so\n * this branch is the one that has to render it unchanged, and an author who\n * named a dataset before filling the container in would otherwise come back to\n * a hundred empty copies of it.\n *\n * A component instance never reaches that branch: the graft stamps the prop on\n * the element it becomes, whose children are the component's own.\n */\nexport function repeatScope(node: unknown): RepeatScope {\n const { props, nodes } = (node ?? {}) as {\n props?: Record<string, unknown>\n nodes?: unknown\n }\n // `'true'`/`'false'` too: a switch round-tripped through a text-shaped\n // store comes back as the string it was written as.\n const self = props?.[REPEAT_SELF_PROP]\n if (self === true || self === 'true') return 'self'\n if (self === false || self === 'false') return 'children'\n return Array.isArray(nodes) ? 'children' : 'self'\n}\n\n/**\n * One record's values put into `{{item.field}}` tokens, anywhere in a props\n * map — the substitution {@link expandRepeatables} makes on every copy it\n * builds, for a caller that already knows which record it is rendering.\n *\n * The besigner's canvas is that caller (AGL-3111): the element an author\n * edits IS the first copy, so it draws with the first record's values while\n * the node it saves keeps the tokens. Exported rather than reimplemented\n * because a canvas that resolved a token differently from the page would be\n * showing the author a page that does not exist.\n */\nexport function substituteRecordTokens<T>(\n props: T,\n context: {\n record: Record<string, unknown>\n /** The repeated rows' references (AGL-180). */\n model?: RepeatRowsModel\n /** Rows by key, for a one-hop reference (AGL-180). */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n },\n): T {\n return substituteValue(props, context) as T\n}\n\n/**\n * The one record a whole page is rendered for (AGL-3475): a record template's\n * routed record, in the shape a repeat hands each of its copies.\n */\nexport interface PageRecordScope {\n record: Record<string, unknown>\n /** The record's references (AGL-180). */\n model?: RepeatRowsModel\n /** Rows by key, for a one-hop reference (AGL-180). */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n}\n\n/**\n * Every node's props with the page's record put into its `{{item.field}}`\n * tokens — the substitution a repeat makes on each copy, made once over a\n * page that renders one record (AGL-3475).\n *\n * Run AFTER {@link expandRepeatables}: a repeat inside the page has already\n * spent its own `{{item.*}}` tokens on its own rows by then, so what is left\n * is the page's. A token naming a field the record leaves empty prints\n * nothing, exactly as in a repeat (AGL-3616). Returns the input when there is\n * no record.\n */\nexport function substituteNodesRecordTokens<N>(\n nodes: Record<NodeId, N>,\n scope: PageRecordScope | null | undefined,\n): Record<NodeId, N> {\n if (!scope) return nodes\n const next: Record<NodeId, N> = {}\n for (const [id, node] of Object.entries(nodes) as Array<[NodeId, N]>) {\n const props = (node as { props?: unknown })?.props\n next[id] = props\n ? ({\n ...node,\n props: substituteValue(props, { ...scope, missing: 'empty' }),\n } as N)\n : node\n }\n return next\n}\n\n/**\n * The page's record put into each repeat's FILTER, before the repeats expand\n * (AGL-3475): on a record template, `category == {{item.category}}` lists the\n * other records in the routed record's category. Only `repeatFilter` is\n * touched — everything else inside a repeat is its template, whose\n * `{{item.*}}` belongs to its own rows. Returns the input when there is no\n * record or no filter names one.\n */\nexport function substituteRepeatFilterRecordTokens<N>(\n nodes: Record<NodeId, N>,\n scope: PageRecordScope | null | undefined,\n): Record<NodeId, N> {\n if (!scope) return nodes\n let next: Record<NodeId, N> | null = null\n for (const [id, node] of Object.entries(nodes) as Array<[NodeId, N]>) {\n const props = (node as { props?: Record<string, unknown> })?.props\n const filter = props?.['repeatFilter']\n if (typeof filter !== 'string' || !filter.includes('{{')) continue\n next ??= { ...nodes }\n next[id] = {\n ...node,\n props: { ...props, repeatFilter: substituteValue(filter, scope) },\n } as N\n }\n return next ?? nodes\n}\n\n/** The node minus its repeat directives, or the node itself when it has none. */\nexport function withoutRepeatDirective<N>(node: N): N {\n const props = (node as { props?: Record<string, unknown> })?.props\n if (!props || !REPEAT_DIRECTIVE_PROPS.some((key) => key in props)) {\n return node\n }\n const kept = { ...props }\n for (const key of REPEAT_DIRECTIVE_PROPS) delete kept[key]\n return { ...node, props: kept }\n}\n\n/**\n * The records a repeating node renders, in order (AGL-181): its filter and sort\n * evaluated over the rows, then its limit, never past\n * {@link REPEAT_MAX_RECORDS}. An unparseable filter or sort fails open.\n *\n * Shared by the expansion and the besigner's canvas preview and badge, so the\n * canvas can never show a copy or a count the published page does not.\n */\nexport function repeatedRecords(\n node: unknown,\n dataset: RepeatableDataset | undefined,\n): Array<Record<string, unknown>> {\n const props = ((node as { props?: unknown })?.props ?? {}) as Record<\n string,\n unknown\n >\n const where = parseRepeatFilter(String(props['repeatFilter'] ?? ''))\n const orderBy = parseRepeatSort(String(props['repeatSort'] ?? ''))\n const limit = Number(props['repeatLimit'])\n return applyRepeatQuery(dataset?.records ?? [], {\n ...(where ? { where: [where] } : {}),\n ...(orderBy ? { orderBy } : {}),\n }).slice(\n 0,\n Number.isFinite(limit) && limit > 0\n ? Math.min(limit, REPEAT_MAX_RECORDS)\n : REPEAT_MAX_RECORDS,\n )\n}\n\n/**\n * Does this tree contain anything {@link expandRepeatables} would expand —\n * or, with no rows, empty?\n *\n * The rows read is the largest on the render path — up to two pages of\n * {@link REPEAT_MAX_RECORDS} records for every key a page repeats over — and a\n * page that repeats over nothing should pay none of it (AGL-1440).\n *\n * Any gate on that read has to ask EXACTLY the question the expansion asks,\n * which is why this and {@link repeatKeys} share the one predicate\n * `expandRepeatables` looks keys up with, {@link repeatKey}. A gate that is\n * even slightly stricter than the expansion is not a saving: it is a published\n * page whose repeat never reaches the expansion at all, and so goes out as\n * its raw template — `{{item.*}}` tokens and all — where the author put a list.\n */\nexport function hasRepeatableNodes(\n nodes: Record<NodeId, unknown> | null | undefined,\n): boolean {\n if (!nodes) return false\n return Object.values(nodes).some((node) => repeatKey(node) !== '')\n}\n\n/**\n * Every key this tree repeats over, exactly as {@link expandRepeatables} looks\n * it up — sorted and without repeats.\n *\n * What the tenant compose asks the repeat-rows contract for\n * (`plugin-manager/repeat-rows.ts`), so a page loads the rows it renders and\n * not everything its site may see. Built on the same predicate as\n * {@link hasRepeatableNodes} for the reason given there.\n */\nexport function repeatKeys(\n nodes: Record<NodeId, unknown> | null | undefined,\n): string[] {\n const keys = new Set<string>()\n for (const node of Object.values(nodes ?? {})) {\n const key = repeatKey(node)\n if (key) keys.add(key)\n }\n return [...keys].sort()\n}\n\n/**\n * Repeats (AGL-103, AGL-3111): any node carrying `props.repeatDataset` (a\n * dataset id or display name), or `props.repeatConnection` (a plugin\n * connection's synced record, AGL-4212), renders once per record, with\n * `{{item.field}}` tokens in the copied string props replaced by the record's\n * values. A field the record leaves empty prints nothing — never the raw\n * token — and an element whose whole text is such a binding is left out of\n * that copy (AGL-3616: a tour date with no venue drew `{{ITEM.VENUE}}` as its\n * eyebrow on a published site). The besigner's canvas keeps the tokens of\n * the template an author edits ({@link substituteRecordTokens}).\n *\n * What is copied is the node's {@link repeatScope}:\n *\n * - `children` — its children are the item template. The node stays, and its\n * child list becomes the copies, record by record. Its own props are not the\n * template, so no token in them is substituted.\n * - `self` — the node and everything inside it are the template. The copies\n * take the node's place in its parent's child list, and every prop in the\n * subtree is substituted, the node's own included.\n *\n * - Copy ids are namespaced `rep__{repeatId}__{index}__…` — the repeat's own\n * id, then the template node's — so repeats never collide, including inside\n * grafted reusable components. A self-scoped node's first copy is\n * `rep__{id}__0__{id}`. Run this AFTER `composeReusableComponentNodes` and\n * BEFORE binding resolution.\n * - Rows are the node's {@link repeatedRecords}, looked up under its\n * {@link repeatKey}.\n * - An element of a copy whose `hideIf` / `hideUnless` is bound to a\n * `{{item.*}}` token is left out of that copy, with everything inside it,\n * when the record's value says so (AGL-4212).\n * - The repeat directives ({@link REPEAT_DIRECTIVE_PROPS}) are consumed: every\n * node this expands, and every copy it makes, comes out without them.\n * - Repeats do not nest. A repeat inside another repeat's template is copied\n * with its directives consumed, so it renders once in each copy.\n * - No rows renders ZERO copies (AGL-3496): a `children` repeat keeps its\n * element with an empty child list, a `self` repeat leaves its parent's\n * list. That covers a filter matching nothing, an empty dataset, and a key\n * the rows answer nothing under — a deleted or unshared dataset, or no rows\n * map at all — because the template drawn without a record is its literal\n * `{{item.*}}` tokens, printed to every visitor. Never a throw: a dataset\n * going away empties a list, it does not take the page down.\n * - An empty template, or a self-scoped node its parent does not list (the\n * document root, say), has nothing to copy or nowhere to put copies, and is\n * left as written.\n * - Inputs are never mutated; templates stay in the map unreferenced.\n *\n * This is the PUBLISHED page's composition. The besigner's canvas keeps the\n * template on screen whatever the rows say — it is what an author edits — and\n * flags a repeat with no rows on its badge instead ({@link repeatedRecords}\n * is the count both read).\n */\nexport function expandRepeatables<N extends AglynNodeSchema = AglynNodeSchema>(\n nodes: Record<NodeId, N>,\n datasetsByKey: Record<string, RepeatableDataset | undefined> | undefined,\n): Record<NodeId, N> {\n const rowsByKey = datasetsByKey ?? {}\n const repeatIds = Object.entries(nodes).filter(\n ([, node]) => repeatKey(node) !== '',\n )\n if (!repeatIds.length) return nodes\n\n const next: Record<NodeId, N> = { ...nodes }\n for (const [repeatId, repeated] of repeatIds) {\n const dataset = rowsByKey[repeatKey(repeated)]\n const records = repeatedRecords(repeated, dataset)\n const self = repeatScope(repeated) === 'self'\n // The copies' parent: the node itself, or — for a self-scoped node — the\n // parent whose child list the copies take its place in, read from `next`\n // so two self-scoped siblings both land in the list the other has left.\n const parentId = (self ? repeated.parentId : repeatId) as NodeId\n const siblings = next[parentId]?.nodes\n const slot = Array.isArray(siblings)\n ? (siblings as NodeId[]).indexOf(repeatId)\n : -1\n const templateIds = self\n ? [repeatId]\n : Array.isArray(repeated.nodes)\n ? (repeated.nodes as NodeId[])\n : []\n next[repeatId] = withoutRepeatDirective(next[repeatId])\n if (!templateIds.length || (self && slot < 0)) continue\n if (!records.length) {\n // Zero copies (AGL-3496). The template is a design, not content: drawn\n // without a record it prints `{{item.name}}` to every visitor.\n if (self) {\n const listed = [...(next[parentId].nodes as NodeId[])]\n listed.splice(slot, 1)\n next[parentId] = { ...next[parentId], nodes: listed }\n } else {\n next[repeatId] = { ...next[repeatId], nodes: [] }\n }\n continue\n }\n\n const copyIds: NodeId[] = []\n records.forEach((record, index) => {\n const prefix = `${REPEAT_NODE_ID_PREFIX}${repeatId}__${index}__`\n const prefixId = (id: NodeId) => `${prefix}${id}`\n // Whether the copy drew the node: an element whose whole text is a\n // binding this record leaves empty is left out of it (AGL-3616).\n const cloneSubtree = (id: NodeId, clonedParentId: NodeId): boolean => {\n const node = nodes[id]\n if (!node) return false\n const props = substituteValue(node.props ?? {}, {\n record,\n model: dataset?.model,\n datasetsByKey: rowsByKey,\n missing: 'empty',\n }) as Record<string, unknown>\n const template = node.props as Record<string, unknown> | undefined\n if (\n isEmptyBinding(template, props) ||\n isHiddenByRecord(template, props)\n ) {\n return false\n }\n // Read, so not carried: a copy is drawn or left out, and the\n // directive that decided it has nothing left to say.\n for (const prop of [NODE_HIDE_IF_PROP, NODE_HIDE_UNLESS_PROP]) {\n const bound = template?.[prop]\n if (typeof bound === 'string' && namesItemToken(bound)) {\n delete props[prop]\n }\n }\n const clonedChildren = Array.isArray(node.nodes)\n ? (node.nodes as NodeId[])\n : undefined\n const drawn = clonedChildren?.filter((childId) =>\n cloneSubtree(childId, prefixId(id)),\n )\n next[prefixId(id)] = withoutRepeatDirective({\n ...node,\n $id: prefixId(id),\n parentId: clonedParentId,\n props: props as any,\n ...(drawn && {\n nodes: drawn.map((childId) => prefixId(childId)),\n }),\n })\n return true\n }\n for (const templateId of templateIds) {\n if (cloneSubtree(templateId, parentId)) {\n copyIds.push(prefixId(templateId))\n }\n }\n })\n if (self) {\n const listed = [...(next[parentId].nodes as NodeId[])]\n listed.splice(slot, 1, ...copyIds)\n next[parentId] = { ...next[parentId], nodes: listed }\n } else {\n next[repeatId] = { ...next[repeatId], nodes: copyIds }\n }\n }\n return next\n}\n\nexport default expandRepeatables\n"],"names":["applyRepeatQuery","parseRepeatFilter","parseRepeatSort","NODE_HIDE_IF_PROP","NODE_HIDE_UNLESS_PROP","readYesNoValue","REPEAT_NODE_ID_PREFIX","ITEM_TOKEN_PATTERN","REPEAT_MAX_RECORDS","displayValue","value","Array","isArray","join","String","resolveReferenceHop","context","fieldId","targetFieldId","targetKey","model","references","target","datasetsByKey","keys","record","ids","resolved","map","id","match","records","find","row","filter","length","substituteValue","unresolved","token","missing","replace","field","hop","entry","next","key","Object","entries","WHOLE_BINDING","RegExp","source","isEmptyBinding","template","substituted","some","prop","text","test","printed","trim","ITEM_TOKEN_ANYWHERE","namesItemToken","isHiddenByRecord","reads","hiddenWhen","bound","REPEAT_CONNECTION_PROP","REPEAT_CONNECTION_KEY_PREFIX","repeatKey","node","props","dataset","connection","REPEAT_SELF_PROP","REPEAT_DIRECTIVE_PROPS","repeatScope","nodes","self","substituteRecordTokens","substituteNodesRecordTokens","scope","substituteRepeatFilterRecordTokens","includes","repeatFilter","withoutRepeatDirective","kept","repeatedRecords","where","orderBy","limit","Number","slice","isFinite","Math","min","hasRepeatableNodes","values","repeatKeys","Set","add","sort","expandRepeatables","rowsByKey","repeatIds","repeatId","repeated","parentId","siblings","slot","indexOf","templateIds","listed","splice","copyIds","forEach","index","prefix","prefixId","cloneSubtree","clonedParentId","clonedChildren","undefined","drawn","childId","$id","templateId","push"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,eAAe,QACV,oBAAgB;AACvB,SACEC,iBAAiB,EACjBC,qBAAqB,QAChB,+BAA2B;AAClC,SAASC,cAAc,QAAQ,4BAAwB;AAEvD,yDAAyD,GACzD,OAAO,MAAMC,wBAAwB,QAAO;AAE5C;;;;CAIC,GACD,MAAMC,qBACJ;AAEF,0EAA0E,GAC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BAEjCe,IAAI,CAACyE,SAASxF,IAAI,GAAGuD,uBAAuB,aACvCf;oBACHuD,KAAKP,SAASxF;oBACd6E,UAAUa;oBACVjD,OAAOA;mBACHoD,SAAS;oBACX9C,OAAO8C,MAAM9F,GAAG,CAAC,CAAC+F,UAAYN,SAASM;gBACzC;gBAEF,OAAO;YACT;YACA,KAAK,MAAME,cAAcf,YAAa;gBACpC,IAAIQ,aAAaO,YAAYnB,WAAW;oBACtCO,QAAQa,IAAI,CAACT,SAASQ;gBACxB;YACF;QACF;QACA,IAAIhD,MAAM;YACR,MAAMkC,SAAS;mBAAKnE,IAAI,CAAC8D,SAAS,CAAC9B,KAAK;aAAc;YACtDmC,OAAOC,MAAM,CAACJ,MAAM,MAAMK;YAC1BrE,IAAI,CAAC8D,SAAS,GAAG,aAAK9D,IAAI,CAAC8D,SAAS;gBAAE9B,OAAOmC;;QAC/C,OAAO;YACLnE,IAAI,CAAC4D,SAAS,GAAG,aAAK5D,IAAI,CAAC4D,SAAS;gBAAE5B,OAAOqC;;QAC/C;IACF;IACA,OAAOrE;AACT;AAEA,eAAeyD,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/expand-repeatables.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AglynNodeSchema, NodeId } from '../foundation'\nimport {\n applyRepeatQuery,\n parseRepeatFilter,\n parseRepeatSort,\n} from './repeat-query'\nimport {\n NODE_HIDE_IF_PROP,\n NODE_HIDE_UNLESS_PROP,\n} from './reusable-component-keys'\nimport { readYesNoValue } from './reusable-prop-values'\n\n/** Namespaces cloned template ids per container/record. */\nexport const REPEAT_NODE_ID_PREFIX = 'rep__'\n\n/**\n * `{{item.field}}` token, plus an optional single reference hop\n * (`{{item.author.name}}`, AGL-180). One hop only — the pattern itself is\n * the depth guard, so cycles can't recurse.\n */\nconst ITEM_TOKEN_PATTERN =\n /\\{\\{\\s*item\\.([A-Za-z][A-Za-z0-9_]*)(?:\\.([A-Za-z][A-Za-z0-9_]*))?\\s*\\}\\}/g\n\n/** Hard bound on rows a single repeatable renders, before `repeatLimit`. */\nexport const REPEAT_MAX_RECORDS = 100\n\n/**\n * What the expansion reads of the rows' field model (AGL-177, AGL-180): which\n * fields are references, each with the key its target's rows are answered\n * under (`datasetsByKey`). The model itself is the plugin's that keeps the\n * rows, and it states this much of it when it hands the rows over\n * (`plugin-manager/repeat-rows`, `repeat-sources`); a field it does not name\n * here hops nowhere, and its token is left as written.\n */\nexport interface RepeatRowsModel {\n /** Reference field id → the key of the rows it points into. */\n references?: Readonly<Record<string, string>>\n}\n\nexport interface RepeatableDataset {\n /**\n * Row value maps, in display order. Rows carry `$id` (needed to resolve\n * incoming references); values may be typed (AGL-177), stringified at\n * substitution.\n */\n records: Array<Record<string, unknown>>\n /** The rows' references; required for reference-hop bindings. */\n model?: RepeatRowsModel\n}\n\ninterface SubstituteContext {\n record: Record<string, unknown>\n /** The repeated rows' references (AGL-180). */\n model?: RepeatRowsModel\n /** All host datasets keyed by id (and name) for hop resolution. */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n /**\n * What a token whose field the record leaves empty becomes: `'token'` keeps\n * it as written (the besigner's canvas, where an author edits the template),\n * `'empty'` prints nothing (a rendered page, AGL-3616). A published page\n * never shows a visitor `{{item.venue}}` because one record has no venue.\n */\n missing?: 'token' | 'empty'\n}\n\n/**\n * A plain object's part a token can name (AGL-4190): `{{item.icon.iconPath}}`\n * reads the `iconPath` of a record's icon. Only text and numbers are parts;\n * anything else is not something a page can print.\n */\nfunction plainObjectPart(value: unknown, key: string): string | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n if (!Object.prototype.hasOwnProperty.call(value, key)) return null\n const part = (value as Record<string, unknown>)[key]\n return typeof part === 'string' || typeof part === 'number' ? String(part) : null\n}\n\n/**\n * A field's value as page text. A list is its entries, comma-joined. A map\n * that names an icon (`{ iconId, iconPath }`, AGL-4190) is the icon's id,\n * which is what an Icon element's icon holds; any other map is nothing,\n * rather than the `[object Object]` a page would otherwise print.\n */\nconst displayValue = (value: unknown): string => {\n if (Array.isArray(value)) return value.join(', ')\n if (value && typeof value === 'object') return plainObjectPart(value, 'iconId') ?? ''\n return String(value)\n}\n\n/** Resolves `{{item.ref.field}}`: FKey(s) → target document field value. */\nfunction resolveReferenceHop(\n context: SubstituteContext,\n fieldId: string,\n targetFieldId: string,\n): string | null {\n const targetKey = context.model?.references?.[fieldId]\n if (!targetKey) return null\n const target = context.datasetsByKey?.[targetKey]\n if (!target) return null\n const keys = context.record[fieldId]\n const ids = Array.isArray(keys) ? keys : keys != null ? [keys] : []\n const resolved = ids\n .map((id) => {\n const match = target.records.find((row) => row['$id'] === id)\n const value = match?.[targetFieldId]\n return value != null ? displayValue(value) : null\n })\n .filter((value): value is string => value != null)\n return resolved.length ? resolved.join(', ') : null\n}\n\nfunction substituteValue(\n value: unknown,\n context: SubstituteContext,\n): unknown {\n const { record } = context\n if (typeof value === 'string') {\n const unresolved = (token: string) =>\n context.missing === 'empty' ? '' : token\n return value.replace(\n ITEM_TOKEN_PATTERN,\n (token, field: string, hop?: string) => {\n if (hop) {\n // A reference's target field first (AGL-180); otherwise a part of\n // the field's own map, such as an icon's path (AGL-4190).\n const resolved =\n resolveReferenceHop(context, field, hop) ??\n plainObjectPart(record[field], hop)\n return resolved != null ? resolved : unresolved(token)\n }\n return record[field] != null\n ? displayValue(record[field])\n : unresolved(token)\n },\n )\n }\n if (Array.isArray(value)) {\n return value.map((entry) => substituteValue(entry, context))\n }\n if (value && typeof value === 'object') {\n const next: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n next[key] = substituteValue(entry, context)\n }\n return next\n }\n return value\n}\n\n/** A text that is nothing but `{{item.*}}` tokens: a binding, not words. */\nconst WHOLE_BINDING = new RegExp(\n `^\\\\s*(?:${ITEM_TOKEN_PATTERN.source}\\\\s*)+$`,\n)\n\n/**\n * Whether a copy's element is a binding its record left empty (AGL-3616):\n * its text, `children`, or its picture, `src`, was only `{{item.*}}` tokens\n * and they printed nothing. The copy leaves the element out rather than\n * drawing an empty line (an eyebrow with no venue) or an empty frame (a card\n * whose record has no photo, AGL-3912), and a record that fills the field\n * draws it.\n */\nfunction isEmptyBinding(\n template: Record<string, unknown> | undefined,\n substituted: Record<string, unknown>,\n): boolean {\n return (['children', 'src'] as const).some((prop) => {\n const text = template?.[prop]\n if (typeof text !== 'string' || !WHOLE_BINDING.test(text)) return false\n const printed = substituted[prop]\n return typeof printed === 'string' && printed.trim() === ''\n })\n}\n\n/** One `{{item.*}}` token anywhere, without the global pattern's `lastIndex`. */\nconst ITEM_TOKEN_ANYWHERE = new RegExp(ITEM_TOKEN_PATTERN.source)\n\n/** Whether `text` holds a `{{item.*}}` token. */\nconst namesItemToken = (text: string): boolean => ITEM_TOKEN_ANYWHERE.test(text)\n\n/**\n * Whether a copy's element asks to be left out of it (AGL-4212): its\n * `hideIf` or `hideUnless` was bound to a `{{item.*}}` token, and this\n * record's value says so — `hideIf` a yes, `hideUnless` a no, an empty field\n * included. An owner's reply block bound `hideUnless: '{{item.reply}}'`\n * draws on the reviews that have one and on no other. A directive bound to\n * anything else is not the record's to answer, and is left to the graft and\n * the host prune that read it.\n */\nfunction isHiddenByRecord(\n template: Record<string, unknown> | undefined,\n substituted: Record<string, unknown>,\n): boolean {\n const reads = (prop: string, hiddenWhen: boolean) => {\n const bound = template?.[prop]\n return (\n typeof bound === 'string' &&\n namesItemToken(bound) &&\n readYesNoValue(substituted[prop]) === hiddenWhen\n )\n }\n return reads(NODE_HIDE_IF_PROP, true) || reads(NODE_HIDE_UNLESS_PROP, false)\n}\n\n/**\n * The prop a repeat over a plugin connection's synced record persists under\n * (AGL-4212): `<pluginIdentity>/<connectionId>` repeats once per item of the\n * record, `<pluginIdentity>/<connectionId>/fields` once for its summary\n * fields. Persisted — never rename.\n */\nexport const REPEAT_CONNECTION_PROP = 'repeatConnection'\n\n/**\n * What {@link repeatKey} puts before a {@link REPEAT_CONNECTION_PROP} value,\n * so a connection's key and a dataset's never name the same rows, and the\n * server's repeat-rows contract can route each to the plugin that answers it.\n */\nexport const REPEAT_CONNECTION_KEY_PREFIX = 'connection:'\n\n/**\n * The key a node repeats over, trimmed, or `''` when it repeats over nothing:\n * its `repeatDataset`, else {@link REPEAT_CONNECTION_KEY_PREFIX} and its\n * {@link REPEAT_CONNECTION_PROP} (AGL-4212).\n *\n * The one predicate every repeat question is asked through: the expansion, the\n * datasets-read gate below, the reusable-component graft that moves a\n * placement's repeat onto the element it becomes, and the besigner's preview\n * and badge. Two copies of it are how a `.trim()` on one side and not the\n * other becomes an empty list on a customer's page.\n */\nexport const repeatKey = (node: unknown): string => {\n const props = (node as { props?: Record<string, unknown> } | null)?.props\n const dataset = props?.['repeatDataset']\n const key = typeof dataset === 'string' ? dataset.trim() : ''\n if (key) return key\n const connection = props?.[REPEAT_CONNECTION_PROP]\n const value = typeof connection === 'string' ? connection.trim() : ''\n return value ? `${REPEAT_CONNECTION_KEY_PREFIX}${value}` : ''\n}\n\n/**\n * Makes an element that holds children repeat ITSELF, once per record, instead\n * of what is inside it (AGL-3111): a card whose contents are the design, rather\n * than a list whose contents are the item.\n *\n * Persisted in screen, layout and component documents — never rename. `'true'`\n * counts too, because a switch round-tripped through a text-shaped store comes\n * back as the string.\n */\nexport const REPEAT_SELF_PROP = 'repeatSelf'\n\n/**\n * Every prop that directs a repeat. They are instructions to the composition,\n * never attributes of the element: the expansion consumes them from every node\n * it expands and every copy it makes, so a published element never carries\n * one. Persisted — never rename.\n */\nexport const REPEAT_DIRECTIVE_PROPS: readonly string[] = [\n 'repeatDataset',\n REPEAT_CONNECTION_PROP,\n 'repeatLimit',\n 'repeatFilter',\n 'repeatSort',\n REPEAT_SELF_PROP,\n]\n\n/**\n * What a repeating node copies once per record (AGL-3111).\n *\n * - `children` — what is inside it. The node stays one element around the\n * copies: the list, grid or gallery they fill. This is how a Stack has\n * always repeated (AGL-103), and a stored Stack names neither scope.\n * - `self` — the node itself, with everything inside it. What a leaf and a\n * component instance repeat, and what any element carrying\n * {@link REPEAT_SELF_PROP} repeats.\n */\nexport type RepeatScope = 'self' | 'children'\n\n/**\n * Which scope a repeating node has, read off the node alone so the published\n * page's composition and the besigner decide it identically.\n *\n * {@link REPEAT_SELF_PROP} decides it whenever the node carries one, which is\n * every repeat the Attributes panel writes. Without one the node's own shape\n * decides, and it decides CONSERVATIVELY: anything that holds a child list —\n * a Stack, empty or not — keeps repeating its children, and only a node with\n * no child list at all repeats itself. A stored repeat predates the prop, so\n * this branch is the one that has to render it unchanged, and an author who\n * named a dataset before filling the container in would otherwise come back to\n * a hundred empty copies of it.\n *\n * A component instance never reaches that branch: the graft stamps the prop on\n * the element it becomes, whose children are the component's own.\n */\nexport function repeatScope(node: unknown): RepeatScope {\n const { props, nodes } = (node ?? {}) as {\n props?: Record<string, unknown>\n nodes?: unknown\n }\n // `'true'`/`'false'` too: a switch round-tripped through a text-shaped\n // store comes back as the string it was written as.\n const self = props?.[REPEAT_SELF_PROP]\n if (self === true || self === 'true') return 'self'\n if (self === false || self === 'false') return 'children'\n return Array.isArray(nodes) ? 'children' : 'self'\n}\n\n/**\n * One record's values put into `{{item.field}}` tokens, anywhere in a props\n * map — the substitution {@link expandRepeatables} makes on every copy it\n * builds, for a caller that already knows which record it is rendering.\n *\n * The besigner's canvas is that caller (AGL-3111): the element an author\n * edits IS the first copy, so it draws with the first record's values while\n * the node it saves keeps the tokens. Exported rather than reimplemented\n * because a canvas that resolved a token differently from the page would be\n * showing the author a page that does not exist.\n */\nexport function substituteRecordTokens<T>(\n props: T,\n context: {\n record: Record<string, unknown>\n /** The repeated rows' references (AGL-180). */\n model?: RepeatRowsModel\n /** Rows by key, for a one-hop reference (AGL-180). */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n },\n): T {\n return substituteValue(props, context) as T\n}\n\n/**\n * The one record a whole page is rendered for (AGL-3475): a record template's\n * routed record, in the shape a repeat hands each of its copies.\n */\nexport interface PageRecordScope {\n record: Record<string, unknown>\n /** The record's references (AGL-180). */\n model?: RepeatRowsModel\n /** Rows by key, for a one-hop reference (AGL-180). */\n datasetsByKey?: Record<string, RepeatableDataset | undefined>\n}\n\n/**\n * Every node's props with the page's record put into its `{{item.field}}`\n * tokens — the substitution a repeat makes on each copy, made once over a\n * page that renders one record (AGL-3475).\n *\n * Run AFTER {@link expandRepeatables}: a repeat inside the page has already\n * spent its own `{{item.*}}` tokens on its own rows by then, so what is left\n * is the page's. A token naming a field the record leaves empty prints\n * nothing, exactly as in a repeat (AGL-3616). Returns the input when there is\n * no record.\n */\nexport function substituteNodesRecordTokens<N>(\n nodes: Record<NodeId, N>,\n scope: PageRecordScope | null | undefined,\n): Record<NodeId, N> {\n if (!scope) return nodes\n const next: Record<NodeId, N> = {}\n for (const [id, node] of Object.entries(nodes) as Array<[NodeId, N]>) {\n const props = (node as { props?: unknown })?.props\n next[id] = props\n ? ({\n ...node,\n props: substituteValue(props, { ...scope, missing: 'empty' }),\n } as N)\n : node\n }\n return next\n}\n\n/**\n * The page's record put into each repeat's FILTER, before the repeats expand\n * (AGL-3475): on a record template, `category == {{item.category}}` lists the\n * other records in the routed record's category. Only `repeatFilter` is\n * touched — everything else inside a repeat is its template, whose\n * `{{item.*}}` belongs to its own rows. Returns the input when there is no\n * record or no filter names one.\n */\nexport function substituteRepeatFilterRecordTokens<N>(\n nodes: Record<NodeId, N>,\n scope: PageRecordScope | null | undefined,\n): Record<NodeId, N> {\n if (!scope) return nodes\n let next: Record<NodeId, N> | null = null\n for (const [id, node] of Object.entries(nodes) as Array<[NodeId, N]>) {\n const props = (node as { props?: Record<string, unknown> })?.props\n const filter = props?.['repeatFilter']\n if (typeof filter !== 'string' || !filter.includes('{{')) continue\n next ??= { ...nodes }\n next[id] = {\n ...node,\n props: { ...props, repeatFilter: substituteValue(filter, scope) },\n } as N\n }\n return next ?? nodes\n}\n\n/** The node minus its repeat directives, or the node itself when it has none. */\nexport function withoutRepeatDirective<N>(node: N): N {\n const props = (node as { props?: Record<string, unknown> })?.props\n if (!props || !REPEAT_DIRECTIVE_PROPS.some((key) => key in props)) {\n return node\n }\n const kept = { ...props }\n for (const key of REPEAT_DIRECTIVE_PROPS) delete kept[key]\n return { ...node, props: kept }\n}\n\n/**\n * The records a repeating node renders, in order (AGL-181): its filter and sort\n * evaluated over the rows, then its limit, never past\n * {@link REPEAT_MAX_RECORDS}. An unparseable filter or sort fails open.\n *\n * Shared by the expansion and the besigner's canvas preview and badge, so the\n * canvas can never show a copy or a count the published page does not.\n */\nexport function repeatedRecords(\n node: unknown,\n dataset: RepeatableDataset | undefined,\n): Array<Record<string, unknown>> {\n const props = ((node as { props?: unknown })?.props ?? {}) as Record<\n string,\n unknown\n >\n const where = parseRepeatFilter(String(props['repeatFilter'] ?? ''))\n const orderBy = parseRepeatSort(String(props['repeatSort'] ?? ''))\n const limit = Number(props['repeatLimit'])\n return applyRepeatQuery(dataset?.records ?? [], {\n ...(where ? { where: [where] } : {}),\n ...(orderBy ? { orderBy } : {}),\n }).slice(\n 0,\n Number.isFinite(limit) && limit > 0\n ? Math.min(limit, REPEAT_MAX_RECORDS)\n : REPEAT_MAX_RECORDS,\n )\n}\n\n/**\n * Does this tree contain anything {@link expandRepeatables} would expand —\n * or, with no rows, empty?\n *\n * The rows read is the largest on the render path — up to two pages of\n * {@link REPEAT_MAX_RECORDS} records for every key a page repeats over — and a\n * page that repeats over nothing should pay none of it (AGL-1440).\n *\n * Any gate on that read has to ask EXACTLY the question the expansion asks,\n * which is why this and {@link repeatKeys} share the one predicate\n * `expandRepeatables` looks keys up with, {@link repeatKey}. A gate that is\n * even slightly stricter than the expansion is not a saving: it is a published\n * page whose repeat never reaches the expansion at all, and so goes out as\n * its raw template — `{{item.*}}` tokens and all — where the author put a list.\n */\nexport function hasRepeatableNodes(\n nodes: Record<NodeId, unknown> | null | undefined,\n): boolean {\n if (!nodes) return false\n return Object.values(nodes).some((node) => repeatKey(node) !== '')\n}\n\n/**\n * Every key this tree repeats over, exactly as {@link expandRepeatables} looks\n * it up — sorted and without repeats.\n *\n * What the tenant compose asks the repeat-rows contract for\n * (`plugin-manager/repeat-rows.ts`), so a page loads the rows it renders and\n * not everything its site may see. Built on the same predicate as\n * {@link hasRepeatableNodes} for the reason given there.\n */\nexport function repeatKeys(\n nodes: Record<NodeId, unknown> | null | undefined,\n): string[] {\n const keys = new Set<string>()\n for (const node of Object.values(nodes ?? {})) {\n const key = repeatKey(node)\n if (key) keys.add(key)\n }\n return [...keys].sort()\n}\n\n/**\n * Repeats (AGL-103, AGL-3111): any node carrying `props.repeatDataset` (a\n * dataset id or display name), or `props.repeatConnection` (a plugin\n * connection's synced record, AGL-4212), renders once per record, with\n * `{{item.field}}` tokens in the copied string props replaced by the record's\n * values. A field the record leaves empty prints nothing — never the raw\n * token — and an element whose whole text is such a binding is left out of\n * that copy (AGL-3616: a tour date with no venue drew `{{ITEM.VENUE}}` as its\n * eyebrow on a published site). The besigner's canvas keeps the tokens of\n * the template an author edits ({@link substituteRecordTokens}).\n *\n * What is copied is the node's {@link repeatScope}:\n *\n * - `children` — its children are the item template. The node stays, and its\n * child list becomes the copies, record by record. Its own props are not the\n * template, so no token in them is substituted.\n * - `self` — the node and everything inside it are the template. The copies\n * take the node's place in its parent's child list, and every prop in the\n * subtree is substituted, the node's own included.\n *\n * - Copy ids are namespaced `rep__{repeatId}__{index}__…` — the repeat's own\n * id, then the template node's — so repeats never collide, including inside\n * grafted reusable components. A self-scoped node's first copy is\n * `rep__{id}__0__{id}`. Run this AFTER `composeReusableComponentNodes` and\n * BEFORE binding resolution.\n * - Rows are the node's {@link repeatedRecords}, looked up under its\n * {@link repeatKey}.\n * - An element of a copy whose `hideIf` / `hideUnless` is bound to a\n * `{{item.*}}` token is left out of that copy, with everything inside it,\n * when the record's value says so (AGL-4212).\n * - The repeat directives ({@link REPEAT_DIRECTIVE_PROPS}) are consumed: every\n * node this expands, and every copy it makes, comes out without them.\n * - Repeats do not nest. A repeat inside another repeat's template is copied\n * with its directives consumed, so it renders once in each copy.\n * - No rows renders ZERO copies (AGL-3496): a `children` repeat keeps its\n * element with an empty child list, a `self` repeat leaves its parent's\n * list. That covers a filter matching nothing, an empty dataset, and a key\n * the rows answer nothing under — a deleted or unshared dataset, or no rows\n * map at all — because the template drawn without a record is its literal\n * `{{item.*}}` tokens, printed to every visitor. Never a throw: a dataset\n * going away empties a list, it does not take the page down.\n * - An empty template, or a self-scoped node its parent does not list (the\n * document root, say), has nothing to copy or nowhere to put copies, and is\n * left as written.\n * - Inputs are never mutated; templates stay in the map unreferenced.\n *\n * This is the PUBLISHED page's composition. The besigner's canvas keeps the\n * template on screen whatever the rows say — it is what an author edits — and\n * flags a repeat with no rows on its badge instead ({@link repeatedRecords}\n * is the count both read).\n */\nexport function expandRepeatables<N extends AglynNodeSchema = AglynNodeSchema>(\n nodes: Record<NodeId, N>,\n datasetsByKey: Record<string, RepeatableDataset | undefined> | undefined,\n): Record<NodeId, N> {\n const rowsByKey = datasetsByKey ?? {}\n const repeatIds = Object.entries(nodes).filter(\n ([, node]) => repeatKey(node) !== '',\n )\n if (!repeatIds.length) return nodes\n\n const next: Record<NodeId, N> = { ...nodes }\n for (const [repeatId, repeated] of repeatIds) {\n const dataset = rowsByKey[repeatKey(repeated)]\n const records = repeatedRecords(repeated, dataset)\n const self = repeatScope(repeated) === 'self'\n // The copies' parent: the node itself, or — for a self-scoped node — the\n // parent whose child list the copies take its place in, read from `next`\n // so two self-scoped siblings both land in the list the other has left.\n const parentId = (self ? repeated.parentId : repeatId) as NodeId\n const siblings = next[parentId]?.nodes\n const slot = Array.isArray(siblings)\n ? (siblings as NodeId[]).indexOf(repeatId)\n : -1\n const templateIds = self\n ? [repeatId]\n : Array.isArray(repeated.nodes)\n ? (repeated.nodes as NodeId[])\n : []\n next[repeatId] = withoutRepeatDirective(next[repeatId])\n if (!templateIds.length || (self && slot < 0)) continue\n if (!records.length) {\n // Zero copies (AGL-3496). The template is a design, not content: drawn\n // without a record it prints `{{item.name}}` to every visitor.\n if (self) {\n const listed = [...(next[parentId].nodes as NodeId[])]\n listed.splice(slot, 1)\n next[parentId] = { ...next[parentId], nodes: listed }\n } else {\n next[repeatId] = { ...next[repeatId], nodes: [] }\n }\n continue\n }\n\n const copyIds: NodeId[] = []\n records.forEach((record, index) => {\n const prefix = `${REPEAT_NODE_ID_PREFIX}${repeatId}__${index}__`\n const prefixId = (id: NodeId) => `${prefix}${id}`\n // Whether the copy drew the node: an element whose whole text is a\n // binding this record leaves empty is left out of it (AGL-3616).\n const cloneSubtree = (id: NodeId, clonedParentId: NodeId): boolean => {\n const node = nodes[id]\n if (!node) return false\n const props = substituteValue(node.props ?? {}, {\n record,\n model: dataset?.model,\n datasetsByKey: rowsByKey,\n missing: 'empty',\n }) as Record<string, unknown>\n const template = node.props as Record<string, unknown> | undefined\n if (\n isEmptyBinding(template, props) ||\n isHiddenByRecord(template, props)\n ) {\n return false\n }\n // Read, so not carried: a copy is drawn or left out, and the\n // directive that decided it has nothing left to say.\n for (const prop of [NODE_HIDE_IF_PROP, NODE_HIDE_UNLESS_PROP]) {\n const bound = template?.[prop]\n if (typeof bound === 'string' && namesItemToken(bound)) {\n delete props[prop]\n }\n }\n const clonedChildren = Array.isArray(node.nodes)\n ? (node.nodes as NodeId[])\n : undefined\n const drawn = clonedChildren?.filter((childId) =>\n cloneSubtree(childId, prefixId(id)),\n )\n next[prefixId(id)] = withoutRepeatDirective({\n ...node,\n $id: prefixId(id),\n parentId: clonedParentId,\n props: props as any,\n ...(drawn && {\n nodes: drawn.map((childId) => prefixId(childId)),\n }),\n })\n return true\n }\n for (const templateId of templateIds) {\n if (cloneSubtree(templateId, parentId)) {\n copyIds.push(prefixId(templateId))\n }\n }\n })\n if (self) {\n const listed = [...(next[parentId].nodes as NodeId[])]\n listed.splice(slot, 1, ...copyIds)\n next[parentId] = { ...next[parentId], nodes: listed }\n } else {\n next[repeatId] = { ...next[repeatId], nodes: copyIds }\n }\n }\n return next\n}\n\nexport default expandRepeatables\n"],"names":["applyRepeatQuery","parseRepeatFilter","parseRepeatSort","NODE_HIDE_IF_PROP","NODE_HIDE_UNLESS_PROP","readYesNoValue","REPEAT_NODE_ID_PREFIX","ITEM_TOKEN_PATTERN","REPEAT_MAX_RECORDS","plainObjectPart","value","key","Array","isArray","Object","prototype","hasOwnProperty","call","part","String","displayValue","join","resolveReferenceHop","context","fieldId","targetFieldId","targetKey","model","references","target","datasetsByKey","keys","record","ids","resolved","map","id","match","records","find","row","filter","length","substituteValue","unresolved","token","missing","replace","field","hop","entry","next","entries","WHOLE_BINDING","RegExp","source","isEmptyBinding","template","substituted","some","prop","text","test","printed","trim","ITEM_TOKEN_ANYWHERE","namesItemToken","isHiddenByRecord","reads","hiddenWhen","bound","REPEAT_CONNECTION_PROP","REPEAT_CONNECTION_KEY_PREFIX","repeatKey","node","props","dataset","connection","REPEAT_SELF_PROP","REPEAT_DIRECTIVE_PROPS","repeatScope","nodes","self","substituteRecordTokens","substituteNodesRecordTokens","scope","substituteRepeatFilterRecordTokens","includes","repeatFilter","withoutRepeatDirective","kept","repeatedRecords","where","orderBy","limit","Number","slice","isFinite","Math","min","hasRepeatableNodes","values","repeatKeys","Set","add","sort","expandRepeatables","rowsByKey","repeatIds","repeatId","repeated","parentId","siblings","slot","indexOf","templateIds","listed","splice","copyIds","forEach","index","prefix","prefixId","cloneSubtree","clonedParentId","clonedChildren","undefined","drawn","childId","$id","templateId","push"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,gBAAgB,EAChBC,iBAAiB,E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;YACtDmC,OAAOC,MAAM,CAACJ,MAAM,MAAMK;YAC1BnE,IAAI,CAAC4D,SAAS,GAAG,aAAK5D,IAAI,CAAC4D,SAAS;gBAAE9B,OAAOmC;;QAC/C,OAAO;YACLjE,IAAI,CAAC0D,SAAS,GAAG,aAAK1D,IAAI,CAAC0D,SAAS;gBAAE5B,OAAOqC;;QAC/C;IACF;IACA,OAAOnE;AACT;AAEA,eAAeuD,kBAAiB"}
|
|
@@ -32,8 +32,10 @@ export declare function nativeAppAssociationRoute(pathname: string): string | nu
|
|
|
32
32
|
* auth session opens them for the app, and a universal link there would loop
|
|
33
33
|
* back into the app), the native hand-off and other `/auth` pages, the
|
|
34
34
|
* sign-out page, the site admin bar's connect page, a plugin's public
|
|
35
|
-
* device pages
|
|
36
|
-
* by someone with no account)
|
|
35
|
+
* device pages, a site's photo link (`/p/<linkId>`, opened on a phone
|
|
36
|
+
* by someone with no account) and the connector consent page
|
|
37
|
+
* (`/oauth/authorize`, AGL-4225), which an app such as Claude opens in the
|
|
38
|
+
* browser and expects to finish there. The sections the apps finish natively are
|
|
37
39
|
* {@link NATIVE_AUTH_LINK_SEGMENTS}.
|
|
38
40
|
*
|
|
39
41
|
* The rest of the console's top-level sections (`admin`, `billing`,
|
|
@@ -52,8 +52,10 @@
|
|
|
52
52
|
* auth session opens them for the app, and a universal link there would loop
|
|
53
53
|
* back into the app), the native hand-off and other `/auth` pages, the
|
|
54
54
|
* sign-out page, the site admin bar's connect page, a plugin's public
|
|
55
|
-
* device pages
|
|
56
|
-
* by someone with no account)
|
|
55
|
+
* device pages, a site's photo link (`/p/<linkId>`, opened on a phone
|
|
56
|
+
* by someone with no account) and the connector consent page
|
|
57
|
+
* (`/oauth/authorize`, AGL-4225), which an app such as Claude opens in the
|
|
58
|
+
* browser and expects to finish there. The sections the apps finish natively are
|
|
57
59
|
* {@link NATIVE_AUTH_LINK_SEGMENTS}.
|
|
58
60
|
*
|
|
59
61
|
* The rest of the console's top-level sections (`admin`, `billing`,
|
|
@@ -66,6 +68,7 @@
|
|
|
66
68
|
'auth',
|
|
67
69
|
'edit-access',
|
|
68
70
|
'kiosk',
|
|
71
|
+
'oauth',
|
|
69
72
|
'p',
|
|
70
73
|
'signin',
|
|
71
74
|
'signout',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/native-app-association.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE DOCUMENTS THAT TIE THE NATIVE APPS TO A DOMAIN (AGL-3817).\n *\n * Apple's `apple-app-site-association` and Google's `assetlinks.json` are how\n * a domain says which apps may use its passkeys (`webcredentials`,\n * `get_login_creds`) and open its links (`applinks`, `handle_all_urls`). Both\n * are fetched by the platform's verifier, not by a person, so each has to be\n * exactly `application/json`, a 200, no redirect and no cookie.\n *\n * Everything that names an app comes from the environment, never from here:\n *\n * - `NATIVE_APPLE_APP_IDS`: comma-separated `<team id>.<bundle id>` values,\n * in the order the system should prefer them;\n * - `NATIVE_ANDROID_APPS`: `;`-separated `<package>=<sha256>,<sha256>`\n * entries, each fingerprint the colon-separated hex Play Console prints.\n *\n * Unset (or nothing valid in it), the document answers 404: a deployment\n * with no apps of its own vouches for none.\n *\n * A leaf with no imports, because both middlewares read the paths below.\n *=========================================*/\n\n/** Where Apple's verifier reads the association file: no `.json` suffix. */\nexport const APPLE_APP_SITE_ASSOCIATION_PATH = '/.well-known/apple-app-site-association'\n\n/** Where Google's verifier reads the statement list. */\nexport const ASSET_LINKS_PATH = '/.well-known/assetlinks.json'\n\n/**\n * The route handlers each middleware rewrites the two public paths to. They\n * live under `/api` because both apps keep their route handlers there, and\n * neither middleware runs again on `/api`.\n */\nexport const NATIVE_APP_ASSOCIATION_ROUTES: Readonly<Record<string, string>> = {\n [APPLE_APP_SITE_ASSOCIATION_PATH]: '/api/native-app-association/apple-app-site-association',\n [ASSET_LINKS_PATH]: '/api/native-app-association/assetlinks',\n}\n\n/** The route handler a public association path is served by, or null. */\nexport function nativeAppAssociationRoute(pathname: string): string | null {\n return Object.prototype.hasOwnProperty.call(NATIVE_APP_ASSOCIATION_ROUTES, pathname)\n ? NATIVE_APP_ASSOCIATION_ROUTES[pathname]\n : null\n}\n\n/**\n * The console's top-level sections the native apps have no screen for, so a\n * link to one stays in the browser: the sign-in page and SSO (the system\n * auth session opens them for the app, and a universal link there would loop\n * back into the app), the native hand-off and other `/auth` pages, the\n * sign-out page, the site admin bar's connect page, a plugin's public\n * device pages and a site's photo link (`/p/<linkId>`, opened on a phone\n * by someone with no account). The sections the apps finish natively are\n * {@link NATIVE_AUTH_LINK_SEGMENTS}.\n *\n * The rest of the console's top-level sections (`admin`, `billing`,\n * `manage`, `support`) and every workspace path are what the native\n * deep-link grammar resolves (`DeepLinks.swift`, `DeepLinks.kt`): a\n * registered screen, the Besigner in the app's own web view, or the nearest\n * native screen. `apps/console/specs/native-app-association.spec.ts` holds\n * this list to the console's route set and the native link specs.\n */\nexport const NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS: readonly string[] = [\n 'auth',\n 'edit-access',\n 'kiosk',\n 'p',\n 'signin',\n 'signout',\n 'sso',\n]\n\n/**\n * The pre-sign-in sections whose exact page the apps finish natively: sign-up\n * (with its `?plan=`), an emailed verification link, an emailed password\n * reset and account recovery (`AuthFlow.swift`; Android's console intent\n * filter lists the same four paths). Only the page itself opens the app;\n * anything under it stays in the browser, where the console handles it.\n */\nexport const NATIVE_AUTH_LINK_SEGMENTS: readonly string[] = [\n 'account-recovery',\n 'reset-password',\n 'signup',\n 'verify-email',\n]\n\n/** One `applinks` component: a URL path pattern, optionally excluded. */\nexport interface AppLinksComponent {\n '/': string\n exclude?: true\n comment?: string\n}\n\n/**\n * The console paths the apps open, as `applinks` components. Apple reads\n * them in order and the first match wins, so every exclusion comes ahead of\n * the closing catch-all.\n */\nexport function consoleAppLinksComponents(): AppLinksComponent[] {\n const excluded: AppLinksComponent[] = [\n { '/': '/_*', exclude: true, comment: 'framework and internal paths' },\n { '/': '/api', exclude: true },\n { '/': '/api/*', exclude: true, comment: 'route handlers' },\n { '/': '/.well-known/*', exclude: true },\n ]\n for (const segment of NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS) {\n excluded.push({ '/': `/${segment}`, exclude: true }, { '/': `/${segment}/*`, exclude: true })\n }\n for (const segment of NATIVE_AUTH_LINK_SEGMENTS) {\n excluded.push({ '/': `/${segment}/*`, exclude: true })\n }\n return [\n ...excluded,\n { '/': '/*', comment: 'workspace, site, account, billing, support and staff pages' },\n ]\n}\n\n/** `TEAMID1234.com.example.app`: a 10-character team id, then a bundle id. */\nconst APPLE_APP_ID = /^[A-Z0-9]{10}\\.[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/\n\n/** A Java package name: dot-separated identifiers, at least two. */\nconst ANDROID_PACKAGE = /^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$/\n\n/** A SHA-256 certificate fingerprint as 32 colon-separated hex pairs. */\nconst SHA256_FINGERPRINT = /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/\n\n/** The Apple app ids in `NATIVE_APPLE_APP_IDS`, in order; invalid ones dropped. */\nexport function parseAppleAppIds(raw: string | undefined): string[] {\n const ids = (raw ?? '')\n .split(',')\n .map((value) => value.trim())\n .filter((value) => APPLE_APP_ID.test(value))\n return [...new Set(ids)]\n}\n\n/** One Android app and the signing certificates it may be verified by. */\nexport interface AndroidAppAssociation {\n packageName: string\n sha256Fingerprints: string[]\n}\n\n/**\n * The Android apps in `NATIVE_ANDROID_APPS`. An entry without a valid package\n * or without one valid fingerprint is dropped whole: a statement with no\n * certificate verifies nothing.\n */\nexport function parseAndroidApps(raw: string | undefined): AndroidAppAssociation[] {\n const apps: AndroidAppAssociation[] = []\n for (const entry of (raw ?? '').split(';')) {\n const at = entry.indexOf('=')\n if (at < 0) continue\n const packageName = entry.slice(0, at).trim()\n if (!ANDROID_PACKAGE.test(packageName)) continue\n if (apps.some((app) => app.packageName === packageName)) continue\n const fingerprints = entry\n .slice(at + 1)\n .split(',')\n .map((value) => value.trim().toUpperCase())\n .filter((value) => SHA256_FINGERPRINT.test(value))\n if (fingerprints.length === 0) continue\n apps.push({ packageName, sha256Fingerprints: [...new Set(fingerprints)] })\n }\n return apps\n}\n\n/** The `apple-app-site-association` document Apple's CDN reads. */\nexport interface AppleAppSiteAssociation {\n applinks?: {\n apps: []\n details: Array<{ appIDs: string[]; components: AppLinksComponent[] }>\n }\n webcredentials: { apps: string[] }\n}\n\n/**\n * The association file for these app ids. `applinks` is only for a host\n * whose paths the native deep-link grammar resolves: the console. A host\n * that serves the passkey relying party alone gets `webcredentials` only.\n *\n * One `details` entry per app, in the configured order, because when two\n * installed apps claim the same path the system takes the first.\n */\nexport function appleAppSiteAssociation(\n appIds: string[],\n options: { applinks: boolean },\n): AppleAppSiteAssociation {\n const document: AppleAppSiteAssociation = { webcredentials: { apps: [...appIds] } }\n if (options.applinks) {\n const components = consoleAppLinksComponents()\n document.applinks = {\n apps: [],\n details: appIds.map((appId) => ({ appIDs: [appId], components })),\n }\n }\n return document\n}\n\n/** One Digital Asset Links statement. */\nexport interface AssetLinkStatement {\n relation: string[]\n target: { namespace: 'android_app'; package_name: string; sha256_cert_fingerprints: string[] }\n}\n\n/** Passkeys and app links, for every configured app. */\nexport const ASSET_LINK_RELATIONS = [\n 'delegate_permission/common.handle_all_urls',\n 'delegate_permission/common.get_login_creds',\n] as const\n\n/** The `assetlinks.json` statement list Google's verifier reads. */\nexport function assetLinks(apps: AndroidAppAssociation[]): AssetLinkStatement[] {\n return apps.map((app) => ({\n relation: [...ASSET_LINK_RELATIONS],\n target: {\n namespace: 'android_app',\n package_name: app.packageName,\n sha256_cert_fingerprints: [...app.sha256Fingerprints],\n },\n }))\n}\n\n/** The request's hostname: lowercase, no port. */\nexport function requestHostname(host: string | null | undefined): string {\n return (host ?? '').trim().toLowerCase().replace(/:\\d+$/, '')\n}\n\n/** A URL's hostname, or null when it is not one. */\nexport function hostnameOfUrl(url: string | null | undefined): string | null {\n if (!url) return null\n try {\n return new URL(url).hostname.toLowerCase() || null\n } catch {\n return null\n }\n}\n\n/** What a route handler needs to answer one of the two documents. */\nexport interface NativeAppAssociationRequest {\n /** The request's `Host` header. */\n host: string | null\n /**\n * The hostnames this deployment vouches for. Every other host an app\n * serves (a customer's custom domain, a workspace subdomain, a white-label\n * console) answers 404, because the apps are this deployment's and not\n * theirs.\n */\n servedHosts: ReadonlyArray<string | null | undefined>\n /** Whether this host's paths are console links the apps resolve. */\n applinks: boolean\n /** The environment; `process.env` in the routes, a fixture in specs. */\n env: Readonly<Record<string, string | undefined>>\n}\n\n/** Short on purpose: Apple's CDN caches on top, and a fix must land within minutes. */\nconst CACHE_CONTROL = 'public, max-age=300, s-maxage=300'\n\n/**\n * Whether this host may answer. A Vercel preview deployment is reachable only\n * at the platform's own generated hostnames, so it answers on any host, which\n * is what lets a preview be checked before it is promoted.\n */\nfunction servesHost(request: NativeAppAssociationRequest): boolean {\n if (request.env['VERCEL_ENV'] === 'preview') return true\n const hostname = requestHostname(request.host)\n if (!hostname) return false\n return request.servedHosts.some((served) => requestHostname(served) === hostname)\n}\n\nfunction notFound(): Response {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': CACHE_CONTROL },\n })\n}\n\nfunction json(body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status: 200,\n headers: { 'content-type': 'application/json', 'cache-control': CACHE_CONTROL },\n })\n}\n\n/** `GET /.well-known/apple-app-site-association`. */\nexport function appleAppSiteAssociationResponse(request: NativeAppAssociationRequest): Response {\n const appIds = parseAppleAppIds(request.env['NATIVE_APPLE_APP_IDS'])\n if (appIds.length === 0 || !servesHost(request)) return notFound()\n return json(appleAppSiteAssociation(appIds, { applinks: request.applinks }))\n}\n\n/** `GET /.well-known/assetlinks.json`. */\nexport function assetLinksResponse(request: NativeAppAssociationRequest): Response {\n const apps = parseAndroidApps(request.env['NATIVE_ANDROID_APPS'])\n if (apps.length === 0 || !servesHost(request)) return notFound()\n return json(assetLinks(apps))\n}\n"],"names":["APPLE_APP_SITE_ASSOCIATION_PATH","ASSET_LINKS_PATH","NATIVE_APP_ASSOCIATION_ROUTES","nativeAppAssociationRoute","pathname","Object","prototype","hasOwnProperty","call","NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS","NATIVE_AUTH_LINK_SEGMENTS","consoleAppLinksComponents","excluded","exclude","comment","segment","push","APPLE_APP_ID","ANDROID_PACKAGE","SHA256_FINGERPRINT","parseAppleAppIds","raw","ids","split","map","value","trim","filter","test","Set","parseAndroidApps","apps","entry","at","indexOf","packageName","slice","some","app","fingerprints","toUpperCase","length","sha256Fingerprints","appleAppSiteAssociation","appIds","options","document","webcredentials","applinks","components","details","appId","appIDs","ASSET_LINK_RELATIONS","assetLinks","relation","target","namespace","package_name","sha256_cert_fingerprints","requestHostname","host","toLowerCase","replace","hostnameOfUrl","url","URL","hostname","CACHE_CONTROL","servesHost","request","env","servedHosts","served","notFound","Response","status","headers","json","body","JSON","stringify","appleAppSiteAssociationResponse","assetLinksResponse"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,0EAA0E,GAC1E,OAAO,MAAMA,kCAAkC,0CAAyC;AAExF,sDAAsD,GACtD,OAAO,MAAMC,mBAAmB,+BAA8B;AAE9D;;;;CAIC,GACD,OAAO,MAAMC,gCAAkE;IAC7E,CAACF,gCAAgC,EAAE;IACnC,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CAAgCZ,OAAoC;IAClF,MAAM1B,SAASxB,iBAAiBkD,QAAQC,GAAG,CAAC,uBAAuB;IACnE,IAAI3B,OAAOH,MAAM,KAAK,KAAK,CAAC4B,WAAWC,UAAU,OAAOI;IACxD,OAAOI,KAAKnC,wBAAwBC,QAAQ;QAAEI,UAAUsB,QAAQtB,QAAQ;IAAC;AAC3E;AAEA,wCAAwC,GACxC,OAAO,SAASmC,mBAAmBb,OAAoC;IACrE,MAAMvC,OAAOD,iBAAiBwC,QAAQC,GAAG,CAAC,sBAAsB;IAChE,IAAIxC,KAAKU,MAAM,KAAK,KAAK,CAAC4B,WAAWC,UAAU,OAAOI;IACtD,OAAOI,KAAKxB,WAAWvB;AACzB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/native-app-association.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE DOCUMENTS THAT TIE THE NATIVE APPS TO A DOMAIN (AGL-3817).\n *\n * Apple's `apple-app-site-association` and Google's `assetlinks.json` are how\n * a domain says which apps may use its passkeys (`webcredentials`,\n * `get_login_creds`) and open its links (`applinks`, `handle_all_urls`). Both\n * are fetched by the platform's verifier, not by a person, so each has to be\n * exactly `application/json`, a 200, no redirect and no cookie.\n *\n * Everything that names an app comes from the environment, never from here:\n *\n * - `NATIVE_APPLE_APP_IDS`: comma-separated `<team id>.<bundle id>` values,\n * in the order the system should prefer them;\n * - `NATIVE_ANDROID_APPS`: `;`-separated `<package>=<sha256>,<sha256>`\n * entries, each fingerprint the colon-separated hex Play Console prints.\n *\n * Unset (or nothing valid in it), the document answers 404: a deployment\n * with no apps of its own vouches for none.\n *\n * A leaf with no imports, because both middlewares read the paths below.\n *=========================================*/\n\n/** Where Apple's verifier reads the association file: no `.json` suffix. */\nexport const APPLE_APP_SITE_ASSOCIATION_PATH = '/.well-known/apple-app-site-association'\n\n/** Where Google's verifier reads the statement list. */\nexport const ASSET_LINKS_PATH = '/.well-known/assetlinks.json'\n\n/**\n * The route handlers each middleware rewrites the two public paths to. They\n * live under `/api` because both apps keep their route handlers there, and\n * neither middleware runs again on `/api`.\n */\nexport const NATIVE_APP_ASSOCIATION_ROUTES: Readonly<Record<string, string>> = {\n [APPLE_APP_SITE_ASSOCIATION_PATH]: '/api/native-app-association/apple-app-site-association',\n [ASSET_LINKS_PATH]: '/api/native-app-association/assetlinks',\n}\n\n/** The route handler a public association path is served by, or null. */\nexport function nativeAppAssociationRoute(pathname: string): string | null {\n return Object.prototype.hasOwnProperty.call(NATIVE_APP_ASSOCIATION_ROUTES, pathname)\n ? NATIVE_APP_ASSOCIATION_ROUTES[pathname]\n : null\n}\n\n/**\n * The console's top-level sections the native apps have no screen for, so a\n * link to one stays in the browser: the sign-in page and SSO (the system\n * auth session opens them for the app, and a universal link there would loop\n * back into the app), the native hand-off and other `/auth` pages, the\n * sign-out page, the site admin bar's connect page, a plugin's public\n * device pages, a site's photo link (`/p/<linkId>`, opened on a phone\n * by someone with no account) and the connector consent page\n * (`/oauth/authorize`, AGL-4225), which an app such as Claude opens in the\n * browser and expects to finish there. The sections the apps finish natively are\n * {@link NATIVE_AUTH_LINK_SEGMENTS}.\n *\n * The rest of the console's top-level sections (`admin`, `billing`,\n * `manage`, `support`) and every workspace path are what the native\n * deep-link grammar resolves (`DeepLinks.swift`, `DeepLinks.kt`): a\n * registered screen, the Besigner in the app's own web view, or the nearest\n * native screen. `apps/console/specs/native-app-association.spec.ts` holds\n * this list to the console's route set and the native link specs.\n */\nexport const NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS: readonly string[] = [\n 'auth',\n 'edit-access',\n 'kiosk',\n 'oauth',\n 'p',\n 'signin',\n 'signout',\n 'sso',\n]\n\n/**\n * The pre-sign-in sections whose exact page the apps finish natively: sign-up\n * (with its `?plan=`), an emailed verification link, an emailed password\n * reset and account recovery (`AuthFlow.swift`; Android's console intent\n * filter lists the same four paths). Only the page itself opens the app;\n * anything under it stays in the browser, where the console handles it.\n */\nexport const NATIVE_AUTH_LINK_SEGMENTS: readonly string[] = [\n 'account-recovery',\n 'reset-password',\n 'signup',\n 'verify-email',\n]\n\n/** One `applinks` component: a URL path pattern, optionally excluded. */\nexport interface AppLinksComponent {\n '/': string\n exclude?: true\n comment?: string\n}\n\n/**\n * The console paths the apps open, as `applinks` components. Apple reads\n * them in order and the first match wins, so every exclusion comes ahead of\n * the closing catch-all.\n */\nexport function consoleAppLinksComponents(): AppLinksComponent[] {\n const excluded: AppLinksComponent[] = [\n { '/': '/_*', exclude: true, comment: 'framework and internal paths' },\n { '/': '/api', exclude: true },\n { '/': '/api/*', exclude: true, comment: 'route handlers' },\n { '/': '/.well-known/*', exclude: true },\n ]\n for (const segment of NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS) {\n excluded.push({ '/': `/${segment}`, exclude: true }, { '/': `/${segment}/*`, exclude: true })\n }\n for (const segment of NATIVE_AUTH_LINK_SEGMENTS) {\n excluded.push({ '/': `/${segment}/*`, exclude: true })\n }\n return [\n ...excluded,\n { '/': '/*', comment: 'workspace, site, account, billing, support and staff pages' },\n ]\n}\n\n/** `TEAMID1234.com.example.app`: a 10-character team id, then a bundle id. */\nconst APPLE_APP_ID = /^[A-Z0-9]{10}\\.[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/\n\n/** A Java package name: dot-separated identifiers, at least two. */\nconst ANDROID_PACKAGE = /^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$/\n\n/** A SHA-256 certificate fingerprint as 32 colon-separated hex pairs. */\nconst SHA256_FINGERPRINT = /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/\n\n/** The Apple app ids in `NATIVE_APPLE_APP_IDS`, in order; invalid ones dropped. */\nexport function parseAppleAppIds(raw: string | undefined): string[] {\n const ids = (raw ?? '')\n .split(',')\n .map((value) => value.trim())\n .filter((value) => APPLE_APP_ID.test(value))\n return [...new Set(ids)]\n}\n\n/** One Android app and the signing certificates it may be verified by. */\nexport interface AndroidAppAssociation {\n packageName: string\n sha256Fingerprints: string[]\n}\n\n/**\n * The Android apps in `NATIVE_ANDROID_APPS`. An entry without a valid package\n * or without one valid fingerprint is dropped whole: a statement with no\n * certificate verifies nothing.\n */\nexport function parseAndroidApps(raw: string | undefined): AndroidAppAssociation[] {\n const apps: AndroidAppAssociation[] = []\n for (const entry of (raw ?? '').split(';')) {\n const at = entry.indexOf('=')\n if (at < 0) continue\n const packageName = entry.slice(0, at).trim()\n if (!ANDROID_PACKAGE.test(packageName)) continue\n if (apps.some((app) => app.packageName === packageName)) continue\n const fingerprints = entry\n .slice(at + 1)\n .split(',')\n .map((value) => value.trim().toUpperCase())\n .filter((value) => SHA256_FINGERPRINT.test(value))\n if (fingerprints.length === 0) continue\n apps.push({ packageName, sha256Fingerprints: [...new Set(fingerprints)] })\n }\n return apps\n}\n\n/** The `apple-app-site-association` document Apple's CDN reads. */\nexport interface AppleAppSiteAssociation {\n applinks?: {\n apps: []\n details: Array<{ appIDs: string[]; components: AppLinksComponent[] }>\n }\n webcredentials: { apps: string[] }\n}\n\n/**\n * The association file for these app ids. `applinks` is only for a host\n * whose paths the native deep-link grammar resolves: the console. A host\n * that serves the passkey relying party alone gets `webcredentials` only.\n *\n * One `details` entry per app, in the configured order, because when two\n * installed apps claim the same path the system takes the first.\n */\nexport function appleAppSiteAssociation(\n appIds: string[],\n options: { applinks: boolean },\n): AppleAppSiteAssociation {\n const document: AppleAppSiteAssociation = { webcredentials: { apps: [...appIds] } }\n if (options.applinks) {\n const components = consoleAppLinksComponents()\n document.applinks = {\n apps: [],\n details: appIds.map((appId) => ({ appIDs: [appId], components })),\n }\n }\n return document\n}\n\n/** One Digital Asset Links statement. */\nexport interface AssetLinkStatement {\n relation: string[]\n target: { namespace: 'android_app'; package_name: string; sha256_cert_fingerprints: string[] }\n}\n\n/** Passkeys and app links, for every configured app. */\nexport const ASSET_LINK_RELATIONS = [\n 'delegate_permission/common.handle_all_urls',\n 'delegate_permission/common.get_login_creds',\n] as const\n\n/** The `assetlinks.json` statement list Google's verifier reads. */\nexport function assetLinks(apps: AndroidAppAssociation[]): AssetLinkStatement[] {\n return apps.map((app) => ({\n relation: [...ASSET_LINK_RELATIONS],\n target: {\n namespace: 'android_app',\n package_name: app.packageName,\n sha256_cert_fingerprints: [...app.sha256Fingerprints],\n },\n }))\n}\n\n/** The request's hostname: lowercase, no port. */\nexport function requestHostname(host: string | null | undefined): string {\n return (host ?? '').trim().toLowerCase().replace(/:\\d+$/, '')\n}\n\n/** A URL's hostname, or null when it is not one. */\nexport function hostnameOfUrl(url: string | null | undefined): string | null {\n if (!url) return null\n try {\n return new URL(url).hostname.toLowerCase() || null\n } catch {\n return null\n }\n}\n\n/** What a route handler needs to answer one of the two documents. */\nexport interface NativeAppAssociationRequest {\n /** The request's `Host` header. */\n host: string | null\n /**\n * The hostnames this deployment vouches for. Every other host an app\n * serves (a customer's custom domain, a workspace subdomain, a white-label\n * console) answers 404, because the apps are this deployment's and not\n * theirs.\n */\n servedHosts: ReadonlyArray<string | null | undefined>\n /** Whether this host's paths are console links the apps resolve. */\n applinks: boolean\n /** The environment; `process.env` in the routes, a fixture in specs. */\n env: Readonly<Record<string, string | undefined>>\n}\n\n/** Short on purpose: Apple's CDN caches on top, and a fix must land within minutes. */\nconst CACHE_CONTROL = 'public, max-age=300, s-maxage=300'\n\n/**\n * Whether this host may answer. A Vercel preview deployment is reachable only\n * at the platform's own generated hostnames, so it answers on any host, which\n * is what lets a preview be checked before it is promoted.\n */\nfunction servesHost(request: NativeAppAssociationRequest): boolean {\n if (request.env['VERCEL_ENV'] === 'preview') return true\n const hostname = requestHostname(request.host)\n if (!hostname) return false\n return request.servedHosts.some((served) => requestHostname(served) === hostname)\n}\n\nfunction notFound(): Response {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': CACHE_CONTROL },\n })\n}\n\nfunction json(body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status: 200,\n headers: { 'content-type': 'application/json', 'cache-control': CACHE_CONTROL },\n })\n}\n\n/** `GET /.well-known/apple-app-site-association`. */\nexport function appleAppSiteAssociationResponse(request: NativeAppAssociationRequest): Response {\n const appIds = parseAppleAppIds(request.env['NATIVE_APPLE_APP_IDS'])\n if (appIds.length === 0 || !servesHost(request)) return notFound()\n return json(appleAppSiteAssociation(appIds, { applinks: request.applinks }))\n}\n\n/** `GET /.well-known/assetlinks.json`. */\nexport function assetLinksResponse(request: NativeAppAssociationRequest): Response {\n const apps = parseAndroidApps(request.env['NATIVE_ANDROID_APPS'])\n if (apps.length === 0 || !servesHost(request)) return notFound()\n return json(assetLinks(apps))\n}\n"],"names":["APPLE_APP_SITE_ASSOCIATION_PATH","ASSET_LINKS_PATH","NATIVE_APP_ASSOCIATION_ROUTES","nativeAppAssociationRoute","pathname","Object","prototype","hasOwnProperty","call","NATIVE_WEB_ONLY_TOP_LEVEL_SEGMENTS","NATIVE_AUTH_LINK_SEGMENTS","consoleAppLinksComponents","excluded","exclude","comment","segment","push","APPLE_APP_ID","ANDROID_PACKAGE","SHA256_FINGERPRINT","parseAppleAppIds","raw","ids","split","map","value","trim","filter","test","Set","parseAndroidApps","apps","entry","at","indexOf","packageName","slice","some","app","fingerprints","toUpperCase","length","sha256Fingerprints","appleAppSiteAssociation","appIds","options","document","webcredentials","applinks","components","details","appId","appIDs","ASSET_LINK_RELATIONS","assetLinks","relation","target","namespace","package_name","sha256_cert_fingerprints","requestHostname","host","toLowerCase","replace","hostnameOfUrl","url","URL","hostname","CACHE_CONTROL","servesHost","request","env","servedHosts","served","notFound","Response","status","headers","json","body","JSON","stringify","appleAppSiteAssociationResponse","assetLinksResponse"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,0EAA0E,GAC1E,OAAO,MAAMA,kCAAkC,0CAAyC;AAExF,sDAAsD,GACtD,OAAO,MAAMC,mBAAmB,+BAA8B;AAE9D;;;;CAIC,GACD,OAAO,MAAMC,gCAAkE;IAC7E,CAACF,gCAAgC,EAAE;IACnC,CAACC,iBAAiB,EAAE;AACtB,EAAC;AAED,uEAAuE,GACvE,OAAO,SAASE,0BAA0BC,QAAgB;IACxD,OAAOC,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACN,+BAA+BE,YACvEF,6BAA6B,CAACE,SAAS,GACvC;AACN;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMK,qCAAwD;IACnE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA+C;IAC1D;IACA;IACA;IACA;CACD,CAAA;AASD;;;;CAIC,GACD,OAAO,SAASC;IACd,MAAMC,WAAgC;QACpC;YAAE,KAAK;YAAOC,SAAS;YAAMC,SAAS;QAA+B;QACrE;YAAE,KAAK;YAAQD,SAAS;QAAK;QAC7B;YAAE,KAAK;YAAUA,SAAS;YAAMC,SAAS;QAAiB;QAC1D;YAAE,KAAK;YAAkBD,SAAS;QAAK;KACxC;IACD,KAAK,MAAME,WAAWN,mCAAoC;QACxDG,SAASI,IAAI,CAAC;YAAE,KAAK,CAAC,CAAC,EAAED,SAAS;YAAEF,SAAS;QAAK,GAAG;YAAE,KAAK,CAAC,CAAC,EAAEE,QAAQ,EAAE,CAAC;YAAEF,SAAS;QAAK;IAC7F;IACA,KAAK,MAAME,WAAWL,0BAA2B;QAC/CE,SAASI,IAAI,CAAC;YAAE,KAAK,CAAC,CAAC,EAAED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AC,CAACoC,SAAWb,gBAAgBa,YAAYN;AAC1E;AAEA,SAASO;IACP,OAAO,IAAIC,SAAS,aAAa;QAC/BC,QAAQ;QACRC,SAAS;YAAE,gBAAgB;YAA6B,iBAAiBT;QAAc;IACzF;AACF;AAEA,SAASU,KAAKC,IAAa;IACzB,OAAO,IAAIJ,SAASK,KAAKC,SAAS,CAACF,OAAO;QACxCH,QAAQ;QACRC,SAAS;YAAE,gBAAgB;YAAoB,iBAAiBT;QAAc;IAChF;AACF;AAEA,mDAAmD,GACnD,OAAO,SAASc,gCAAgCZ,OAAoC;IAClF,MAAM1B,SAASxB,iBAAiBkD,QAAQC,GAAG,CAAC,uBAAuB;IACnE,IAAI3B,OAAOH,MAAM,KAAK,KAAK,CAAC4B,WAAWC,UAAU,OAAOI;IACxD,OAAOI,KAAKnC,wBAAwBC,QAAQ;QAAEI,UAAUsB,QAAQtB,QAAQ;IAAC;AAC3E;AAEA,wCAAwC,GACxC,OAAO,SAASmC,mBAAmBb,OAAoC;IACrE,MAAMvC,OAAOD,iBAAiBwC,QAAQC,GAAG,CAAC,sBAAsB;IAChE,IAAIxC,KAAKU,MAAM,KAAK,KAAK,CAAC4B,WAAWC,UAAU,OAAOI;IACtD,OAAOI,KAAKxB,WAAWvB;AACzB"}
|
|
@@ -25,13 +25,15 @@ import { hostScopeToken, ORG_SCOPE_TOKEN, visibleToTokens } from "./scope-tokens
|
|
|
25
25
|
* Org workspace slugs ride the host reserved/profanity blocklist plus
|
|
26
26
|
* console-specific labels the workspace router must own. `kiosk` is the
|
|
27
27
|
* console's public device route (AGL-3608), which a static segment serves
|
|
28
|
-
* ahead of any workspace of that name
|
|
28
|
+
* ahead of any workspace of that name; `oauth` is the connector consent page
|
|
29
|
+
* (AGL-4225), the same way.
|
|
29
30
|
*/ const RESERVED_ORG_ONLY = new Set([
|
|
30
31
|
'staff',
|
|
31
32
|
'org',
|
|
32
33
|
'orgs',
|
|
33
34
|
'workspace',
|
|
34
|
-
'kiosk'
|
|
35
|
+
'kiosk',
|
|
36
|
+
'oauth'
|
|
35
37
|
]);
|
|
36
38
|
/**
|
|
37
39
|
* The label this deployment serves its own console on, when it has one
|