galley-cms 0.1.0 → 0.1.1
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/README.md +3 -3
- package/dist/galley.mjs +887 -425
- package/dist/starters/astro-editorial/README.md +3 -11
- package/dist/starters/astro-editorial/src/galley/catalog-data.js +1 -1
- package/dist/starters/astro-editorial/src/galley/catalog.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/attribution.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/forms.js +2 -2
- package/dist/starters/astro-editorial/src/galley/client/providers/frame-post.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/galley.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/hubspot.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/mailto.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/marketo.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/pardot.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/salesforce.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/providers/webhook.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/registry.js +1 -1
- package/dist/starters/astro-editorial/src/galley/client/types.d.ts +1 -1
- package/dist/starters/astro-editorial/src/galley/components/ConsentBanner.astro +1 -1
- package/dist/starters/astro-editorial/src/galley/components/Form.astro +1 -1
- package/dist/starters/astro-editorial/src/galley/components/Scripts.astro +1 -1
- package/dist/starters/astro-editorial/src/galley/components/index.js +1 -1
- package/dist/starters/astro-editorial/src/galley/forms/forms.css +1 -1
- package/dist/starters/astro-editorial/src/galley/forms/free-email-domains.js +1 -1
- package/dist/starters/astro-editorial/src/galley/forms/logic.js +1 -1
- package/dist/starters/astro-editorial/src/galley/forms/messages.js +1 -1
- package/dist/starters/astro-editorial/src/galley/forms/render.js +1 -1
- package/dist/starters/astro-editorial/src/galley/integration.js +1 -1
- package/dist/starters/astro-editorial/src/galley/kit.d.ts +1 -1
- package/dist/starters/astro-editorial/src/galley/mailto/config.js +1 -1
- package/dist/starters/astro-editorial/src/galley/mailto/runtime.gen.js +1 -1
- package/dist/starters/astro-editorial/src/galley/runtime/site-config.js +1 -1
- package/dist/starters/astro-editorial/src/galley/schema.js +1 -1
- package/dist/starters/astro-editorial/src/galley/scripts/banner.js +1 -1
- package/dist/starters/astro-editorial/src/galley/scripts/plan.js +1 -1
- package/dist/starters/astro-editorial/src/galley/scripts/runtime.gen.js +1 -1
- package/dist/starters/astro-editorial/src/galley/scripts/snippets.js +1 -1
- package/dist/starters/astro-editorial/src/galley/shared/glob.js +1 -1
- package/dist/starters/astro-editorial/src/galley/shared/markdown.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/config.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/content.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/crawlers.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/html.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/integration.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/markdown.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/page.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/site.js +1 -1
- package/dist/starters/astro-editorial/src/galley/visibility/structured.js +1 -1
- package/dist/starters/astro-saas/README.md +5 -7
- package/dist/starters/astro-saas/src/galley/catalog-data.js +1 -1
- package/dist/starters/astro-saas/src/galley/catalog.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/attribution.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/forms.js +2 -2
- package/dist/starters/astro-saas/src/galley/client/providers/frame-post.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/galley.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/hubspot.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/mailto.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/marketo.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/pardot.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/salesforce.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/providers/webhook.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/registry.js +1 -1
- package/dist/starters/astro-saas/src/galley/client/types.d.ts +1 -1
- package/dist/starters/astro-saas/src/galley/components/ConsentBanner.astro +1 -1
- package/dist/starters/astro-saas/src/galley/components/Form.astro +1 -1
- package/dist/starters/astro-saas/src/galley/components/Scripts.astro +1 -1
- package/dist/starters/astro-saas/src/galley/components/index.js +1 -1
- package/dist/starters/astro-saas/src/galley/forms/forms.css +1 -1
- package/dist/starters/astro-saas/src/galley/forms/free-email-domains.js +1 -1
- package/dist/starters/astro-saas/src/galley/forms/logic.js +1 -1
- package/dist/starters/astro-saas/src/galley/forms/messages.js +1 -1
- package/dist/starters/astro-saas/src/galley/forms/render.js +1 -1
- package/dist/starters/astro-saas/src/galley/integration.js +1 -1
- package/dist/starters/astro-saas/src/galley/kit.d.ts +1 -1
- package/dist/starters/astro-saas/src/galley/mailto/config.js +1 -1
- package/dist/starters/astro-saas/src/galley/mailto/runtime.gen.js +1 -1
- package/dist/starters/astro-saas/src/galley/runtime/site-config.js +1 -1
- package/dist/starters/astro-saas/src/galley/schema.js +1 -1
- package/dist/starters/astro-saas/src/galley/scripts/banner.js +1 -1
- package/dist/starters/astro-saas/src/galley/scripts/plan.js +1 -1
- package/dist/starters/astro-saas/src/galley/scripts/runtime.gen.js +1 -1
- package/dist/starters/astro-saas/src/galley/scripts/snippets.js +1 -1
- package/dist/starters/astro-saas/src/galley/shared/glob.js +1 -1
- package/dist/starters/astro-saas/src/galley/shared/markdown.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/config.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/content.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/crawlers.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/html.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/integration.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/markdown.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/page.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/site.js +1 -1
- package/dist/starters/astro-saas/src/galley/visibility/structured.js +1 -1
- package/dist/starters/astro-starter/README.md +5 -13
- package/dist/starters/astro-starter/src/galley/catalog-data.js +1 -1
- package/dist/starters/astro-starter/src/galley/catalog.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/attribution.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/forms.js +2 -2
- package/dist/starters/astro-starter/src/galley/client/providers/frame-post.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/galley.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/hubspot.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/mailto.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/marketo.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/pardot.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/salesforce.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/providers/webhook.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/registry.js +1 -1
- package/dist/starters/astro-starter/src/galley/client/types.d.ts +1 -1
- package/dist/starters/astro-starter/src/galley/components/ConsentBanner.astro +1 -1
- package/dist/starters/astro-starter/src/galley/components/Form.astro +1 -1
- package/dist/starters/astro-starter/src/galley/components/Scripts.astro +1 -1
- package/dist/starters/astro-starter/src/galley/components/index.js +1 -1
- package/dist/starters/astro-starter/src/galley/forms/forms.css +1 -1
- package/dist/starters/astro-starter/src/galley/forms/free-email-domains.js +1 -1
- package/dist/starters/astro-starter/src/galley/forms/logic.js +1 -1
- package/dist/starters/astro-starter/src/galley/forms/messages.js +1 -1
- package/dist/starters/astro-starter/src/galley/forms/render.js +1 -1
- package/dist/starters/astro-starter/src/galley/integration.js +1 -1
- package/dist/starters/astro-starter/src/galley/kit.d.ts +1 -1
- package/dist/starters/astro-starter/src/galley/mailto/config.js +1 -1
- package/dist/starters/astro-starter/src/galley/mailto/runtime.gen.js +1 -1
- package/dist/starters/astro-starter/src/galley/runtime/site-config.js +1 -1
- package/dist/starters/astro-starter/src/galley/schema.js +1 -1
- package/dist/starters/astro-starter/src/galley/scripts/banner.js +1 -1
- package/dist/starters/astro-starter/src/galley/scripts/plan.js +1 -1
- package/dist/starters/astro-starter/src/galley/scripts/runtime.gen.js +1 -1
- package/dist/starters/astro-starter/src/galley/scripts/snippets.js +1 -1
- package/dist/starters/astro-starter/src/galley/shared/glob.js +1 -1
- package/dist/starters/astro-starter/src/galley/shared/markdown.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/config.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/content.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/crawlers.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/html.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/integration.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/markdown.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/page.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/site.js +1 -1
- package/dist/starters/astro-starter/src/galley/visibility/structured.js +1 -1
- package/dist/starters/astro-storefront/README.md +3 -1
- package/dist/starters/astro-storefront/src/galley/catalog-data.js +1 -1
- package/dist/starters/astro-storefront/src/galley/catalog.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/attribution.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/forms.js +2 -2
- package/dist/starters/astro-storefront/src/galley/client/providers/frame-post.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/galley.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/hubspot.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/mailto.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/marketo.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/pardot.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/salesforce.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/providers/webhook.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/registry.js +1 -1
- package/dist/starters/astro-storefront/src/galley/client/types.d.ts +1 -1
- package/dist/starters/astro-storefront/src/galley/components/ConsentBanner.astro +1 -1
- package/dist/starters/astro-storefront/src/galley/components/Form.astro +1 -1
- package/dist/starters/astro-storefront/src/galley/components/Scripts.astro +1 -1
- package/dist/starters/astro-storefront/src/galley/components/index.js +1 -1
- package/dist/starters/astro-storefront/src/galley/forms/forms.css +1 -1
- package/dist/starters/astro-storefront/src/galley/forms/free-email-domains.js +1 -1
- package/dist/starters/astro-storefront/src/galley/forms/logic.js +1 -1
- package/dist/starters/astro-storefront/src/galley/forms/messages.js +1 -1
- package/dist/starters/astro-storefront/src/galley/forms/render.js +1 -1
- package/dist/starters/astro-storefront/src/galley/integration.js +1 -1
- package/dist/starters/astro-storefront/src/galley/kit.d.ts +1 -1
- package/dist/starters/astro-storefront/src/galley/mailto/config.js +1 -1
- package/dist/starters/astro-storefront/src/galley/mailto/runtime.gen.js +1 -1
- package/dist/starters/astro-storefront/src/galley/runtime/site-config.js +1 -1
- package/dist/starters/astro-storefront/src/galley/schema.js +1 -1
- package/dist/starters/astro-storefront/src/galley/scripts/banner.js +1 -1
- package/dist/starters/astro-storefront/src/galley/scripts/plan.js +1 -1
- package/dist/starters/astro-storefront/src/galley/scripts/runtime.gen.js +1 -1
- package/dist/starters/astro-storefront/src/galley/scripts/snippets.js +1 -1
- package/dist/starters/astro-storefront/src/galley/shared/glob.js +1 -1
- package/dist/starters/astro-storefront/src/galley/shared/markdown.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/config.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/content.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/crawlers.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/html.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/integration.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/markdown.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/page.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/site.js +1 -1
- package/dist/starters/astro-storefront/src/galley/visibility/structured.js +1 -1
- package/dist/web/assets/{AppSettingsScreen-D9ZHXus9.js → AppSettingsScreen-C-YJx3gF.js} +1 -1
- package/dist/web/assets/{BodyEditor-DAJ8MM41.js → BodyEditor-8Hp9g0iX.js} +1 -1
- package/dist/web/assets/{CollectionScreen-DVXLw7MF.js → CollectionScreen-Ci_RBTIP.js} +1 -1
- package/dist/web/assets/{EditorScreen-8vhIBZu1.js → EditorScreen-CG30ospj.js} +3 -3
- package/dist/web/assets/{FormsScreen-BbngAAzO.js → FormsScreen-C5Z4-vVZ.js} +2 -2
- package/dist/web/assets/{HistoryScreen-CubZj8QG.js → HistoryScreen-Cz0FyF3N.js} +3 -3
- package/dist/web/assets/InboxScreen-GB8e8oLq.js +2 -0
- package/dist/web/assets/{MediaLibraryPane-jMuqbnLa.js → MediaLibraryPane-D5J9z7rw.js} +1 -1
- package/dist/web/assets/{MediaScreen-mg2CATkP.js → MediaScreen-CoOq4MwF.js} +1 -1
- package/dist/web/assets/{NewSiteScreen-D9zWX6oE.js → NewSiteScreen-B_2094y0.js} +1 -1
- package/dist/web/assets/Online-CS3LLMG4.js +1 -0
- package/dist/web/assets/{PluginsScreen-1qEv-u35.js → PluginsScreen-Cdkv2qWN.js} +1 -1
- package/dist/web/assets/{PreviewPane-a06mELw4.js → PreviewPane-HeTLVD45.js} +1 -1
- package/dist/web/assets/{ProofScreen-CZfFbHFS.js → ProofScreen-BGAsVuYb.js} +1 -1
- package/dist/web/assets/{ProviderSettings-BOiCGeSI.js → ProviderSettings-BtM56M7d.js} +1 -1
- package/dist/web/assets/{PublishDialog-CSKU1lfx.js → PublishDialog-Ctv1sxHs.js} +2 -2
- package/dist/web/assets/{ReachNote-CZYr1oL0.js → ReachNote-BJrBYKWR.js} +1 -1
- package/dist/web/assets/{ScriptsScreen-BXY-kqbq.js → ScriptsScreen-BsYOIXkI.js} +2 -2
- package/dist/web/assets/{SiteHomeScreen-DOrqAteL.js → SiteHomeScreen-C7LLVNdQ.js} +1 -1
- package/dist/web/assets/{SiteSettingsScreen-B8xQnhjd.js → SiteSettingsScreen-DhX8CluW.js} +1 -1
- package/dist/web/assets/{SourceView-B5SoYjUF.js → SourceView-CkX8bKwR.js} +1 -1
- package/dist/web/assets/{VisibilityScreen-B4iOATC4.js → VisibilityScreen-ChOKniqk.js} +1 -1
- package/dist/web/assets/{codemirror-g0T4-Tsm.js → codemirror-ClWBLK2a.js} +1 -1
- package/dist/web/assets/index-CtsAxi5d.js +10 -0
- package/dist/web/assets/{index-Pd8oyXqS.css → index-xTbHx1DQ.css} +1 -1
- package/dist/web/assets/{listPlan-BXud7Oxv.js → listPlan-BPJMzA6e.js} +1 -1
- package/dist/web/assets/{outside-DaBM5h5B.js → outside-Bv1jj3yu.js} +1 -1
- package/dist/web/assets/{paths-C8ESZJVU.js → paths-B6ATG9Kg.js} +1 -1
- package/dist/web/assets/{prefs-BcNyBxxO.js → prefs-D04M07D3.js} +1 -1
- package/dist/web/assets/{scaffold-BHkqc62J.js → scaffold-DrnWBKU9.js} +1 -1
- package/dist/web/assets/{usePlugins-acEOSN5a.js → usePlugins-6k3yRVYT.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +5 -5
- package/dist/web/assets/InboxScreen-Azqy6w4_.js +0 -2
- package/dist/web/assets/Online-bYUu0ETZ.js +0 -1
- package/dist/web/assets/index-Djh-DSIT.js +0 -10
package/dist/galley.mjs
CHANGED
|
@@ -381,7 +381,7 @@ var init_brand = __esm({
|
|
|
381
381
|
byline: `by ${PRODUCT.maker}`,
|
|
382
382
|
docsUrl: `${SITE_URL}/docs`
|
|
383
383
|
};
|
|
384
|
-
VERSION = "0.1.
|
|
384
|
+
VERSION = "0.1.1";
|
|
385
385
|
}
|
|
386
386
|
});
|
|
387
387
|
|
|
@@ -1977,26 +1977,26 @@ var require_parse = __commonJS({
|
|
|
1977
1977
|
};
|
|
1978
1978
|
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input2)) {
|
|
1979
1979
|
let backslashes = false;
|
|
1980
|
-
let output2 = input2.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc3, chars2,
|
|
1981
|
-
if (
|
|
1980
|
+
let output2 = input2.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc3, chars2, first3, rest, index) => {
|
|
1981
|
+
if (first3 === "\\") {
|
|
1982
1982
|
backslashes = true;
|
|
1983
1983
|
return m;
|
|
1984
1984
|
}
|
|
1985
|
-
if (
|
|
1985
|
+
if (first3 === "?") {
|
|
1986
1986
|
if (esc3) {
|
|
1987
|
-
return esc3 +
|
|
1987
|
+
return esc3 + first3 + (rest ? QMARK.repeat(rest.length) : "");
|
|
1988
1988
|
}
|
|
1989
1989
|
if (index === 0) {
|
|
1990
1990
|
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
|
|
1991
1991
|
}
|
|
1992
1992
|
return QMARK.repeat(chars2.length);
|
|
1993
1993
|
}
|
|
1994
|
-
if (
|
|
1994
|
+
if (first3 === ".") {
|
|
1995
1995
|
return DOT_LITERAL.repeat(chars2.length);
|
|
1996
1996
|
}
|
|
1997
|
-
if (
|
|
1997
|
+
if (first3 === "*") {
|
|
1998
1998
|
if (esc3) {
|
|
1999
|
-
return esc3 +
|
|
1999
|
+
return esc3 + first3 + (rest ? star : "");
|
|
2000
2000
|
}
|
|
2001
2001
|
return star;
|
|
2002
2002
|
}
|
|
@@ -3040,7 +3040,7 @@ ${codeblock}`, options2);
|
|
|
3040
3040
|
function parseString(ctx) {
|
|
3041
3041
|
let startPtr = ctx.p;
|
|
3042
3042
|
let c = ctx.s.charCodeAt(ctx.p++);
|
|
3043
|
-
let
|
|
3043
|
+
let first3 = c;
|
|
3044
3044
|
let isLiteral = c === 39;
|
|
3045
3045
|
let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
|
|
3046
3046
|
if (isMultiline) {
|
|
@@ -3058,11 +3058,11 @@ function parseString(ctx) {
|
|
|
3058
3058
|
state = state && 3;
|
|
3059
3059
|
} else if (c < 32 && c !== 9 || c === 127) {
|
|
3060
3060
|
TomlError.x("control characters are not allowed in strings", ctx);
|
|
3061
|
-
} else if ((!state || state === 3) && c ===
|
|
3061
|
+
} else if ((!state || state === 3) && c === first3 && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first3 && ctx.s.charCodeAt(ctx.p + 2) === first3)) {
|
|
3062
3062
|
if (isMultiline) {
|
|
3063
|
-
if (ctx.s.charCodeAt(ctx.p + 3) ===
|
|
3063
|
+
if (ctx.s.charCodeAt(ctx.p + 3) === first3)
|
|
3064
3064
|
ctx.p++;
|
|
3065
|
-
if (ctx.s.charCodeAt(ctx.p + 3) ===
|
|
3065
|
+
if (ctx.s.charCodeAt(ctx.p + 3) === first3)
|
|
3066
3066
|
ctx.p++;
|
|
3067
3067
|
}
|
|
3068
3068
|
if (!state) {
|
|
@@ -8563,9 +8563,9 @@ var require_resolve_block_scalar = __commonJS({
|
|
|
8563
8563
|
}
|
|
8564
8564
|
function splitLines2(source2) {
|
|
8565
8565
|
const split = source2.split(/\n( *)/);
|
|
8566
|
-
const
|
|
8567
|
-
const m =
|
|
8568
|
-
const line0 = m?.[1] ? [m[1],
|
|
8566
|
+
const first3 = split[0];
|
|
8567
|
+
const m = first3.match(/^( *)/);
|
|
8568
|
+
const line0 = m?.[1] ? [m[1], first3.slice(m[1].length)] : ["", first3];
|
|
8569
8569
|
const lines = [line0];
|
|
8570
8570
|
for (let i = 1; i < split.length; i += 2)
|
|
8571
8571
|
lines.push([split[i], split[i + 1]]);
|
|
@@ -11572,8 +11572,8 @@ function labelForKey(key) {
|
|
|
11572
11572
|
const parts = words(key);
|
|
11573
11573
|
if (parts.length === 0) return key;
|
|
11574
11574
|
const rendered2 = parts.map((word) => ACRONYMS.has(word) ? word.toUpperCase() : word);
|
|
11575
|
-
const
|
|
11576
|
-
rendered2[0] =
|
|
11575
|
+
const first3 = rendered2[0] ?? "";
|
|
11576
|
+
rendered2[0] = first3.charAt(0).toUpperCase() + first3.slice(1);
|
|
11577
11577
|
return rendered2.join(" ");
|
|
11578
11578
|
}
|
|
11579
11579
|
function labelForBlockType(type) {
|
|
@@ -13353,10 +13353,10 @@ function unionMembers(chain, scope2, depth) {
|
|
|
13353
13353
|
let discriminator = null;
|
|
13354
13354
|
let list3;
|
|
13355
13355
|
if (chain.base === "discriminatedUnion") {
|
|
13356
|
-
const
|
|
13357
|
-
if (
|
|
13356
|
+
const first3 = resolve3(chain.baseArgs[0] ?? { kind: "unknown" }, scope2);
|
|
13357
|
+
if (first3.kind === "array") list3 = first3;
|
|
13358
13358
|
else {
|
|
13359
|
-
discriminator = stringOf(
|
|
13359
|
+
discriminator = stringOf(first3);
|
|
13360
13360
|
list3 = resolve3(chain.baseArgs[1] ?? { kind: "unknown" }, scope2);
|
|
13361
13361
|
}
|
|
13362
13362
|
} else if (chain.base === "union") {
|
|
@@ -13386,8 +13386,8 @@ function unionBlocks(chain, scope2, depth) {
|
|
|
13386
13386
|
const fieldsList = objects;
|
|
13387
13387
|
let discriminator = union2.discriminator;
|
|
13388
13388
|
if (!discriminator) {
|
|
13389
|
-
const
|
|
13390
|
-
discriminator =
|
|
13389
|
+
const first3 = fieldsList.find((fields) => fields.some(isTag));
|
|
13390
|
+
discriminator = first3?.find((candidate) => isTag(candidate) && fieldsList.every((fields) => fields.some((item) => item.key === candidate.key && (isTag(item) || item.type === "string"))))?.key ?? null;
|
|
13391
13391
|
if (!discriminator) return null;
|
|
13392
13392
|
}
|
|
13393
13393
|
const blocks = [];
|
|
@@ -18326,10 +18326,10 @@ var init_schemas = __esm({
|
|
|
18326
18326
|
}
|
|
18327
18327
|
return void 0;
|
|
18328
18328
|
});
|
|
18329
|
-
const
|
|
18329
|
+
const first3 = def.options.length === 1 ? def.options[0]._zod.run : null;
|
|
18330
18330
|
inst._zod.parse = (payload, ctx) => {
|
|
18331
|
-
if (
|
|
18332
|
-
return
|
|
18331
|
+
if (first3) {
|
|
18332
|
+
return first3(payload, ctx);
|
|
18333
18333
|
}
|
|
18334
18334
|
let async = false;
|
|
18335
18335
|
const results = [];
|
|
@@ -18357,10 +18357,10 @@ var init_schemas = __esm({
|
|
|
18357
18357
|
$ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
|
|
18358
18358
|
$ZodUnion.init(inst, def);
|
|
18359
18359
|
def.inclusive = false;
|
|
18360
|
-
const
|
|
18360
|
+
const first3 = def.options.length === 1 ? def.options[0]._zod.run : null;
|
|
18361
18361
|
inst._zod.parse = (payload, ctx) => {
|
|
18362
|
-
if (
|
|
18363
|
-
return
|
|
18362
|
+
if (first3) {
|
|
18363
|
+
return first3(payload, ctx);
|
|
18364
18364
|
}
|
|
18365
18365
|
let async = false;
|
|
18366
18366
|
const results = [];
|
|
@@ -19237,7 +19237,7 @@ function isRef(value) {
|
|
|
19237
19237
|
function cloneIssues(issues) {
|
|
19238
19238
|
return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
|
|
19239
19239
|
}
|
|
19240
|
-
function isRecursive2(inst, stack,
|
|
19240
|
+
function isRecursive2(inst, stack, resolve25) {
|
|
19241
19241
|
const cached3 = recursive.get(inst);
|
|
19242
19242
|
if (cached3 !== void 0)
|
|
19243
19243
|
return cached3 ? PROVEN : NONE;
|
|
@@ -19247,7 +19247,7 @@ function isRecursive2(inst, stack, resolve24) {
|
|
|
19247
19247
|
let result = NONE;
|
|
19248
19248
|
const check4 = (child2) => {
|
|
19249
19249
|
if (result !== PROVEN && child2?._zod) {
|
|
19250
|
-
const answer2 = isRecursive2(child2, stack,
|
|
19250
|
+
const answer2 = isRecursive2(child2, stack, resolve25);
|
|
19251
19251
|
if (answer2 > result)
|
|
19252
19252
|
result = answer2;
|
|
19253
19253
|
}
|
|
@@ -19258,7 +19258,7 @@ function isRecursive2(inst, stack, resolve24) {
|
|
|
19258
19258
|
const desc = Object.getOwnPropertyDescriptor(sh, key);
|
|
19259
19259
|
if (spread && !desc.enumerable)
|
|
19260
19260
|
continue;
|
|
19261
|
-
const child2 = desc.get ? ASSUMED : desc.value?._zod ? isRecursive2(desc.value, stack,
|
|
19261
|
+
const child2 = desc.get ? ASSUMED : desc.value?._zod ? isRecursive2(desc.value, stack, resolve25) : NONE;
|
|
19262
19262
|
if (child2 > answer2)
|
|
19263
19263
|
answer2 = child2;
|
|
19264
19264
|
}
|
|
@@ -19322,7 +19322,7 @@ function isRecursive2(inst, stack, resolve24) {
|
|
|
19322
19322
|
break;
|
|
19323
19323
|
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
|
|
19324
19324
|
case "lazy": {
|
|
19325
|
-
const inner = def._cachedInner ?? (
|
|
19325
|
+
const inner = def._cachedInner ?? (resolve25 ? inst._zod.innerType : void 0);
|
|
19326
19326
|
merge2(inner ? isRecursive2(inner, stack, false) : ASSUMED);
|
|
19327
19327
|
break;
|
|
19328
19328
|
}
|
|
@@ -31097,9 +31097,9 @@ var init_json_schema_processors = __esm({
|
|
|
31097
31097
|
else
|
|
31098
31098
|
handleUnrepresentable(schema, ctx, json10, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
|
|
31099
31099
|
}
|
|
31100
|
-
const [
|
|
31101
|
-
if (
|
|
31102
|
-
json10.multipleOf =
|
|
31100
|
+
const [first3, ...rest] = divisors;
|
|
31101
|
+
if (first3 !== void 0)
|
|
31102
|
+
json10.multipleOf = first3;
|
|
31103
31103
|
if (rest.length)
|
|
31104
31104
|
json10.allOf = [...json10.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
|
|
31105
31105
|
}
|
|
@@ -33979,14 +33979,14 @@ function checkArrayGuards(arraySchema, guards) {
|
|
|
33979
33979
|
const key = canonicalKey(items[i], /* @__PURE__ */ new Set());
|
|
33980
33980
|
if (key === null)
|
|
33981
33981
|
continue;
|
|
33982
|
-
const
|
|
33983
|
-
if (
|
|
33982
|
+
const first3 = firstSeen.get(key);
|
|
33983
|
+
if (first3 === void 0) {
|
|
33984
33984
|
firstSeen.set(key, i);
|
|
33985
33985
|
continue;
|
|
33986
33986
|
}
|
|
33987
33987
|
payload.issues.push({
|
|
33988
33988
|
code: "custom",
|
|
33989
|
-
message: `Array items must be unique: element at index ${i} duplicates the one at index ${
|
|
33989
|
+
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first3}`,
|
|
33990
33990
|
input: items,
|
|
33991
33991
|
path: [i],
|
|
33992
33992
|
continue: true
|
|
@@ -36032,10 +36032,10 @@ function asMatch(value) {
|
|
|
36032
36032
|
function stringList(value) {
|
|
36033
36033
|
return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
|
|
36034
36034
|
}
|
|
36035
|
-
function sanitizeConventions(value,
|
|
36035
|
+
function sanitizeConventions(value, report3) {
|
|
36036
36036
|
if (value === null || value === void 0) return {};
|
|
36037
36037
|
if (typeof value !== "object" || Array.isArray(value)) {
|
|
36038
|
-
|
|
36038
|
+
report3("its conventions were not an object");
|
|
36039
36039
|
return {};
|
|
36040
36040
|
}
|
|
36041
36041
|
const input2 = value;
|
|
@@ -36044,7 +36044,7 @@ function sanitizeConventions(value, report2) {
|
|
|
36044
36044
|
const inner = input2[key];
|
|
36045
36045
|
if (inner === void 0) return void 0;
|
|
36046
36046
|
if (inner === null || typeof inner !== "object" || Array.isArray(inner)) {
|
|
36047
|
-
|
|
36047
|
+
report3(`\u201C${key}\u201D was not an object`);
|
|
36048
36048
|
return void 0;
|
|
36049
36049
|
}
|
|
36050
36050
|
return inner;
|
|
@@ -36055,10 +36055,10 @@ function sanitizeConventions(value, report2) {
|
|
|
36055
36055
|
if (typeof dev.command === "string" && dev.command.trim() !== "") out.dev.command = dev.command;
|
|
36056
36056
|
if (dev.port === null) out.dev.port = null;
|
|
36057
36057
|
else if (typeof dev.port === "number" && Number.isInteger(dev.port) && dev.port > 0 && dev.port < 65536) out.dev.port = dev.port;
|
|
36058
|
-
else if (dev.port !== void 0)
|
|
36058
|
+
else if (dev.port !== void 0) report3("\u201Cdev.port\u201D was not a port number");
|
|
36059
36059
|
const portArgs = stringList(dev.portArgs);
|
|
36060
36060
|
if (portArgs && portArgs.length > 0 && portArgs.some((arg) => arg.includes("{port}"))) out.dev.portArgs = portArgs;
|
|
36061
|
-
else if (dev.portArgs !== void 0)
|
|
36061
|
+
else if (dev.portArgs !== void 0) report3("\u201Cdev.portArgs\u201D was not a list of arguments with {port} in it");
|
|
36062
36062
|
}
|
|
36063
36063
|
const build2 = object3("build");
|
|
36064
36064
|
if (build2) {
|
|
@@ -36080,7 +36080,7 @@ function sanitizeConventions(value, report2) {
|
|
|
36080
36080
|
if (urls) {
|
|
36081
36081
|
out.urls = {};
|
|
36082
36082
|
if (httpUrl3(urls.production)) out.urls.production = httpUrl3(urls.production);
|
|
36083
|
-
else if (urls.production !== void 0)
|
|
36083
|
+
else if (urls.production !== void 0) report3("\u201Curls.production\u201D was not a web address");
|
|
36084
36084
|
if (httpUrl3(urls.staging)) out.urls.staging = httpUrl3(urls.staging);
|
|
36085
36085
|
}
|
|
36086
36086
|
if (typeof input2.trailingSlash === "boolean") out.trailingSlash = input2.trailingSlash;
|
|
@@ -36089,7 +36089,7 @@ function sanitizeConventions(value, report2) {
|
|
|
36089
36089
|
if (input2[key] === void 0) continue;
|
|
36090
36090
|
const list3 = stringList(input2[key]);
|
|
36091
36091
|
if (list3) out[key] = list3;
|
|
36092
|
-
else
|
|
36092
|
+
else report3(`\u201C${key}\u201D was not a list of folders`);
|
|
36093
36093
|
}
|
|
36094
36094
|
if (input2.contentUrls === "folders" || input2.contentUrls === "none") out.contentUrls = input2.contentUrls;
|
|
36095
36095
|
return out;
|
|
@@ -36977,6 +36977,12 @@ var init_schema2 = __esm({
|
|
|
36977
36977
|
account: external_exports.string().min(1).max(100),
|
|
36978
36978
|
project: external_exports.string().regex(DEPLOY_PROJECT, { message: "must be lowercase letters, digits and dashes (up to 54), like \u201Cmy-site\u201D." }),
|
|
36979
36979
|
productionUrl: external_exports.string().url().optional(),
|
|
36980
|
+
defaultUrl: external_exports.string().url().optional(),
|
|
36981
|
+
domain: external_exports.object({
|
|
36982
|
+
hostname: external_exports.string().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/, { message: "must be a host name like \u201Cwww.example.com\u201D." }),
|
|
36983
|
+
attached: external_exports.boolean(),
|
|
36984
|
+
pending: external_exports.boolean().optional()
|
|
36985
|
+
}).strict().optional(),
|
|
36980
36986
|
autoDeploy: external_exports.boolean().optional(),
|
|
36981
36987
|
previewOnShare: external_exports.boolean().optional()
|
|
36982
36988
|
}).strict();
|
|
@@ -38299,9 +38305,9 @@ function addKey(text7, steps, map3, key, value, layout) {
|
|
|
38299
38305
|
return splice2(text7, lastEnd, lastEnd, `, ${pairText}`);
|
|
38300
38306
|
}
|
|
38301
38307
|
const items = map3.items;
|
|
38302
|
-
const
|
|
38303
|
-
if (!
|
|
38304
|
-
const keyColumn = column(text7, startOf(
|
|
38308
|
+
const first3 = items[0];
|
|
38309
|
+
if (!first3?.key) return null;
|
|
38310
|
+
const keyColumn = column(text7, startOf(first3.key));
|
|
38305
38311
|
const end = endOf(text7, map3);
|
|
38306
38312
|
if (end === null) return null;
|
|
38307
38313
|
const at = lineEnd(text7, end);
|
|
@@ -38797,15 +38803,15 @@ function parse4(source2) {
|
|
|
38797
38803
|
const classMask = () => {
|
|
38798
38804
|
const negated = eat("^");
|
|
38799
38805
|
let mask = 0n;
|
|
38800
|
-
let
|
|
38806
|
+
let first3 = true;
|
|
38801
38807
|
for (; ; ) {
|
|
38802
38808
|
const char = peek();
|
|
38803
38809
|
if (char === void 0) throw new Unreadable();
|
|
38804
|
-
if (char === "]" && !
|
|
38810
|
+
if (char === "]" && !first3) {
|
|
38805
38811
|
at += 1;
|
|
38806
38812
|
break;
|
|
38807
38813
|
}
|
|
38808
|
-
|
|
38814
|
+
first3 = false;
|
|
38809
38815
|
let low;
|
|
38810
38816
|
let lowCode = null;
|
|
38811
38817
|
if (char === "\\") {
|
|
@@ -41212,7 +41218,7 @@ function spawnOptions(cwd, env, shell = false) {
|
|
|
41212
41218
|
};
|
|
41213
41219
|
}
|
|
41214
41220
|
function runCommand(command, args, options2) {
|
|
41215
|
-
return new Promise((
|
|
41221
|
+
return new Promise((resolve25) => {
|
|
41216
41222
|
const stdoutChunks = [];
|
|
41217
41223
|
let stdoutBytes = 0;
|
|
41218
41224
|
let stderr = "";
|
|
@@ -41224,7 +41230,7 @@ function runCommand(command, args, options2) {
|
|
|
41224
41230
|
try {
|
|
41225
41231
|
child2 = spawn(command, args, spawnOptions(options2.cwd, options2.env, options2.shell));
|
|
41226
41232
|
} catch (error63) {
|
|
41227
|
-
|
|
41233
|
+
resolve25({
|
|
41228
41234
|
code: -1,
|
|
41229
41235
|
stdout: Buffer.alloc(0),
|
|
41230
41236
|
stderr: "",
|
|
@@ -41264,7 +41270,7 @@ function runCommand(command, args, options2) {
|
|
|
41264
41270
|
for (const stream2 of ["stdout", "stderr"]) {
|
|
41265
41271
|
if (lineBuffers[stream2] && options2.onLine) options2.onLine(lineBuffers[stream2], stream2);
|
|
41266
41272
|
}
|
|
41267
|
-
|
|
41273
|
+
resolve25(result);
|
|
41268
41274
|
};
|
|
41269
41275
|
child2.on("error", (error63) => {
|
|
41270
41276
|
finish3({ code: -1, stdout: Buffer.alloc(0), stderr, timedOut, spawnError: error63 });
|
|
@@ -42763,8 +42769,8 @@ async function measure(absolute2, size2) {
|
|
|
42763
42769
|
}
|
|
42764
42770
|
};
|
|
42765
42771
|
const head = await readHead(absolute2, Math.min(size2, HEADER_BYTES));
|
|
42766
|
-
const
|
|
42767
|
-
if (
|
|
42772
|
+
const first3 = attempt(head);
|
|
42773
|
+
if (first3 || size2 <= HEADER_BYTES || size2 > FULL_READ_LIMIT) return first3 ?? {};
|
|
42768
42774
|
return attempt(await readHead(absolute2, size2)) ?? {};
|
|
42769
42775
|
}
|
|
42770
42776
|
function rootsOf(media) {
|
|
@@ -44188,7 +44194,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44188
44194
|
let gitQuietUntil = 0;
|
|
44189
44195
|
let watcher = null;
|
|
44190
44196
|
let disposed = false;
|
|
44191
|
-
const
|
|
44197
|
+
const resolve25 = (path6) => resolveContained(root, realRoot, path6);
|
|
44192
44198
|
const absoluteOf = (path6) => path6 === "" ? root : join13(root, ...path6.split("/"));
|
|
44193
44199
|
const emit = (paths2, origin) => {
|
|
44194
44200
|
if (paths2.length === 0 || disposed) return;
|
|
@@ -44241,7 +44247,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44241
44247
|
}
|
|
44242
44248
|
const checkpoints = new CheckpointManager({
|
|
44243
44249
|
restoreFile: async (path6, bytes) => {
|
|
44244
|
-
const resolved =
|
|
44250
|
+
const resolved = resolve25(path6);
|
|
44245
44251
|
const denied = deniedReason(resolved.path, "build") ?? deniedReason(resolved.realPath, "build");
|
|
44246
44252
|
if (denied) throw new GalleyError("forbidden", denied, path6);
|
|
44247
44253
|
await lock(() => applyWrite(resolved, bytes, {}));
|
|
@@ -44278,7 +44284,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44278
44284
|
function refusal2(path6, mode) {
|
|
44279
44285
|
let resolved;
|
|
44280
44286
|
try {
|
|
44281
|
-
resolved =
|
|
44287
|
+
resolved = resolve25(path6);
|
|
44282
44288
|
} catch (error63) {
|
|
44283
44289
|
return { resolved: null, reason: error63.message };
|
|
44284
44290
|
}
|
|
@@ -44289,13 +44295,13 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44289
44295
|
function guard(path6, mode) {
|
|
44290
44296
|
const { resolved, reason } = refusal2(path6, mode);
|
|
44291
44297
|
if (!resolved || reason) {
|
|
44292
|
-
if (!resolved)
|
|
44298
|
+
if (!resolved) resolve25(path6);
|
|
44293
44299
|
throw new GalleyError("forbidden", reason ?? "That file can't be changed.", path6);
|
|
44294
44300
|
}
|
|
44295
44301
|
return resolved;
|
|
44296
44302
|
}
|
|
44297
44303
|
function guardSystem(path6) {
|
|
44298
|
-
const resolved =
|
|
44304
|
+
const resolved = resolve25(path6);
|
|
44299
44305
|
const denied = deniedReason(resolved.path, "build") ?? deniedReason(resolved.realPath, "build");
|
|
44300
44306
|
if (denied) throw new GalleyError("forbidden", denied, path6);
|
|
44301
44307
|
return resolved;
|
|
@@ -44368,7 +44374,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44368
44374
|
});
|
|
44369
44375
|
}
|
|
44370
44376
|
for (const path6 of remove) {
|
|
44371
|
-
const resolved =
|
|
44377
|
+
const resolved = resolve25(path6);
|
|
44372
44378
|
const kind = await lstat2(resolved.absolute).catch(() => null);
|
|
44373
44379
|
if (kind && !kind.isDirectory()) await unlink2(resolved.absolute);
|
|
44374
44380
|
}
|
|
@@ -44422,14 +44428,14 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44422
44428
|
const workspace = {
|
|
44423
44429
|
root,
|
|
44424
44430
|
resolvePath(path6) {
|
|
44425
|
-
return
|
|
44431
|
+
return resolve25(path6).absolute;
|
|
44426
44432
|
},
|
|
44427
44433
|
async exists(path6) {
|
|
44428
|
-
const resolved =
|
|
44434
|
+
const resolved = resolve25(path6);
|
|
44429
44435
|
return await lstat2(resolved.absolute).catch(() => null) !== null;
|
|
44430
44436
|
},
|
|
44431
44437
|
async readBytes(path6) {
|
|
44432
|
-
const resolved =
|
|
44438
|
+
const resolved = resolve25(path6);
|
|
44433
44439
|
try {
|
|
44434
44440
|
return new Uint8Array(await readFile6(resolved.absolute));
|
|
44435
44441
|
} catch (error63) {
|
|
@@ -44443,7 +44449,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44443
44449
|
return Buffer.from(await workspace.readBytes(path6)).toString("utf8");
|
|
44444
44450
|
},
|
|
44445
44451
|
async stat(path6) {
|
|
44446
|
-
const resolved =
|
|
44452
|
+
const resolved = resolve25(path6);
|
|
44447
44453
|
const result = await stat5(resolved.absolute).catch(() => null);
|
|
44448
44454
|
return result ? { size: result.size, mtimeMs: result.mtimeMs } : null;
|
|
44449
44455
|
},
|
|
@@ -44510,7 +44516,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44510
44516
|
return buildChangeSet(context2, new Map(statuses), enrich);
|
|
44511
44517
|
},
|
|
44512
44518
|
async diff(path6) {
|
|
44513
|
-
const resolved =
|
|
44519
|
+
const resolved = resolve25(path6);
|
|
44514
44520
|
const repoInfo = await info();
|
|
44515
44521
|
if (!repoInfo) {
|
|
44516
44522
|
throw new GalleyError("invalid", "This folder isn't under version control, so there's no earlier version to compare with.");
|
|
@@ -44518,7 +44524,7 @@ async function createWorkspace(rootInput, options2) {
|
|
|
44518
44524
|
return buildDiff(await changeContext(repoInfo), resolved.path);
|
|
44519
44525
|
},
|
|
44520
44526
|
async readBase(path6) {
|
|
44521
|
-
const resolved =
|
|
44527
|
+
const resolved = resolve25(path6);
|
|
44522
44528
|
const repoInfo = await info();
|
|
44523
44529
|
if (!repoInfo || !await repo.head()) return null;
|
|
44524
44530
|
const bytes = await readBaseBlob(repo, repoInfo, resolved.path);
|
|
@@ -44852,11 +44858,11 @@ import { realpathSync as realpathSync6 } from "node:fs";
|
|
|
44852
44858
|
import { readlink } from "node:fs/promises";
|
|
44853
44859
|
import { isAbsolute as isAbsolute5, relative as relative6, sep as sep5 } from "node:path";
|
|
44854
44860
|
function run(file2, args, timeoutMs) {
|
|
44855
|
-
return new Promise((
|
|
44861
|
+
return new Promise((resolve25) => {
|
|
44856
44862
|
execFile(file2, args, { timeout: timeoutMs, encoding: "utf8", env: { ...process.env, LC_ALL: "C" } }, (error63, stdout) => {
|
|
44857
|
-
if (error63 && error63.code === "ENOENT")
|
|
44858
|
-
else if (error63 && error63.killed)
|
|
44859
|
-
else
|
|
44863
|
+
if (error63 && error63.code === "ENOENT") resolve25(null);
|
|
44864
|
+
else if (error63 && error63.killed) resolve25(null);
|
|
44865
|
+
else resolve25({ code: error63 ? error63.code ?? 1 : 0, stdout: String(stdout ?? "") });
|
|
44860
44866
|
});
|
|
44861
44867
|
});
|
|
44862
44868
|
}
|
|
@@ -44916,15 +44922,15 @@ function parsePortRange(text7, source2 = "GALLEY_PREVIEW_PORTS") {
|
|
|
44916
44922
|
return { from, to };
|
|
44917
44923
|
}
|
|
44918
44924
|
function tryListen(server, port, host3) {
|
|
44919
|
-
return new Promise((
|
|
44925
|
+
return new Promise((resolve25, reject) => {
|
|
44920
44926
|
const onError = (error63) => {
|
|
44921
44927
|
server.off("listening", onListening);
|
|
44922
|
-
if (error63.code === "EADDRINUSE" || error63.code === "EACCES")
|
|
44928
|
+
if (error63.code === "EADDRINUSE" || error63.code === "EACCES") resolve25(false);
|
|
44923
44929
|
else reject(error63);
|
|
44924
44930
|
};
|
|
44925
44931
|
const onListening = () => {
|
|
44926
44932
|
server.off("error", onError);
|
|
44927
|
-
|
|
44933
|
+
resolve25(true);
|
|
44928
44934
|
};
|
|
44929
44935
|
server.once("error", onError);
|
|
44930
44936
|
server.once("listening", onListening);
|
|
@@ -44961,10 +44967,10 @@ function createPortPool(range2) {
|
|
|
44961
44967
|
}
|
|
44962
44968
|
async function portIsFree(port) {
|
|
44963
44969
|
for (const host3 of ["127.0.0.1", "::1"]) {
|
|
44964
|
-
const free = await new Promise((
|
|
44970
|
+
const free = await new Promise((resolve25) => {
|
|
44965
44971
|
const probe2 = net.createServer();
|
|
44966
|
-
probe2.once("error", (error63) =>
|
|
44967
|
-
probe2.listen({ port, host: host3, exclusive: true }, () => probe2.close(() =>
|
|
44972
|
+
probe2.once("error", (error63) => resolve25(error63.code === "EADDRNOTAVAIL" || error63.code === "EAFNOSUPPORT"));
|
|
44973
|
+
probe2.listen({ port, host: host3, exclusive: true }, () => probe2.close(() => resolve25(true)));
|
|
44968
44974
|
});
|
|
44969
44975
|
if (!free) return false;
|
|
44970
44976
|
}
|
|
@@ -44977,13 +44983,13 @@ async function freePort(preferred, avoid = /* @__PURE__ */ new Set()) {
|
|
|
44977
44983
|
}
|
|
44978
44984
|
}
|
|
44979
44985
|
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
44980
|
-
const port = await new Promise((
|
|
44986
|
+
const port = await new Promise((resolve25, reject) => {
|
|
44981
44987
|
const probe2 = net.createServer();
|
|
44982
44988
|
probe2.once("error", reject);
|
|
44983
44989
|
probe2.listen(0, "127.0.0.1", () => {
|
|
44984
44990
|
const address2 = probe2.address();
|
|
44985
44991
|
const value = typeof address2 === "object" && address2 ? address2.port : 0;
|
|
44986
|
-
probe2.close(() =>
|
|
44992
|
+
probe2.close(() => resolve25(value));
|
|
44987
44993
|
});
|
|
44988
44994
|
});
|
|
44989
44995
|
if (port && !avoid.has(port) && await portIsFree(port)) return port;
|
|
@@ -45243,11 +45249,11 @@ async function startProxy(options2) {
|
|
|
45243
45249
|
if (options2.ports) {
|
|
45244
45250
|
await options2.ports.pool.listen(server, options2.host, options2.ports.owner);
|
|
45245
45251
|
} else {
|
|
45246
|
-
await new Promise((
|
|
45252
|
+
await new Promise((resolve25, reject) => {
|
|
45247
45253
|
server.once("error", reject);
|
|
45248
45254
|
server.listen(0, options2.host, () => {
|
|
45249
45255
|
server.off("error", reject);
|
|
45250
|
-
|
|
45256
|
+
resolve25();
|
|
45251
45257
|
});
|
|
45252
45258
|
});
|
|
45253
45259
|
}
|
|
@@ -45257,10 +45263,10 @@ async function startProxy(options2) {
|
|
|
45257
45263
|
return {
|
|
45258
45264
|
port,
|
|
45259
45265
|
url: proxyOrigin,
|
|
45260
|
-
close: () => new Promise((
|
|
45266
|
+
close: () => new Promise((resolve25) => {
|
|
45261
45267
|
server.close(() => {
|
|
45262
45268
|
options2.ports?.pool.release(port);
|
|
45263
|
-
|
|
45269
|
+
resolve25();
|
|
45264
45270
|
});
|
|
45265
45271
|
server.closeAllConnections();
|
|
45266
45272
|
for (const socket of sockets) socket.destroy();
|
|
@@ -45315,12 +45321,12 @@ function startBaselineProxy(options2) {
|
|
|
45315
45321
|
});
|
|
45316
45322
|
}
|
|
45317
45323
|
function probe(url2, timeoutMs) {
|
|
45318
|
-
return new Promise((
|
|
45324
|
+
return new Promise((resolve25) => {
|
|
45319
45325
|
let parsed;
|
|
45320
45326
|
try {
|
|
45321
45327
|
parsed = new URL(url2);
|
|
45322
45328
|
} catch {
|
|
45323
|
-
|
|
45329
|
+
resolve25(null);
|
|
45324
45330
|
return;
|
|
45325
45331
|
}
|
|
45326
45332
|
const transport = parsed.protocol === "https:" ? https : http;
|
|
@@ -45336,13 +45342,13 @@ function probe(url2, timeoutMs) {
|
|
|
45336
45342
|
agent: false
|
|
45337
45343
|
},
|
|
45338
45344
|
(res) => {
|
|
45339
|
-
|
|
45345
|
+
resolve25(res.statusCode ?? 0);
|
|
45340
45346
|
res.resume();
|
|
45341
45347
|
res.destroy();
|
|
45342
45348
|
}
|
|
45343
45349
|
);
|
|
45344
45350
|
req2.on("timeout", () => req2.destroy());
|
|
45345
|
-
req2.on("error", () =>
|
|
45351
|
+
req2.on("error", () => resolve25(null));
|
|
45346
45352
|
req2.end();
|
|
45347
45353
|
});
|
|
45348
45354
|
}
|
|
@@ -45445,11 +45451,11 @@ async function answeringHost(port, timeoutMs = 1500) {
|
|
|
45445
45451
|
async function connectableHost(port, timeoutMs = 500) {
|
|
45446
45452
|
const results = await Promise.all(
|
|
45447
45453
|
LOOPBACKS.map(
|
|
45448
|
-
(host3) => new Promise((
|
|
45454
|
+
(host3) => new Promise((resolve25) => {
|
|
45449
45455
|
const socket = net3.connect({ host: host3, port });
|
|
45450
45456
|
const done = (value) => {
|
|
45451
45457
|
socket.destroy();
|
|
45452
|
-
|
|
45458
|
+
resolve25(value);
|
|
45453
45459
|
};
|
|
45454
45460
|
socket.setTimeout(timeoutMs, () => done(null));
|
|
45455
45461
|
socket.once("connect", () => done(host3));
|
|
@@ -45463,7 +45469,7 @@ function isWorkingPage(status2, sample3) {
|
|
|
45463
45469
|
return status2 > 0 && status2 < 500 && !/<vite-error-overlay\b/i.test(sample3);
|
|
45464
45470
|
}
|
|
45465
45471
|
function checkPage(host3, port, timeoutMs = PAGE_CHECK_TIMEOUT_MS) {
|
|
45466
|
-
return new Promise((
|
|
45472
|
+
return new Promise((resolve25) => {
|
|
45467
45473
|
const req2 = http2.request(
|
|
45468
45474
|
{ host: host3, port, path: "/", method: "GET", headers: { host: `localhost:${port}`, accept: "text/html", "user-agent": "Mozilla/5.0 (preview check)" }, timeout: timeoutMs, agent: false },
|
|
45469
45475
|
(res) => {
|
|
@@ -45471,7 +45477,7 @@ function checkPage(host3, port, timeoutMs = PAGE_CHECK_TIMEOUT_MS) {
|
|
|
45471
45477
|
let sample3 = "";
|
|
45472
45478
|
const finish3 = () => {
|
|
45473
45479
|
res.destroy();
|
|
45474
|
-
|
|
45480
|
+
resolve25(isWorkingPage(status2, sample3));
|
|
45475
45481
|
};
|
|
45476
45482
|
res.setEncoding("utf8");
|
|
45477
45483
|
res.on("data", (chunk2) => {
|
|
@@ -45479,11 +45485,11 @@ function checkPage(host3, port, timeoutMs = PAGE_CHECK_TIMEOUT_MS) {
|
|
|
45479
45485
|
if (sample3.length >= PAGE_SAMPLE_BYTES) finish3();
|
|
45480
45486
|
});
|
|
45481
45487
|
res.once("end", finish3);
|
|
45482
|
-
res.once("error", () =>
|
|
45488
|
+
res.once("error", () => resolve25(false));
|
|
45483
45489
|
}
|
|
45484
45490
|
);
|
|
45485
45491
|
req2.once("timeout", () => req2.destroy());
|
|
45486
|
-
req2.once("error", () =>
|
|
45492
|
+
req2.once("error", () => resolve25(false));
|
|
45487
45493
|
req2.end();
|
|
45488
45494
|
});
|
|
45489
45495
|
}
|
|
@@ -45561,17 +45567,17 @@ function createPreviewController(options2) {
|
|
|
45561
45567
|
childExitCode = null;
|
|
45562
45568
|
liveChildren.add(spawned);
|
|
45563
45569
|
installExitHook();
|
|
45564
|
-
childExited = new Promise((
|
|
45570
|
+
childExited = new Promise((resolve25) => {
|
|
45565
45571
|
spawned.once("exit", (code, signal) => {
|
|
45566
45572
|
liveChildren.delete(spawned);
|
|
45567
45573
|
childExitCode = code;
|
|
45568
45574
|
pushLog(`The preview command exited (${signal ?? `code ${code ?? "?"}`}).`);
|
|
45569
|
-
|
|
45575
|
+
resolve25();
|
|
45570
45576
|
});
|
|
45571
45577
|
spawned.once("error", (error63) => {
|
|
45572
45578
|
liveChildren.delete(spawned);
|
|
45573
45579
|
pushLog(`The preview command couldn't start: ${error63.message}`);
|
|
45574
|
-
|
|
45580
|
+
resolve25();
|
|
45575
45581
|
});
|
|
45576
45582
|
});
|
|
45577
45583
|
let partial2 = { stdout: "", stderr: "" };
|
|
@@ -45882,7 +45888,7 @@ var init_controller = __esm({
|
|
|
45882
45888
|
liveDetached = /* @__PURE__ */ new Set();
|
|
45883
45889
|
exitHookInstalled = false;
|
|
45884
45890
|
bracket = (host3) => host3.includes(":") ? `[${host3}]` : host3;
|
|
45885
|
-
delay = (ms) => new Promise((
|
|
45891
|
+
delay = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
|
|
45886
45892
|
}
|
|
45887
45893
|
});
|
|
45888
45894
|
|
|
@@ -48169,7 +48175,7 @@ async function createSiteRegistry(options2) {
|
|
|
48169
48175
|
function refreshFacts(force = false) {
|
|
48170
48176
|
if (refreshing) return refreshing;
|
|
48171
48177
|
refreshing = (async () => {
|
|
48172
|
-
await new Promise((
|
|
48178
|
+
await new Promise((resolve25) => setImmediate(resolve25));
|
|
48173
48179
|
const now = Date.now();
|
|
48174
48180
|
const due = store.all().filter((record3) => force || !record3.facts || now - record3.facts.checkedAt > factsMaxAgeMs).sort((a, b) => (a.facts?.checkedAt ?? 0) - (b.facts?.checkedAt ?? 0));
|
|
48175
48181
|
const updated = [];
|
|
@@ -48942,16 +48948,16 @@ var init_values = __esm({
|
|
|
48942
48948
|
var sleep;
|
|
48943
48949
|
var init_sleep = __esm({
|
|
48944
48950
|
"../../node_modules/.pnpm/@anthropic-ai+sdk@1.12.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() {
|
|
48945
|
-
sleep = (ms, signal) => new Promise((
|
|
48951
|
+
sleep = (ms, signal) => new Promise((resolve25) => {
|
|
48946
48952
|
if (signal?.aborted)
|
|
48947
|
-
return
|
|
48953
|
+
return resolve25();
|
|
48948
48954
|
const onAbort = () => {
|
|
48949
48955
|
clearTimeout(timer);
|
|
48950
|
-
|
|
48956
|
+
resolve25();
|
|
48951
48957
|
};
|
|
48952
48958
|
const timer = setTimeout(() => {
|
|
48953
48959
|
signal?.removeEventListener("abort", onAbort);
|
|
48954
|
-
|
|
48960
|
+
resolve25();
|
|
48955
48961
|
}, ms);
|
|
48956
48962
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
48957
48963
|
});
|
|
@@ -52691,8 +52697,8 @@ var init_api_promise = __esm({
|
|
|
52691
52697
|
APIPromise = /* @__PURE__ */ (() => {
|
|
52692
52698
|
class APIPromise2 extends Promise {
|
|
52693
52699
|
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
|
|
52694
|
-
super((
|
|
52695
|
-
|
|
52700
|
+
super((resolve25) => {
|
|
52701
|
+
resolve25(null);
|
|
52696
52702
|
});
|
|
52697
52703
|
this.responsePromise = responsePromise;
|
|
52698
52704
|
this.parseResponse = parseResponse;
|
|
@@ -55617,16 +55623,16 @@ var init_async_queue = __esm({
|
|
|
55617
55623
|
if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f") || signal?.aborted) {
|
|
55618
55624
|
return Promise.resolve({ done: true, value: void 0 });
|
|
55619
55625
|
}
|
|
55620
|
-
return new Promise((
|
|
55626
|
+
return new Promise((resolve25) => {
|
|
55621
55627
|
const waiter = (r) => {
|
|
55622
55628
|
signal?.removeEventListener("abort", onAbort);
|
|
55623
|
-
|
|
55629
|
+
resolve25(r);
|
|
55624
55630
|
};
|
|
55625
55631
|
const onAbort = () => {
|
|
55626
55632
|
const idx = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").indexOf(waiter);
|
|
55627
55633
|
if (idx >= 0)
|
|
55628
55634
|
__classPrivateFieldGet(this, _AsyncQueue_waiters, "f").splice(idx, 1);
|
|
55629
|
-
|
|
55635
|
+
resolve25({ done: true, value: void 0 });
|
|
55630
55636
|
};
|
|
55631
55637
|
__classPrivateFieldGet(this, _AsyncQueue_waiters, "f").push(waiter);
|
|
55632
55638
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -56533,13 +56539,13 @@ var init_json_schema2 = __esm({
|
|
|
56533
56539
|
|
|
56534
56540
|
// ../../node_modules/.pnpm/@anthropic-ai+sdk@1.12.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs
|
|
56535
56541
|
function promiseWithResolvers() {
|
|
56536
|
-
let
|
|
56542
|
+
let resolve25;
|
|
56537
56543
|
let reject;
|
|
56538
56544
|
const promise3 = new Promise((res, rej) => {
|
|
56539
|
-
|
|
56545
|
+
resolve25 = res;
|
|
56540
56546
|
reject = rej;
|
|
56541
56547
|
});
|
|
56542
|
-
return { promise: promise3, resolve:
|
|
56548
|
+
return { promise: promise3, resolve: resolve25, reject };
|
|
56543
56549
|
}
|
|
56544
56550
|
var init_promise = __esm({
|
|
56545
56551
|
"../../node_modules/.pnpm/@anthropic-ai+sdk@1.12.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs"() {
|
|
@@ -56709,18 +56715,18 @@ async function findExecutable(name3, notInside = [], searchPath = readEnv("PATH"
|
|
|
56709
56715
|
return null;
|
|
56710
56716
|
}
|
|
56711
56717
|
async function searchPathOutside(notInside, helpers) {
|
|
56712
|
-
const
|
|
56718
|
+
const resolve25 = (p) => fs2.realpath(p).catch(() => void 0);
|
|
56713
56719
|
const isInside3 = async (real3) => await containingRoot(notInside, real3, isWithinFolded) !== void 0;
|
|
56714
56720
|
let outside = null;
|
|
56715
56721
|
nextEntry: for (const dir of absolutePathEntries(readEnv("PATH") ?? "")) {
|
|
56716
|
-
const real3 = await
|
|
56722
|
+
const real3 = await resolve25(dir);
|
|
56717
56723
|
if (await isInside3(real3 ?? await canonicalize(dir).catch(() => dir)))
|
|
56718
56724
|
continue;
|
|
56719
56725
|
outside ?? (outside = []);
|
|
56720
56726
|
if (real3 === void 0 || real3.includes(path2.delimiter))
|
|
56721
56727
|
continue;
|
|
56722
56728
|
for (const name3 of helpers) {
|
|
56723
|
-
const helper = await
|
|
56729
|
+
const helper = await resolve25(path2.join(real3, name3));
|
|
56724
56730
|
if (helper !== void 0 && await isInside3(helper))
|
|
56725
56731
|
continue nextEntry;
|
|
56726
56732
|
}
|
|
@@ -56883,7 +56889,7 @@ async function runArchiveTool(cmd, args, notInside) {
|
|
|
56883
56889
|
const env = scrubbedShellEnv();
|
|
56884
56890
|
if (searchPath !== null)
|
|
56885
56891
|
env["PATH"] = searchPath;
|
|
56886
|
-
return new Promise((
|
|
56892
|
+
return new Promise((resolve25, reject) => {
|
|
56887
56893
|
const proc = child_process.spawn(file2, args, {
|
|
56888
56894
|
// A link called `tar` may lead to a program that goes by the name it was started under.
|
|
56889
56895
|
argv0: cmd,
|
|
@@ -56909,7 +56915,7 @@ async function runArchiveTool(cmd, args, notInside) {
|
|
|
56909
56915
|
} else if (code !== 0) {
|
|
56910
56916
|
reject(new AnthropicError(`\`${cmd}\` failed (${signal ?? `exit ${code}`}): ${output2.stderr.trim()}`));
|
|
56911
56917
|
} else {
|
|
56912
|
-
|
|
56918
|
+
resolve25(output2.stdout);
|
|
56913
56919
|
}
|
|
56914
56920
|
});
|
|
56915
56921
|
});
|
|
@@ -56921,10 +56927,10 @@ function archiveTopDir(names3) {
|
|
|
56921
56927
|
const parts = raw2.trim().split("/").filter((p) => p !== "" && p !== ".");
|
|
56922
56928
|
if (parts.length === 0)
|
|
56923
56929
|
continue;
|
|
56924
|
-
const
|
|
56930
|
+
const first3 = parts[0];
|
|
56925
56931
|
if (top === void 0)
|
|
56926
|
-
top =
|
|
56927
|
-
else if (
|
|
56932
|
+
top = first3;
|
|
56933
|
+
else if (first3 !== top)
|
|
56928
56934
|
return "";
|
|
56929
56935
|
if (parts.length > 1)
|
|
56930
56936
|
nested = true;
|
|
@@ -57479,10 +57485,10 @@ async function settledOrAborted(p, signal) {
|
|
|
57479
57485
|
return;
|
|
57480
57486
|
}
|
|
57481
57487
|
let onAbort;
|
|
57482
|
-
const aborted3 = new Promise((
|
|
57483
|
-
onAbort =
|
|
57488
|
+
const aborted3 = new Promise((resolve25) => {
|
|
57489
|
+
onAbort = resolve25;
|
|
57484
57490
|
if (signal.aborted)
|
|
57485
|
-
|
|
57491
|
+
resolve25();
|
|
57486
57492
|
});
|
|
57487
57493
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
57488
57494
|
try {
|
|
@@ -58562,7 +58568,7 @@ function betaGrepTool(ctx) {
|
|
|
58562
58568
|
});
|
|
58563
58569
|
}
|
|
58564
58570
|
function runRipgrep(rg, pattern, searchPath, signal) {
|
|
58565
|
-
return new Promise((
|
|
58571
|
+
return new Promise((resolve25, reject) => {
|
|
58566
58572
|
const proc = cp.spawn(rg, ["--no-config", "-n", "--no-heading", "-e", pattern, "--", searchPath], {
|
|
58567
58573
|
// A link called `rg` may lead to a program that goes by the name it was started under.
|
|
58568
58574
|
argv0: "rg",
|
|
@@ -58587,12 +58593,12 @@ function runRipgrep(rg, pattern, searchPath, signal) {
|
|
|
58587
58593
|
if (signal?.aborted)
|
|
58588
58594
|
return reject(new ToolError("grep: aborted"));
|
|
58589
58595
|
if (truncated)
|
|
58590
|
-
return
|
|
58596
|
+
return resolve25(out + `
|
|
58591
58597
|
[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
|
|
58592
58598
|
if (code === 0)
|
|
58593
|
-
return
|
|
58599
|
+
return resolve25(out);
|
|
58594
58600
|
if (code === 1)
|
|
58595
|
-
return
|
|
58601
|
+
return resolve25("no matches");
|
|
58596
58602
|
reject(new ToolError(`grep: rg failed: ${errOut || `exit ${code}`}`));
|
|
58597
58603
|
});
|
|
58598
58604
|
proc.on("error", (e) => {
|
|
@@ -58873,8 +58879,8 @@ var init_node2 = __esm({
|
|
|
58873
58879
|
`;
|
|
58874
58880
|
__classPrivateFieldGet(this, _BashSession_proc, "f").stdin.write(wrapped);
|
|
58875
58881
|
if (__classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel2) < 0) {
|
|
58876
|
-
const { promise: sentinelSeen, resolve:
|
|
58877
|
-
__classPrivateFieldSet(this, _BashSession_waiting, { sentinel: sentinel2, resolve:
|
|
58882
|
+
const { promise: sentinelSeen, resolve: resolve25 } = promiseWithResolvers();
|
|
58883
|
+
__classPrivateFieldSet(this, _BashSession_waiting, { sentinel: sentinel2, resolve: resolve25 }, "f");
|
|
58878
58884
|
let timer;
|
|
58879
58885
|
let onAbort;
|
|
58880
58886
|
try {
|
|
@@ -59052,8 +59058,8 @@ async function withTimeout2(p, ms) {
|
|
|
59052
59058
|
try {
|
|
59053
59059
|
return await Promise.race([
|
|
59054
59060
|
p.then(() => false, () => false),
|
|
59055
|
-
new Promise((
|
|
59056
|
-
timer = setTimeout(() =>
|
|
59061
|
+
new Promise((resolve25) => {
|
|
59062
|
+
timer = setTimeout(() => resolve25(true), ms);
|
|
59057
59063
|
})
|
|
59058
59064
|
]);
|
|
59059
59065
|
} finally {
|
|
@@ -61396,12 +61402,12 @@ var init_BetaMessageStream = __esm({
|
|
|
61396
61402
|
}
|
|
61397
61403
|
return this._emit("error", new AnthropicError(String(error63)));
|
|
61398
61404
|
});
|
|
61399
|
-
__classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((
|
|
61400
|
-
__classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise,
|
|
61405
|
+
__classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve25, reject) => {
|
|
61406
|
+
__classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve25, "f");
|
|
61401
61407
|
__classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
|
|
61402
61408
|
}), "f");
|
|
61403
|
-
__classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((
|
|
61404
|
-
__classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise,
|
|
61409
|
+
__classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve25, reject) => {
|
|
61410
|
+
__classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve25, "f");
|
|
61405
61411
|
__classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
|
|
61406
61412
|
}), "f");
|
|
61407
61413
|
__classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
|
|
@@ -61614,11 +61620,11 @@ var init_BetaMessageStream = __esm({
|
|
|
61614
61620
|
* const message = await stream.emitted('message') // rejects if the stream errors
|
|
61615
61621
|
*/
|
|
61616
61622
|
emitted(event) {
|
|
61617
|
-
return new Promise((
|
|
61623
|
+
return new Promise((resolve25, reject) => {
|
|
61618
61624
|
__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
|
|
61619
61625
|
if (event !== "error")
|
|
61620
61626
|
this.once("error", reject);
|
|
61621
|
-
this.once(event,
|
|
61627
|
+
this.once(event, resolve25);
|
|
61622
61628
|
});
|
|
61623
61629
|
}
|
|
61624
61630
|
async done() {
|
|
@@ -62006,7 +62012,7 @@ var init_BetaMessageStream = __esm({
|
|
|
62006
62012
|
if (done) {
|
|
62007
62013
|
return { value: void 0, done: true };
|
|
62008
62014
|
}
|
|
62009
|
-
return new Promise((
|
|
62015
|
+
return new Promise((resolve25, reject) => readQueue.push({ resolve: resolve25, reject })).then((chunk3) => chunk3 ? { value: chunk3, done: false } : { value: void 0, done: true });
|
|
62010
62016
|
}
|
|
62011
62017
|
const chunk2 = pushQueue.shift();
|
|
62012
62018
|
return { value: chunk2, done: false };
|
|
@@ -73391,12 +73397,12 @@ var init_MessageStream = __esm({
|
|
|
73391
73397
|
}
|
|
73392
73398
|
return this._emit("error", new AnthropicError(String(error63)));
|
|
73393
73399
|
});
|
|
73394
|
-
__classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((
|
|
73395
|
-
__classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise,
|
|
73400
|
+
__classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve25, reject) => {
|
|
73401
|
+
__classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve25, "f");
|
|
73396
73402
|
__classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
|
|
73397
73403
|
}), "f");
|
|
73398
|
-
__classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((
|
|
73399
|
-
__classPrivateFieldSet(this, _MessageStream_resolveEndPromise,
|
|
73404
|
+
__classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve25, reject) => {
|
|
73405
|
+
__classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve25, "f");
|
|
73400
73406
|
__classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
|
|
73401
73407
|
}), "f");
|
|
73402
73408
|
__classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {
|
|
@@ -73588,11 +73594,11 @@ var init_MessageStream = __esm({
|
|
|
73588
73594
|
* const message = await stream.emitted('message') // rejects if the stream errors
|
|
73589
73595
|
*/
|
|
73590
73596
|
emitted(event) {
|
|
73591
|
-
return new Promise((
|
|
73597
|
+
return new Promise((resolve25, reject) => {
|
|
73592
73598
|
__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
|
|
73593
73599
|
if (event !== "error")
|
|
73594
73600
|
this.once("error", reject);
|
|
73595
|
-
this.once(event,
|
|
73601
|
+
this.once(event, resolve25);
|
|
73596
73602
|
});
|
|
73597
73603
|
}
|
|
73598
73604
|
async done() {
|
|
@@ -73927,7 +73933,7 @@ var init_MessageStream = __esm({
|
|
|
73927
73933
|
if (done) {
|
|
73928
73934
|
return { value: void 0, done: true };
|
|
73929
73935
|
}
|
|
73930
|
-
return new Promise((
|
|
73936
|
+
return new Promise((resolve25, reject) => readQueue.push({ resolve: resolve25, reject })).then((chunk3) => chunk3 ? { value: chunk3, done: false } : { value: void 0, done: true });
|
|
73931
73937
|
}
|
|
73932
73938
|
const chunk2 = pushQueue.shift();
|
|
73933
73939
|
return { value: chunk2, done: false };
|
|
@@ -81548,12 +81554,12 @@ function scanDeclared(files, readPackage, options2 = {}) {
|
|
|
81548
81554
|
for (const variable of variables) {
|
|
81549
81555
|
if (/^(:root|html|@theme|:host)/.test(variable.context) || !byName.has(variable.name)) byName.set(variable.name, variable);
|
|
81550
81556
|
}
|
|
81551
|
-
const
|
|
81557
|
+
const resolve25 = (value, depth) => depth > 5 ? value : value.replace(/var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (whole, name3, fallback3) => {
|
|
81552
81558
|
const target = byName.get(name3);
|
|
81553
|
-
return target ?
|
|
81559
|
+
return target ? resolve25(target.raw, depth + 1) : fallback3?.trim() ?? whole;
|
|
81554
81560
|
});
|
|
81555
81561
|
for (const variable of variables) {
|
|
81556
|
-
variable.resolved =
|
|
81562
|
+
variable.resolved = resolve25(variable.raw, 0);
|
|
81557
81563
|
variable.kind = kindOf(variable.name, variable.resolved);
|
|
81558
81564
|
}
|
|
81559
81565
|
const counts = /* @__PURE__ */ new Map();
|
|
@@ -81578,12 +81584,12 @@ function scanDeclared(files, readPackage, options2 = {}) {
|
|
|
81578
81584
|
const fonts = [];
|
|
81579
81585
|
for (const variable of variables.filter((v) => v.kind === "font" && kept(v))) {
|
|
81580
81586
|
const families = splitFamilies(variable.resolved);
|
|
81581
|
-
const
|
|
81582
|
-
if (!
|
|
81583
|
-
const pkg = packageOfFamily(
|
|
81584
|
-
const ownFile = fontFaces.some((face) => face.family ===
|
|
81587
|
+
const first3 = families[0];
|
|
81588
|
+
if (!first3 || GENERIC.has(first3.toLowerCase())) continue;
|
|
81589
|
+
const pkg = packageOfFamily(first3, [...packages]) ?? fontFaces.find((face) => face.family === first3 && face.file.startsWith("pkg:"))?.file.slice(4).split("/").slice(0, 2).join("/");
|
|
81590
|
+
const ownFile = fontFaces.some((face) => face.family === first3 && !face.file.startsWith("pkg:"));
|
|
81585
81591
|
fonts.push({
|
|
81586
|
-
family:
|
|
81592
|
+
family: first3,
|
|
81587
81593
|
fallbacks: families.slice(1),
|
|
81588
81594
|
token: variable.name,
|
|
81589
81595
|
file: variable.file,
|
|
@@ -82209,8 +82215,8 @@ function checkChanges(brand, files, options2) {
|
|
|
82209
82215
|
}
|
|
82210
82216
|
const declared = /(?:font-family|--font[\w-]*)\s*:\s*([^;{}]+)/i.exec(text7);
|
|
82211
82217
|
if (declared && families.size) {
|
|
82212
|
-
const
|
|
82213
|
-
if (
|
|
82218
|
+
const first3 = splitFamilies(declared[1])[0];
|
|
82219
|
+
if (first3 && !/var\(/.test(first3) && !GENERIC2.test(first3) && !families.has(fontKey2(first3))) items.push({ kind: "font", text: `\u201C${first3}\u201D isn't one of the brand's fonts.`, path: file2.path, line, value: first3 });
|
|
82214
82220
|
}
|
|
82215
82221
|
}
|
|
82216
82222
|
if (brand.tokensFile === file2.path && file2.after) {
|
|
@@ -84111,8 +84117,8 @@ function parseSitemap(xml) {
|
|
|
84111
84117
|
}
|
|
84112
84118
|
function parseLlmsTxt(text7) {
|
|
84113
84119
|
const lines = text7.replace(/^/, "").split(/\r?\n/);
|
|
84114
|
-
const
|
|
84115
|
-
const title =
|
|
84120
|
+
const first3 = lines.find((line) => line.trim() !== "");
|
|
84121
|
+
const title = first3 && /^#\s+\S/.test(first3) ? first3.replace(/^#\s+/, "").trim() : null;
|
|
84116
84122
|
const summary3 = lines.find((line) => /^>\s?/.test(line))?.replace(/^>\s?/, "").trim() ?? null;
|
|
84117
84123
|
const links = [];
|
|
84118
84124
|
const problems = [];
|
|
@@ -85368,16 +85374,16 @@ function canonicalChecks(rendered2) {
|
|
|
85368
85374
|
if (isNoindex(rendered2.facts)) return out;
|
|
85369
85375
|
if (canonicals.length === 0) return [finding("canonical-missing", at)];
|
|
85370
85376
|
if (new Set(canonicals).size > 1) out.push(finding("canonical-multiple", { ...at, evidence: { values: canonicals } }));
|
|
85371
|
-
const
|
|
85372
|
-
if (!/^https?:\/\//i.test(
|
|
85373
|
-
out.push(finding("canonical-relative", { ...at, evidence: { value:
|
|
85377
|
+
const first3 = canonicals[0];
|
|
85378
|
+
if (!/^https?:\/\//i.test(first3)) {
|
|
85379
|
+
out.push(finding("canonical-relative", { ...at, evidence: { value: first3 } }));
|
|
85374
85380
|
return out;
|
|
85375
85381
|
}
|
|
85376
85382
|
try {
|
|
85377
|
-
const url2 = new URL(
|
|
85378
|
-
if (pathKey(url2.pathname) !== pathKey(rendered2.urlPath)) out.push(finding("canonical-elsewhere", { ...at, evidence: { value:
|
|
85383
|
+
const url2 = new URL(first3);
|
|
85384
|
+
if (pathKey(url2.pathname) !== pathKey(rendered2.urlPath)) out.push(finding("canonical-elsewhere", { ...at, evidence: { value: first3, note: `This page is ${rendered2.urlPath}.` } }));
|
|
85379
85385
|
} catch {
|
|
85380
|
-
out.push(finding("canonical-relative", { ...at, evidence: { value:
|
|
85386
|
+
out.push(finding("canonical-relative", { ...at, evidence: { value: first3 } }));
|
|
85381
85387
|
}
|
|
85382
85388
|
return out;
|
|
85383
85389
|
}
|
|
@@ -85613,12 +85619,12 @@ function noRender(total2, cap, reason, kit = null) {
|
|
|
85613
85619
|
}
|
|
85614
85620
|
function sample2(urls, priority, cap) {
|
|
85615
85621
|
const unique2 = [...new Set(urls)].filter((url2) => !/(^|\/)404(\.html|\/)?$/.test(url2));
|
|
85616
|
-
const
|
|
85617
|
-
const rest = unique2.filter((url2) => !
|
|
85618
|
-
const room = Math.max(0, cap -
|
|
85622
|
+
const first3 = unique2.filter((url2) => url2 === "/" || priority.has(pathKey(url2)));
|
|
85623
|
+
const rest = unique2.filter((url2) => !first3.includes(url2)).sort();
|
|
85624
|
+
const room = Math.max(0, cap - first3.length);
|
|
85619
85625
|
const step = rest.length > room && room > 0 ? rest.length / room : 1;
|
|
85620
85626
|
const picked = room === 0 ? [] : rest.length <= room ? rest : Array.from({ length: room }, (_, index) => rest[Math.floor(index * step)]);
|
|
85621
|
-
return [...
|
|
85627
|
+
return [...first3.slice(0, cap), ...picked].slice(0, cap);
|
|
85622
85628
|
}
|
|
85623
85629
|
async function renderedAudit(site, source2, model, pages, cap, siteName3, kit, only) {
|
|
85624
85630
|
const byKey = new Map(pages.filter((page) => page.url).map((page) => [pathKey(page.url), page]));
|
|
@@ -85896,8 +85902,8 @@ function structuredSuggestions(model, rendered2, types2, kit = null, base3 = "")
|
|
|
85896
85902
|
if (deep.length) out.push(finding("jsonld-suggest-breadcrumbs", { rendered: true, evidence: { pages: deep.slice(0, 8).map((item) => ({ url: item.urlPath, ...item.facts.title ? { title: item.facts.title } : {} })), note: `${deep.length} nested page${deep.length === 1 ? "" : "s"} checked.` } }));
|
|
85897
85903
|
return out;
|
|
85898
85904
|
}
|
|
85899
|
-
function crawlerFindings(
|
|
85900
|
-
if (!robotsText || !
|
|
85905
|
+
function crawlerFindings(report3, robotsText) {
|
|
85906
|
+
if (!robotsText || !report3.blocksEverything) return [];
|
|
85901
85907
|
return [finding("robots-blocks-all", { evidence: { value: robotsText.split(/\r?\n/).filter((line) => /disallow:\s*\/\s*$/i.test(line)).slice(0, 3).join("\n") } })];
|
|
85902
85908
|
}
|
|
85903
85909
|
function assetFindings(robots) {
|
|
@@ -85905,9 +85911,9 @@ function assetFindings(robots) {
|
|
|
85905
85911
|
const blocked2 = ASSET_PATHS.filter((path6) => !isAllowed(robots.file, "googlebot", path6).allowed && isAllowed(robots.file, "googlebot", "/").allowed);
|
|
85906
85912
|
return blocked2.length ? [finding("robots-blocks-assets", { evidence: { values: blocked2, note: "Paths like these are refused to Googlebot." } })] : [];
|
|
85907
85913
|
}
|
|
85908
|
-
function aiSearchFindings(
|
|
85909
|
-
if (
|
|
85910
|
-
return
|
|
85914
|
+
function aiSearchFindings(report3) {
|
|
85915
|
+
if (report3.blocksEverything || !report3.readable) return [];
|
|
85916
|
+
return report3.crawlers.filter((crawler) => crawler.purpose === "search" && !crawler.allowed).map((crawler) => ({ ...finding("ai-search-blocked", { key: crawler.token, title: `${crawler.label} is blocked`, evidence: { value: crawler.token, note: crawler.ifBlocked } }), source: crawler.source }));
|
|
85911
85917
|
}
|
|
85912
85918
|
function robotsWritable(model) {
|
|
85913
85919
|
return model.ai.allowBuild;
|
|
@@ -86627,12 +86633,12 @@ function checkRedirects(list3, ctx) {
|
|
|
86627
86633
|
});
|
|
86628
86634
|
for (const [from, indices] of want("duplicate", "conflict") ? byFrom : []) {
|
|
86629
86635
|
if (indices.length < 2) continue;
|
|
86630
|
-
const
|
|
86631
|
-
const conflicting = indices.slice(1).filter((index) => list3[index].to !==
|
|
86632
|
-
const same2 = indices.slice(1).filter((index) => list3[index].to ===
|
|
86636
|
+
const first3 = list3[indices[0]];
|
|
86637
|
+
const conflicting = indices.slice(1).filter((index) => list3[index].to !== first3.to);
|
|
86638
|
+
const same2 = indices.slice(1).filter((index) => list3[index].to === first3.to);
|
|
86633
86639
|
if (same2.length) issues.push({ code: "duplicate", severity: "warning", indices: [indices[0], ...same2], message: `${from} is listed ${plural4(same2.length + 1, "time")}. Only the first counts.` });
|
|
86634
86640
|
if (conflicting.length) {
|
|
86635
|
-
issues.push({ code: "conflict", severity: "error", indices: [indices[0], ...conflicting], message: `${from} is sent to ${conflicting.length + 1} different places. Visitors only ever reach the first, ${
|
|
86641
|
+
issues.push({ code: "conflict", severity: "error", indices: [indices[0], ...conflicting], message: `${from} is sent to ${conflicting.length + 1} different places. Visitors only ever reach the first, ${first3.to}.` });
|
|
86636
86642
|
}
|
|
86637
86643
|
}
|
|
86638
86644
|
for (const twins of want("case-twin") ? byLower.values() : []) {
|
|
@@ -87854,7 +87860,7 @@ function createAgentRuntime(options2) {
|
|
|
87854
87860
|
const controller = new AbortController();
|
|
87855
87861
|
const turnId = randomUUID5();
|
|
87856
87862
|
let resolveDone = () => void 0;
|
|
87857
|
-
const done = new Promise((
|
|
87863
|
+
const done = new Promise((resolve25) => resolveDone = resolve25);
|
|
87858
87864
|
active2.set(threadKey, { turnId, controller, done });
|
|
87859
87865
|
try {
|
|
87860
87866
|
const client = await clientFor();
|
|
@@ -88366,6 +88372,7 @@ var init_errors7 = __esm({
|
|
|
88366
88372
|
"no-output": "invalid",
|
|
88367
88373
|
"too-large": "invalid",
|
|
88368
88374
|
"site-file": "invalid",
|
|
88375
|
+
domain: "invalid",
|
|
88369
88376
|
offline: "internal",
|
|
88370
88377
|
"rate-limited": "busy",
|
|
88371
88378
|
unpublished: "invalid",
|
|
@@ -88453,11 +88460,11 @@ async function collectFiles(dir, limits, hostName, folderLabel) {
|
|
|
88453
88460
|
if (limits.maxFileBytes !== null) {
|
|
88454
88461
|
const big = found.filter((file2) => file2.size > limits.maxFileBytes).sort((a, b) => b.size - a.size);
|
|
88455
88462
|
if (big.length > 0) {
|
|
88456
|
-
const
|
|
88457
|
-
const name3 = relative9(dir,
|
|
88463
|
+
const first3 = big[0];
|
|
88464
|
+
const name3 = relative9(dir, first3.absolute).split(sep8).join("/");
|
|
88458
88465
|
throw new DeployError(
|
|
88459
88466
|
"too-large",
|
|
88460
|
-
`\u201C${name3}\u201D is ${formatBytes(
|
|
88467
|
+
`\u201C${name3}\u201D is ${formatBytes(first3.size)}, and ${hostName} takes files up to ${formatBytes(limits.maxFileBytes)}.${big.length > 1 ? ` ${big.length - 1} other ${big.length === 2 ? "file is" : "files are"} too big as well.` : ""} Make ${big.length > 1 ? "them" : "it"} smaller or move ${big.length > 1 ? "them" : "it"} elsewhere. Nothing was uploaded.`,
|
|
88461
88468
|
big.map((file2) => `${relative9(dir, file2.absolute)} ${file2.size}`).join("\n")
|
|
88462
88469
|
);
|
|
88463
88470
|
}
|
|
@@ -88537,11 +88544,11 @@ var init_files7 = __esm({
|
|
|
88537
88544
|
|
|
88538
88545
|
// ../core/src/deploy/http.ts
|
|
88539
88546
|
function wait(ms, signal) {
|
|
88540
|
-
return new Promise((
|
|
88541
|
-
const timer = setTimeout(
|
|
88547
|
+
return new Promise((resolve25) => {
|
|
88548
|
+
const timer = setTimeout(resolve25, ms);
|
|
88542
88549
|
signal?.addEventListener("abort", () => {
|
|
88543
88550
|
clearTimeout(timer);
|
|
88544
|
-
|
|
88551
|
+
resolve25();
|
|
88545
88552
|
});
|
|
88546
88553
|
});
|
|
88547
88554
|
}
|
|
@@ -88707,6 +88714,41 @@ var init_info2 = __esm({
|
|
|
88707
88714
|
}
|
|
88708
88715
|
});
|
|
88709
88716
|
|
|
88717
|
+
// ../core/src/deploy/domains.ts
|
|
88718
|
+
function normalizeHostname(input2) {
|
|
88719
|
+
let text7 = input2.trim().toLowerCase();
|
|
88720
|
+
text7 = text7.replace(/^[a-z]+:\/\//, "").replace(/[/?#].*$/, "").replace(/:\d+$/, "").replace(/\.$/, "");
|
|
88721
|
+
return text7;
|
|
88722
|
+
}
|
|
88723
|
+
function hostnameProblem(hostname3) {
|
|
88724
|
+
if (!hostname3) return "Type the address, for example \u201Cwww.example.com\u201D.";
|
|
88725
|
+
if (hostname3.includes("*")) return "Wildcard addresses can't be used. Type one address, for example \u201Cwww.example.com\u201D.";
|
|
88726
|
+
const labels = hostname3.split(".");
|
|
88727
|
+
if (hostname3.length > 253 || labels.length < 2 || !labels.every((label) => LABEL.test(label)) || !/^[a-z]{2,63}$/.test(labels.at(-1))) {
|
|
88728
|
+
return "That doesn't look like an address. Type it like \u201Cwww.example.com\u201D, without spaces.";
|
|
88729
|
+
}
|
|
88730
|
+
if (HOST_DEFAULTS.some((pattern) => pattern.test(hostname3))) return "That's one of the host's own addresses. Use an address on a domain you own.";
|
|
88731
|
+
return null;
|
|
88732
|
+
}
|
|
88733
|
+
function requireHostname(input2) {
|
|
88734
|
+
const hostname3 = normalizeHostname(input2);
|
|
88735
|
+
const problem = hostnameProblem(hostname3);
|
|
88736
|
+
if (problem) throw new DeployError("domain", problem, input2);
|
|
88737
|
+
return hostname3;
|
|
88738
|
+
}
|
|
88739
|
+
function apexOf(hostname3) {
|
|
88740
|
+
return hostname3.split(".").slice(-2).join(".");
|
|
88741
|
+
}
|
|
88742
|
+
var LABEL, HOST_DEFAULTS;
|
|
88743
|
+
var init_domains = __esm({
|
|
88744
|
+
"../core/src/deploy/domains.ts"() {
|
|
88745
|
+
"use strict";
|
|
88746
|
+
init_errors7();
|
|
88747
|
+
LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
88748
|
+
HOST_DEFAULTS = [/\.workers\.dev$/, /\.pages\.dev$/, /\.vercel\.app$/];
|
|
88749
|
+
}
|
|
88750
|
+
});
|
|
88751
|
+
|
|
88710
88752
|
// ../core/src/deploy/routing.ts
|
|
88711
88753
|
function checkCloudflareRedirects(text7) {
|
|
88712
88754
|
let staticRules = 0;
|
|
@@ -88894,6 +88936,28 @@ function workerForm(metadata) {
|
|
|
88894
88936
|
form.append(CLOUDFLARE_MODULE_NAME, new Blob([CLOUDFLARE_MODULE], { type: "application/javascript+module" }), CLOUDFLARE_MODULE_NAME);
|
|
88895
88937
|
return form;
|
|
88896
88938
|
}
|
|
88939
|
+
async function domainsFor(ctx, account, hostname3) {
|
|
88940
|
+
const list3 = await cf(ctx, "GET", `accounts/${encodeURIComponent(account)}/workers/domains`, "list the account's Worker domains", { query: { hostname: hostname3 } });
|
|
88941
|
+
return (list3 ?? []).filter((domain2) => domain2.hostname === hostname3);
|
|
88942
|
+
}
|
|
88943
|
+
async function changesetFor(ctx, account, project, hostname3) {
|
|
88944
|
+
const path6 = `${scriptPath(account, project)}/domains/changeset`;
|
|
88945
|
+
const response = await hostRequest(ctx, NAME, {
|
|
88946
|
+
method: "POST",
|
|
88947
|
+
path: path6,
|
|
88948
|
+
query: { replace_state: "true" },
|
|
88949
|
+
headers: { "content-type": "application/json" },
|
|
88950
|
+
body: JSON.stringify([{ hostname: hostname3 }]),
|
|
88951
|
+
retry: true
|
|
88952
|
+
});
|
|
88953
|
+
if (response.ok && response.body?.success !== false) return response.body?.result ?? {};
|
|
88954
|
+
const message2 = (response.body?.errors ?? []).map((error63) => error63.message ?? "").join(" ");
|
|
88955
|
+
if (response.status !== 401 && response.status !== 403 && /zone/i.test(message2)) return null;
|
|
88956
|
+
throw failure3(response, "POST", path6, "check the address");
|
|
88957
|
+
}
|
|
88958
|
+
function domainPlan(hostname3, status2, summary3, extra2 = {}) {
|
|
88959
|
+
return { hostname: hostname3, status: status2, summary: summary3, canAttach: status2 === "ready", ...extra2 };
|
|
88960
|
+
}
|
|
88897
88961
|
function createCloudflareTarget() {
|
|
88898
88962
|
return {
|
|
88899
88963
|
id: "cloudflare",
|
|
@@ -88932,6 +88996,59 @@ function createCloudflareTarget() {
|
|
|
88932
88996
|
}
|
|
88933
88997
|
return { project: name3, productionUrl: productionAddress(name3, subdomain) };
|
|
88934
88998
|
},
|
|
88999
|
+
async planDomain(ctx, { account, project, hostname: hostname3 }) {
|
|
89000
|
+
const apex = apexOf(hostname3);
|
|
89001
|
+
const worker = await workerState(ctx, account, project);
|
|
89002
|
+
if (!worker.exists || !worker.hasVersions) {
|
|
89003
|
+
return domainPlan(hostname3, "not-online", "Put the site online first; then it can answer on your own address.");
|
|
89004
|
+
}
|
|
89005
|
+
const existing = await domainsFor(ctx, account, hostname3);
|
|
89006
|
+
if (existing.some((domain2) => domain2.service === project)) {
|
|
89007
|
+
return domainPlan(hostname3, "already", `${hostname3} already shows this site.`);
|
|
89008
|
+
}
|
|
89009
|
+
if (existing.length > 0) {
|
|
89010
|
+
return domainPlan(hostname3, "taken", `${hostname3} already shows another Worker in this account (\u201C${existing[0].service ?? "unnamed"}\u201D). Choose another address, or free that one on Cloudflare first. Nothing was changed.`);
|
|
89011
|
+
}
|
|
89012
|
+
const changeset = await changesetFor(ctx, account, project, hostname3);
|
|
89013
|
+
if (!changeset) {
|
|
89014
|
+
return domainPlan(
|
|
89015
|
+
hostname3,
|
|
89016
|
+
"not-in-account",
|
|
89017
|
+
`${apex} isn't a domain in this Cloudflare account, so Cloudflare can't answer ${hostname3} with this site \u2014 no DNS record elsewhere can do it. Add ${apex} to this Cloudflare account first (it moves the domain's DNS to Cloudflare), or use an address on a domain that is already there.`,
|
|
89018
|
+
{ helpUrl: ADD_DOMAIN_HELP }
|
|
89019
|
+
);
|
|
89020
|
+
}
|
|
89021
|
+
if ((changeset.conflicting ?? []).some((domain2) => domain2.hostname === hostname3)) {
|
|
89022
|
+
return domainPlan(
|
|
89023
|
+
hostname3,
|
|
89024
|
+
"dns-conflict",
|
|
89025
|
+
`${apex} already has a DNS record for ${hostname3}. This app never replaces DNS records: remove or rename that record on Cloudflare (DNS \u203A Records), then check again. Nothing was changed.`,
|
|
89026
|
+
{ helpUrl: "https://developers.cloudflare.com/dns/manage-dns-records/how-to/create-dns-records/" }
|
|
89027
|
+
);
|
|
89028
|
+
}
|
|
89029
|
+
const zone = (changeset.added ?? []).find((domain2) => domain2.hostname === hostname3)?.zone_name ?? apex;
|
|
89030
|
+
return domainPlan(hostname3, "ready", `Cloudflare will answer ${hostname3} with this site and set up its certificate. Nothing else on ${zone} changes.`);
|
|
89031
|
+
},
|
|
89032
|
+
async attachDomain(ctx, input2) {
|
|
89033
|
+
const plan2 = await this.planDomain(ctx, input2);
|
|
89034
|
+
if (plan2.status === "already") return {};
|
|
89035
|
+
if (plan2.status !== "ready") throw new DeployError("domain", plan2.summary, plan2.status);
|
|
89036
|
+
const changeset = await changesetFor(ctx, input2.account, input2.project, input2.hostname);
|
|
89037
|
+
const zone = (changeset?.added ?? []).find((domain2) => domain2.hostname === input2.hostname);
|
|
89038
|
+
await cf(ctx, "PUT", `accounts/${encodeURIComponent(input2.account)}/workers/domains`, "attach the address", {
|
|
89039
|
+
json: { hostname: input2.hostname, service: input2.project, ...zone?.zone_id ? { zone_id: zone.zone_id } : {} }
|
|
89040
|
+
});
|
|
89041
|
+
return {};
|
|
89042
|
+
},
|
|
89043
|
+
async domainStatus(ctx, { account, project, hostname: hostname3 }) {
|
|
89044
|
+
return { ready: (await domainsFor(ctx, account, hostname3)).some((domain2) => domain2.service === project) };
|
|
89045
|
+
},
|
|
89046
|
+
async detachDomain(ctx, { account, project, hostname: hostname3 }) {
|
|
89047
|
+
for (const domain2 of await domainsFor(ctx, account, hostname3)) {
|
|
89048
|
+
if (domain2.service !== project || !domain2.id) continue;
|
|
89049
|
+
await cf(ctx, "DELETE", `accounts/${encodeURIComponent(account)}/workers/domains/${encodeURIComponent(domain2.id)}`, "stop using the address");
|
|
89050
|
+
}
|
|
89051
|
+
},
|
|
88935
89052
|
async deploy(ctx, input2) {
|
|
88936
89053
|
const { account, project, kind } = input2;
|
|
88937
89054
|
const routing = {};
|
|
@@ -89008,7 +89125,7 @@ function createCloudflareTarget() {
|
|
|
89008
89125
|
}
|
|
89009
89126
|
};
|
|
89010
89127
|
}
|
|
89011
|
-
var CLOUDFLARE_API, NAME, CLOUDFLARE_MODULE_NAME, CLOUDFLARE_MODULE, CLOUDFLARE_COMPATIBILITY_DATE, UPLOAD_PARALLEL, UPLOAD_CHUNK, PERMISSION, scriptPath;
|
|
89128
|
+
var CLOUDFLARE_API, NAME, CLOUDFLARE_MODULE_NAME, CLOUDFLARE_MODULE, CLOUDFLARE_COMPATIBILITY_DATE, UPLOAD_PARALLEL, UPLOAD_CHUNK, PERMISSION, scriptPath, ADD_DOMAIN_HELP;
|
|
89012
89129
|
var init_cloudflare = __esm({
|
|
89013
89130
|
"../core/src/deploy/cloudflare.ts"() {
|
|
89014
89131
|
"use strict";
|
|
@@ -89016,6 +89133,7 @@ var init_cloudflare = __esm({
|
|
|
89016
89133
|
init_files7();
|
|
89017
89134
|
init_http();
|
|
89018
89135
|
init_info2();
|
|
89136
|
+
init_domains();
|
|
89019
89137
|
init_routing();
|
|
89020
89138
|
CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
|
|
89021
89139
|
NAME = "Cloudflare";
|
|
@@ -89033,6 +89151,7 @@ export default {
|
|
|
89033
89151
|
UPLOAD_CHUNK = 50;
|
|
89034
89152
|
PERMISSION = "Edit the key on Cloudflare (My Profile \u203A API Tokens): under Permissions add Account \u203A Workers Scripts \u203A Edit, and under Account Resources include this account. Then try again.";
|
|
89035
89153
|
scriptPath = (account, name3) => `accounts/${encodeURIComponent(account)}/workers/scripts/${encodeURIComponent(name3)}`;
|
|
89154
|
+
ADD_DOMAIN_HELP = "https://developers.cloudflare.com/fundamentals/manage-domains/add-site/";
|
|
89036
89155
|
}
|
|
89037
89156
|
});
|
|
89038
89157
|
|
|
@@ -89071,11 +89190,11 @@ async function vercel(ctx, method, path6, doing, init = {}) {
|
|
|
89071
89190
|
return { status: response.status, body: response.body };
|
|
89072
89191
|
}
|
|
89073
89192
|
function wait2(ms, signal) {
|
|
89074
|
-
return new Promise((
|
|
89075
|
-
const timer = setTimeout(
|
|
89193
|
+
return new Promise((resolve25) => {
|
|
89194
|
+
const timer = setTimeout(resolve25, ms);
|
|
89076
89195
|
signal?.addEventListener("abort", () => {
|
|
89077
89196
|
clearTimeout(timer);
|
|
89078
|
-
|
|
89197
|
+
resolve25();
|
|
89079
89198
|
});
|
|
89080
89199
|
});
|
|
89081
89200
|
}
|
|
@@ -89094,6 +89213,18 @@ async function withVercelConfig(files, siteRoot) {
|
|
|
89094
89213
|
`, "utf8");
|
|
89095
89214
|
return [...rest, { path: "vercel.json", absolute: join33(siteRoot ?? ".", "vercel.json"), size: bytes.byteLength, sha1: sha1(bytes), cfHash: cloudflareHash(bytes, "vercel.json"), type: "application/json; charset=utf-8", bytes }];
|
|
89096
89215
|
}
|
|
89216
|
+
function recordsFrom(hostname3, config2, verification = []) {
|
|
89217
|
+
const records = [];
|
|
89218
|
+
const apex = hostname3.split(".").length === 2;
|
|
89219
|
+
const ipv43 = first2(config2?.recommendedIPv4)?.value?.[0];
|
|
89220
|
+
const cname = first2(config2?.recommendedCNAME)?.value;
|
|
89221
|
+
if (apex && ipv43) records.push({ type: "A", name: hostname3, value: ipv43 });
|
|
89222
|
+
else if (!apex && cname) records.push({ type: "CNAME", name: hostname3, value: cname.replace(/\.$/, "") });
|
|
89223
|
+
for (const challenge of verification ?? []) {
|
|
89224
|
+
if (challenge.type && challenge.domain && challenge.value) records.push({ type: challenge.type, name: challenge.domain, value: challenge.value });
|
|
89225
|
+
}
|
|
89226
|
+
return records;
|
|
89227
|
+
}
|
|
89097
89228
|
function createVercelTarget() {
|
|
89098
89229
|
async function upload(ctx, account, files, onSent) {
|
|
89099
89230
|
let sent = 0;
|
|
@@ -89162,6 +89293,46 @@ function createVercelTarget() {
|
|
|
89162
89293
|
}
|
|
89163
89294
|
return { project: name3, productionUrl: `https://${name3}.vercel.app` };
|
|
89164
89295
|
},
|
|
89296
|
+
async planDomain(ctx, { account, project, hostname: hostname3 }) {
|
|
89297
|
+
const apex = apexOf(hostname3);
|
|
89298
|
+
const found = await vercel(ctx, "GET", `v9/projects/${encodeURIComponent(project)}`, "look up the project", { query: team(account), allow: [404] });
|
|
89299
|
+
if (found.status === 404) return { hostname: hostname3, status: "not-online", summary: "Put the site online first; then it can answer on your own address.", canAttach: false };
|
|
89300
|
+
const existing = await vercel(ctx, "GET", `v9/projects/${encodeURIComponent(project)}/domains/${encodeURIComponent(hostname3)}`, "look up the address", { query: team(account), allow: [404] });
|
|
89301
|
+
if (existing.status === 200) return { hostname: hostname3, status: "already", summary: `${hostname3} is already one of this site's addresses on Vercel.`, canAttach: false };
|
|
89302
|
+
const config2 = await vercel(ctx, "GET", `v6/domains/${encodeURIComponent(hostname3)}/config`, "read the address's DNS", { query: { ...team(account), projectIdOrName: project } });
|
|
89303
|
+
if (config2.body && config2.body.misconfigured === false) {
|
|
89304
|
+
return { hostname: hostname3, status: "ready", summary: `Vercel will answer ${hostname3} with this site and set up its certificate. Its DNS already points at Vercel; nothing else on ${apex} changes.`, canAttach: true };
|
|
89305
|
+
}
|
|
89306
|
+
return {
|
|
89307
|
+
hostname: hostname3,
|
|
89308
|
+
status: "needs-dns",
|
|
89309
|
+
summary: `Vercel will answer ${hostname3} with this site once the DNS record below exists. This app adds the address to the project now; you create the record where ${apex}'s DNS is managed, then check again. Nothing else on ${apex} changes.`,
|
|
89310
|
+
records: recordsFrom(hostname3, config2.body),
|
|
89311
|
+
canAttach: true,
|
|
89312
|
+
helpUrl: "https://vercel.com/docs/domains/working-with-domains/add-a-domain"
|
|
89313
|
+
};
|
|
89314
|
+
},
|
|
89315
|
+
async attachDomain(ctx, { account, project, hostname: hostname3 }) {
|
|
89316
|
+
const added = await vercel(ctx, "POST", `v10/projects/${encodeURIComponent(project)}/domains`, "add the address", { query: team(account), json: { name: hostname3 }, allow: [409] });
|
|
89317
|
+
if (added.status === 409) {
|
|
89318
|
+
throw new DeployError("domain", `${hostname3} is already used by another Vercel project. Remove it there, or choose another address. Nothing was changed.`, added.body?.error?.message);
|
|
89319
|
+
}
|
|
89320
|
+
const config2 = await vercel(ctx, "GET", `v6/domains/${encodeURIComponent(hostname3)}/config`, "read the address's DNS", { query: { ...team(account), projectIdOrName: project } });
|
|
89321
|
+
return { records: config2.body?.misconfigured === false && added.body?.verified !== false ? [] : recordsFrom(hostname3, config2.body, added.body?.verification) };
|
|
89322
|
+
},
|
|
89323
|
+
async domainStatus(ctx, { account, project, hostname: hostname3 }) {
|
|
89324
|
+
const path6 = `v9/projects/${encodeURIComponent(project)}/domains/${encodeURIComponent(hostname3)}`;
|
|
89325
|
+
let domain2 = (await vercel(ctx, "GET", path6, "look up the address", { query: team(account) })).body;
|
|
89326
|
+
if (domain2 && domain2.verified === false) {
|
|
89327
|
+
domain2 = (await vercel(ctx, "POST", `${path6}/verify`, "verify the address", { query: team(account), allow: [400] })).body ?? domain2;
|
|
89328
|
+
}
|
|
89329
|
+
const config2 = await vercel(ctx, "GET", `v6/domains/${encodeURIComponent(hostname3)}/config`, "read the address's DNS", { query: { ...team(account), projectIdOrName: project } });
|
|
89330
|
+
const ready = domain2?.verified !== false && config2.body?.misconfigured === false;
|
|
89331
|
+
return ready ? { ready } : { ready, records: recordsFrom(hostname3, config2.body, domain2?.verified === false ? domain2.verification : []) };
|
|
89332
|
+
},
|
|
89333
|
+
async detachDomain(ctx, { account, project, hostname: hostname3 }) {
|
|
89334
|
+
await vercel(ctx, "DELETE", `v9/projects/${encodeURIComponent(project)}/domains/${encodeURIComponent(hostname3)}`, "stop using the address", { query: team(account), allow: [404] });
|
|
89335
|
+
},
|
|
89165
89336
|
async deploy(ctx, input2) {
|
|
89166
89337
|
const { account, project, kind } = input2;
|
|
89167
89338
|
const files = await withVercelConfig(input2.files, input2.siteRoot);
|
|
@@ -89222,7 +89393,7 @@ function createVercelTarget() {
|
|
|
89222
89393
|
}
|
|
89223
89394
|
};
|
|
89224
89395
|
}
|
|
89225
|
-
var VERCEL_API, NAME2, VERCEL_PERSONAL, UPLOAD_PARALLEL2, READY_TIMEOUT_MS, POLL_MS2, STATIC_SETTINGS;
|
|
89396
|
+
var VERCEL_API, NAME2, VERCEL_PERSONAL, UPLOAD_PARALLEL2, READY_TIMEOUT_MS, POLL_MS2, STATIC_SETTINGS, first2;
|
|
89226
89397
|
var init_vercel = __esm({
|
|
89227
89398
|
"../core/src/deploy/vercel.ts"() {
|
|
89228
89399
|
"use strict";
|
|
@@ -89230,6 +89401,7 @@ var init_vercel = __esm({
|
|
|
89230
89401
|
init_files7();
|
|
89231
89402
|
init_http();
|
|
89232
89403
|
init_info2();
|
|
89404
|
+
init_domains();
|
|
89233
89405
|
init_routing();
|
|
89234
89406
|
VERCEL_API = "https://api.vercel.com";
|
|
89235
89407
|
NAME2 = "Vercel";
|
|
@@ -89238,6 +89410,7 @@ var init_vercel = __esm({
|
|
|
89238
89410
|
READY_TIMEOUT_MS = 10 * 6e4;
|
|
89239
89411
|
POLL_MS2 = 1500;
|
|
89240
89412
|
STATIC_SETTINGS = { framework: null, buildCommand: null, installCommand: null, devCommand: null, outputDirectory: null };
|
|
89413
|
+
first2 = (items) => [...items ?? []].sort((a, b) => (a.rank ?? 99) - (b.rank ?? 99))[0];
|
|
89241
89414
|
}
|
|
89242
89415
|
});
|
|
89243
89416
|
|
|
@@ -89866,9 +90039,9 @@ import { randomUUID as randomUUID8 } from "node:crypto";
|
|
|
89866
90039
|
import { mkdir as mkdir11, readdir as readdir12, readFile as readFile24, rm as rm9, stat as stat15, writeFile as writeFile11 } from "node:fs/promises";
|
|
89867
90040
|
import { join as join35 } from "node:path";
|
|
89868
90041
|
function defaultSleep(ms, signal) {
|
|
89869
|
-
return new Promise((
|
|
90042
|
+
return new Promise((resolve25, reject) => {
|
|
89870
90043
|
if (signal.aborted) return reject(new Error("stopped"));
|
|
89871
|
-
const timer = setTimeout(
|
|
90044
|
+
const timer = setTimeout(resolve25, ms);
|
|
89872
90045
|
signal.addEventListener(
|
|
89873
90046
|
"abort",
|
|
89874
90047
|
() => {
|
|
@@ -91129,7 +91302,7 @@ function isPublicAddress(address2) {
|
|
|
91129
91302
|
function describeHost(url2) {
|
|
91130
91303
|
return url2.hostname.replace(/^\[|\]$/g, "");
|
|
91131
91304
|
}
|
|
91132
|
-
async function checkTarget(url2, options2,
|
|
91305
|
+
async function checkTarget(url2, options2, resolve25) {
|
|
91133
91306
|
if (url2.protocol !== "https:" && !(options2.allowHttp && url2.protocol === "http:")) {
|
|
91134
91307
|
throw new OutboundRefused("Only secure (https://) addresses can be used here.", url2.protocol);
|
|
91135
91308
|
}
|
|
@@ -91143,7 +91316,7 @@ async function checkTarget(url2, options2, resolve24) {
|
|
|
91143
91316
|
addresses = [{ address: host3, family: isIP(host3) === 6 ? 6 : 4 }];
|
|
91144
91317
|
} else {
|
|
91145
91318
|
try {
|
|
91146
|
-
addresses = await
|
|
91319
|
+
addresses = await resolve25(host3);
|
|
91147
91320
|
} catch (error63) {
|
|
91148
91321
|
throw new OutboundRefused(`${host3} couldn't be found. Check the address.`, error63 instanceof Error ? error63.message : String(error63));
|
|
91149
91322
|
}
|
|
@@ -91158,7 +91331,7 @@ async function checkTarget(url2, options2, resolve24) {
|
|
|
91158
91331
|
return addresses[0];
|
|
91159
91332
|
}
|
|
91160
91333
|
function createGuardedFetch(deps = {}) {
|
|
91161
|
-
const
|
|
91334
|
+
const resolve25 = deps.resolve ?? systemResolver;
|
|
91162
91335
|
const transport = deps.transport ?? nodeTransport;
|
|
91163
91336
|
return async (raw2, init = {}, options2 = {}) => {
|
|
91164
91337
|
let url2;
|
|
@@ -91170,7 +91343,7 @@ function createGuardedFetch(deps = {}) {
|
|
|
91170
91343
|
const limits = { timeoutMs: options2.timeoutMs ?? 8e3, maxBytes: options2.maxBytes ?? 1024 * 1024 };
|
|
91171
91344
|
const firstHost = describeHost(url2).toLowerCase();
|
|
91172
91345
|
for (let hop = 0; ; hop += 1) {
|
|
91173
|
-
const pinned = await checkTarget(url2, options2,
|
|
91346
|
+
const pinned = await checkTarget(url2, options2, resolve25);
|
|
91174
91347
|
const response = await transport(url2, init, pinned, limits);
|
|
91175
91348
|
if (response.status < 300 || response.status >= 400 || !response.headers.location) return response;
|
|
91176
91349
|
if (hop >= (options2.maxRedirects ?? 2)) throw new OutboundRefused("The address kept redirecting, so it wasn't followed.");
|
|
@@ -91919,7 +92092,7 @@ function safeDecode3(str2) {
|
|
|
91919
92092
|
return str2;
|
|
91920
92093
|
}
|
|
91921
92094
|
}
|
|
91922
|
-
function
|
|
92095
|
+
function normalizeHostname3(raw2, href) {
|
|
91923
92096
|
const hostname3 = raw2 || "";
|
|
91924
92097
|
if (!hostname3) {
|
|
91925
92098
|
return "";
|
|
@@ -91953,7 +92126,7 @@ var init_url = __esm({
|
|
|
91953
92126
|
} catch (err) {
|
|
91954
92127
|
return legacyParse(normalized2, parseQueryString, err);
|
|
91955
92128
|
}
|
|
91956
|
-
const hostname3 =
|
|
92129
|
+
const hostname3 = normalizeHostname3(u.hostname, u.href);
|
|
91957
92130
|
const port = u.port || null;
|
|
91958
92131
|
const pathname = u.pathname || null;
|
|
91959
92132
|
const search = u.search || null;
|
|
@@ -92634,8 +92807,8 @@ function resolveContent(data, key, options2, callback2) {
|
|
|
92634
92807
|
options2 = options2 || {};
|
|
92635
92808
|
let promise3;
|
|
92636
92809
|
if (!callback2) {
|
|
92637
|
-
promise3 = new Promise((
|
|
92638
|
-
callback2 = callbackPromise(
|
|
92810
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
92811
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
92639
92812
|
});
|
|
92640
92813
|
}
|
|
92641
92814
|
resolveContentValue(data, key, options2, callback2);
|
|
@@ -93131,12 +93304,12 @@ var init_shared3 = __esm({
|
|
|
93131
93304
|
});
|
|
93132
93305
|
return response;
|
|
93133
93306
|
};
|
|
93134
|
-
callbackPromise = (
|
|
93307
|
+
callbackPromise = (resolve25, reject) => function(...args) {
|
|
93135
93308
|
const err = args.shift();
|
|
93136
93309
|
if (err) {
|
|
93137
93310
|
reject(err);
|
|
93138
93311
|
} else {
|
|
93139
|
-
|
|
93312
|
+
resolve25(...args);
|
|
93140
93313
|
}
|
|
93141
93314
|
};
|
|
93142
93315
|
parseDataURI = (uri) => {
|
|
@@ -97458,8 +97631,8 @@ var init_mime_node = __esm({
|
|
|
97458
97631
|
build(callback2) {
|
|
97459
97632
|
let promise3;
|
|
97460
97633
|
if (!callback2) {
|
|
97461
|
-
promise3 = new Promise((
|
|
97462
|
-
callback2 = callbackPromise(
|
|
97634
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
97635
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
97463
97636
|
});
|
|
97464
97637
|
}
|
|
97465
97638
|
const done = callback2;
|
|
@@ -100067,8 +100240,8 @@ var init_mailer = __esm({
|
|
|
100067
100240
|
sendMail(data, callback2 = null) {
|
|
100068
100241
|
let promise3;
|
|
100069
100242
|
if (!callback2) {
|
|
100070
|
-
promise3 = new Promise((
|
|
100071
|
-
callback2 = callbackPromise(
|
|
100243
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
100244
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
100072
100245
|
});
|
|
100073
100246
|
}
|
|
100074
100247
|
const done = callback2;
|
|
@@ -100914,7 +101087,7 @@ var init_smtp_connection = __esm({
|
|
|
100914
101087
|
const handler = this.customAuth.get(this._authMethod);
|
|
100915
101088
|
let lastResponse;
|
|
100916
101089
|
let returned = false;
|
|
100917
|
-
const
|
|
101090
|
+
const resolve25 = () => {
|
|
100918
101091
|
if (returned) {
|
|
100919
101092
|
return;
|
|
100920
101093
|
}
|
|
@@ -100938,8 +101111,8 @@ var init_smtp_connection = __esm({
|
|
|
100938
101111
|
const sendCommand = (cmd, done) => {
|
|
100939
101112
|
let promise3;
|
|
100940
101113
|
if (!done) {
|
|
100941
|
-
promise3 = new Promise((
|
|
100942
|
-
done = callbackPromise(
|
|
101114
|
+
promise3 = new Promise((resolve26, reject2) => {
|
|
101115
|
+
done = callbackPromise(resolve26, reject2);
|
|
100943
101116
|
});
|
|
100944
101117
|
}
|
|
100945
101118
|
this._responseActions.push((str2) => {
|
|
@@ -100971,11 +101144,11 @@ var init_smtp_connection = __esm({
|
|
|
100971
101144
|
authMethods: [].concat(this._supportedAuth),
|
|
100972
101145
|
maxAllowedSize: this._maxAllowedSize || false,
|
|
100973
101146
|
sendCommand,
|
|
100974
|
-
resolve:
|
|
101147
|
+
resolve: resolve25,
|
|
100975
101148
|
reject
|
|
100976
101149
|
});
|
|
100977
101150
|
if (handlerResponse && typeof handlerResponse.catch === "function") {
|
|
100978
|
-
handlerResponse.then(
|
|
101151
|
+
handlerResponse.then(resolve25).catch(reject);
|
|
100979
101152
|
}
|
|
100980
101153
|
return;
|
|
100981
101154
|
}
|
|
@@ -104117,8 +104290,8 @@ var init_smtp_pool = __esm({
|
|
|
104117
104290
|
verify(callback2) {
|
|
104118
104291
|
let promise3;
|
|
104119
104292
|
if (!callback2) {
|
|
104120
|
-
promise3 = new Promise((
|
|
104121
|
-
callback2 = callbackPromise(
|
|
104293
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
104294
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
104122
104295
|
});
|
|
104123
104296
|
}
|
|
104124
104297
|
const done = callback2;
|
|
@@ -104440,8 +104613,8 @@ var init_smtp_transport = __esm({
|
|
|
104440
104613
|
verify(callback2) {
|
|
104441
104614
|
let promise3;
|
|
104442
104615
|
if (!callback2) {
|
|
104443
|
-
promise3 = new Promise((
|
|
104444
|
-
callback2 = callbackPromise(
|
|
104616
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
104617
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
104445
104618
|
});
|
|
104446
104619
|
}
|
|
104447
104620
|
const done = callback2;
|
|
@@ -105032,8 +105205,8 @@ var init_ses_transport = __esm({
|
|
|
105032
105205
|
verify(callback2) {
|
|
105033
105206
|
let promise3;
|
|
105034
105207
|
if (!callback2) {
|
|
105035
|
-
promise3 = new Promise((
|
|
105036
|
-
callback2 = callbackPromise(
|
|
105208
|
+
promise3 = new Promise((resolve25, reject) => {
|
|
105209
|
+
callback2 = callbackPromise(resolve25, reject);
|
|
105037
105210
|
});
|
|
105038
105211
|
}
|
|
105039
105212
|
const done = callback2;
|
|
@@ -109193,7 +109366,7 @@ var require_compile = __commonJS({
|
|
|
109193
109366
|
const schOrFunc = root.refs[ref2];
|
|
109194
109367
|
if (schOrFunc)
|
|
109195
109368
|
return schOrFunc;
|
|
109196
|
-
let _sch =
|
|
109369
|
+
let _sch = resolve25.call(this, root, ref2);
|
|
109197
109370
|
if (_sch === void 0) {
|
|
109198
109371
|
const schema = (_a4 = root.localRefs) === null || _a4 === void 0 ? void 0 : _a4[ref2];
|
|
109199
109372
|
const { schemaId } = this.opts;
|
|
@@ -109220,7 +109393,7 @@ var require_compile = __commonJS({
|
|
|
109220
109393
|
function sameSchemaEnv(s1, s2) {
|
|
109221
109394
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
109222
109395
|
}
|
|
109223
|
-
function
|
|
109396
|
+
function resolve25(root, ref2) {
|
|
109224
109397
|
let sch;
|
|
109225
109398
|
while (typeof (sch = this.refs[ref2]) == "string")
|
|
109226
109399
|
ref2 = sch;
|
|
@@ -110084,7 +110257,7 @@ var require_fast_uri = __commonJS({
|
|
|
110084
110257
|
}
|
|
110085
110258
|
return uri;
|
|
110086
110259
|
}
|
|
110087
|
-
function
|
|
110260
|
+
function resolve25(baseURI, relativeURI, options2) {
|
|
110088
110261
|
const schemelessOptions = options2 ? Object.assign({ scheme: "null" }, options2) : { scheme: "null" };
|
|
110089
110262
|
const {
|
|
110090
110263
|
parsed: baseParsed,
|
|
@@ -110475,7 +110648,7 @@ var require_fast_uri = __commonJS({
|
|
|
110475
110648
|
var fastUri = {
|
|
110476
110649
|
SCHEMES,
|
|
110477
110650
|
normalize: normalize3,
|
|
110478
|
-
resolve:
|
|
110651
|
+
resolve: resolve25,
|
|
110479
110652
|
resolveComponent,
|
|
110480
110653
|
equal,
|
|
110481
110654
|
serialize: serialize3,
|
|
@@ -113960,7 +114133,7 @@ function createPluginRegistry(options2 = {}) {
|
|
|
113960
114133
|
}
|
|
113961
114134
|
};
|
|
113962
114135
|
}
|
|
113963
|
-
function
|
|
114136
|
+
function resolve25(list3, kind, collect2, idOf) {
|
|
113964
114137
|
const winners = /* @__PURE__ */ new Map();
|
|
113965
114138
|
const conflicts = /* @__PURE__ */ new Map();
|
|
113966
114139
|
for (const entry of byPrecedence(list3)) {
|
|
@@ -113981,24 +114154,24 @@ function createPluginRegistry(options2 = {}) {
|
|
|
113981
114154
|
return { items: ordered2, conflicts: [...conflicts.values()] };
|
|
113982
114155
|
}
|
|
113983
114156
|
const kinds = {
|
|
113984
|
-
adapters: (list3) =>
|
|
113985
|
-
images: (list3) =>
|
|
114157
|
+
adapters: (list3) => resolve25(list3, "adapter", (entry) => entry.plugin?.adapters, (adapter) => adapter.id),
|
|
114158
|
+
images: (list3) => resolve25(
|
|
113986
114159
|
list3.filter((entry) => entry.source !== "site"),
|
|
113987
114160
|
"imageProvider",
|
|
113988
114161
|
(entry) => entry.images ??= (entry.plugin?.imageProviders ?? []).map((provider) => imageHandle(provider, contributionOwner(entry))),
|
|
113989
114162
|
(handle2) => handle2.id
|
|
113990
114163
|
),
|
|
113991
|
-
videos: (list3) =>
|
|
114164
|
+
videos: (list3) => resolve25(
|
|
113992
114165
|
list3.filter((entry) => entry.source !== "site"),
|
|
113993
114166
|
"videoProvider",
|
|
113994
114167
|
(entry) => entry.videos ??= (entry.plugin?.videoProviders ?? []).map((provider) => videoHandle(provider, contributionOwner(entry))),
|
|
113995
114168
|
(handle2) => handle2.id
|
|
113996
114169
|
),
|
|
113997
|
-
forms: (list3) =>
|
|
113998
|
-
scripts: (list3) =>
|
|
113999
|
-
importers: (list3) =>
|
|
114000
|
-
deploy: (list3) =>
|
|
114001
|
-
tools: (list3) =>
|
|
114170
|
+
forms: (list3) => resolve25(list3, "formProvider", (entry) => entry.plugin?.formProviders, (provider) => provider.id),
|
|
114171
|
+
scripts: (list3) => resolve25(list3, "scriptIntegration", (entry) => entry.plugin?.scriptIntegrations, (integration) => integration.kind),
|
|
114172
|
+
importers: (list3) => resolve25(list3, "importer", (entry) => entry.plugin?.importers, (importer) => importer.id),
|
|
114173
|
+
deploy: (list3) => resolve25(list3, "deployTarget", (entry) => entry.plugin?.deployTargets, (target) => target.id),
|
|
114174
|
+
tools: (list3) => resolve25(
|
|
114002
114175
|
list3,
|
|
114003
114176
|
"tool",
|
|
114004
114177
|
(entry) => {
|
|
@@ -114015,7 +114188,7 @@ function createPluginRegistry(options2 = {}) {
|
|
|
114015
114188
|
},
|
|
114016
114189
|
(tool) => tool.name
|
|
114017
114190
|
),
|
|
114018
|
-
dataSources: (list3) =>
|
|
114191
|
+
dataSources: (list3) => resolve25(list3, "dataSource", (entry) => entry.plugin?.dataSources, (source2) => source2.id)
|
|
114019
114192
|
};
|
|
114020
114193
|
function contributions(plugin) {
|
|
114021
114194
|
return {
|
|
@@ -114873,6 +115046,10 @@ var init_source = __esm({
|
|
|
114873
115046
|
});
|
|
114874
115047
|
|
|
114875
115048
|
// ../core/src/deploy/service.ts
|
|
115049
|
+
function hasCustomAddress(config2) {
|
|
115050
|
+
if (config2.domain && !config2.domain.pending) return true;
|
|
115051
|
+
return Boolean(config2.productionUrl) && config2.productionUrl !== config2.defaultUrl && !HOST_ADDRESS.test(config2.productionUrl);
|
|
115052
|
+
}
|
|
114876
115053
|
function normalizeUrl(url2) {
|
|
114877
115054
|
return (url2 ?? "").trim().replace(/\/+$/, "").toLowerCase();
|
|
114878
115055
|
}
|
|
@@ -114883,6 +115060,20 @@ function createDeployService(options2) {
|
|
|
114883
115060
|
const doFetch = options2.fetch ?? fetch;
|
|
114884
115061
|
const running = /* @__PURE__ */ new Map();
|
|
114885
115062
|
const lastJob = /* @__PURE__ */ new Map();
|
|
115063
|
+
const lastDomainJob = /* @__PURE__ */ new Map();
|
|
115064
|
+
const domainRecords = /* @__PURE__ */ new Map();
|
|
115065
|
+
const probeTemplate = env.GALLEY_DEPLOY_PROBE?.trim();
|
|
115066
|
+
const probe2 = options2.probe ?? (async (hostname3) => {
|
|
115067
|
+
const url2 = probeTemplate ? probeTemplate.replace("{host}", encodeURIComponent(hostname3)) : `https://${hostname3}/`;
|
|
115068
|
+
try {
|
|
115069
|
+
const response = await doFetch(url2, { method: probeTemplate ? "GET" : "HEAD", redirect: "manual", signal: AbortSignal.timeout(1e4) });
|
|
115070
|
+
return probeTemplate ? response.ok : true;
|
|
115071
|
+
} catch {
|
|
115072
|
+
return false;
|
|
115073
|
+
}
|
|
115074
|
+
});
|
|
115075
|
+
const waitMs = options2.domainWaitMs ?? 10 * 6e4;
|
|
115076
|
+
const pollMs = options2.domainPollMs ?? 5e3;
|
|
114886
115077
|
function targetFor2(id5) {
|
|
114887
115078
|
const target = targets.find((candidate) => candidate.id === id5);
|
|
114888
115079
|
if (!target) throw new DeployError("not-set-up", "That host isn't one this app can put sites on.", String(id5));
|
|
@@ -114958,12 +115149,15 @@ function createDeployService(options2) {
|
|
|
114958
115149
|
onProgress: ({ detail, progress }) => job.update({ detail, ...progress !== void 0 ? { progress: 0.4 + progress * 0.55 } : {} }, progress === void 0 || progress === 0 || progress === 1 ? STEP : {})
|
|
114959
115150
|
});
|
|
114960
115151
|
const author = await who();
|
|
115152
|
+
const latest = start.kind === "production" ? await readDeployConfig(site) : null;
|
|
115153
|
+
const hostDefault = outcome.productionUrl ?? (start.kind === "production" ? project.productionUrl : void 0);
|
|
115154
|
+
const custom2 = latest ? hasCustomAddress(latest) : false;
|
|
114961
115155
|
const record3 = {
|
|
114962
115156
|
id: outcome.id,
|
|
114963
115157
|
kind: start.kind,
|
|
114964
115158
|
target: target.id,
|
|
114965
115159
|
project: project.project,
|
|
114966
|
-
url: outcome.url,
|
|
115160
|
+
url: custom2 && latest?.productionUrl ? latest.productionUrl : outcome.url,
|
|
114967
115161
|
commit: built.commit,
|
|
114968
115162
|
createdAt: outcome.createdAt,
|
|
114969
115163
|
...author ? { who: author } : {},
|
|
@@ -114972,10 +115166,9 @@ function createDeployService(options2) {
|
|
|
114972
115166
|
bytes
|
|
114973
115167
|
};
|
|
114974
115168
|
await appendDeployment(options2.home, site.id, record3);
|
|
114975
|
-
|
|
114976
|
-
|
|
114977
|
-
|
|
114978
|
-
if (latest) await writeDeployConfig(site, { ...latest, productionUrl });
|
|
115169
|
+
if (latest && hostDefault) {
|
|
115170
|
+
const next = { ...latest, defaultUrl: hostDefault, ...custom2 ? {} : { productionUrl: hostDefault } };
|
|
115171
|
+
if (next.defaultUrl !== latest.defaultUrl || next.productionUrl !== latest.productionUrl) await writeDeployConfig(site, next);
|
|
114979
115172
|
}
|
|
114980
115173
|
return record3;
|
|
114981
115174
|
} catch (error63) {
|
|
@@ -115041,6 +115234,40 @@ function createDeployService(options2) {
|
|
|
115041
115234
|
}
|
|
115042
115235
|
return launch(site, config2, start);
|
|
115043
115236
|
}
|
|
115237
|
+
async function domainContext(site, input2) {
|
|
115238
|
+
const config2 = await readDeployConfig(site);
|
|
115239
|
+
if (!config2) throw new DeployError("not-set-up", "Put the site online first; then it can answer on your own address.");
|
|
115240
|
+
const target = targetFor2(config2.target);
|
|
115241
|
+
if (!target.planDomain || !target.attachDomain) throw new DeployError("domain", `Using your own address isn't available for ${target.name} here.`);
|
|
115242
|
+
return { config: config2, target, hostname: requireHostname(input2) };
|
|
115243
|
+
}
|
|
115244
|
+
async function waitForDomain(site, target, ctx, input2, job, records) {
|
|
115245
|
+
const { hostname: hostname3 } = input2;
|
|
115246
|
+
const started = Date.now();
|
|
115247
|
+
let said = false;
|
|
115248
|
+
for (; ; ) {
|
|
115249
|
+
const status2 = target.domainStatus ? await target.domainStatus(ctx, input2) : { ready: true };
|
|
115250
|
+
const needs = status2.records ?? records;
|
|
115251
|
+
if (!status2.ready && needs.length > 0) {
|
|
115252
|
+
domainRecords.set(site.id, needs);
|
|
115253
|
+
job.finish("done", { progress: 1, detail: `Create the DNS record for ${hostname3}, then check again.` });
|
|
115254
|
+
return;
|
|
115255
|
+
}
|
|
115256
|
+
if (status2.ready && await probe2(hostname3)) break;
|
|
115257
|
+
if (!said) {
|
|
115258
|
+
job.update({ detail: `Waiting for ${hostname3} to answer \u2014 ${target.name} is setting up its certificate\u2026`, progress: 0.5 }, STEP);
|
|
115259
|
+
said = true;
|
|
115260
|
+
}
|
|
115261
|
+
if (Date.now() - started >= waitMs) {
|
|
115262
|
+
throw new DeployError("domain", `${hostname3} is attached but isn't answering over HTTPS yet \u2014 certificates can take a while. Check again in a few minutes; the site's address stays as it was until then.`);
|
|
115263
|
+
}
|
|
115264
|
+
await new Promise((resolve25) => setTimeout(resolve25, pollMs));
|
|
115265
|
+
}
|
|
115266
|
+
domainRecords.delete(site.id);
|
|
115267
|
+
const latest = await readDeployConfig(site);
|
|
115268
|
+
if (latest) await writeDeployConfig(site, { ...latest, productionUrl: `https://${hostname3}`, domain: { hostname: hostname3, attached: latest.domain?.hostname === hostname3 ? latest.domain.attached : false } });
|
|
115269
|
+
job.finish("done", { progress: 1, url: `https://${hostname3}`, detail: `${hostname3} answers` });
|
|
115270
|
+
}
|
|
115044
115271
|
const service = {
|
|
115045
115272
|
async targets() {
|
|
115046
115273
|
const statuses = await Promise.all(
|
|
@@ -115098,12 +115325,15 @@ function createDeployService(options2) {
|
|
|
115098
115325
|
const last = lastJob.get(site.id);
|
|
115099
115326
|
return {
|
|
115100
115327
|
config: config2,
|
|
115101
|
-
|
|
115328
|
+
// Shown at the live address the person chose, whatever the host called it at the time.
|
|
115329
|
+
production: production && config2?.productionUrl ? { ...production, url: config2.productionUrl } : production,
|
|
115102
115330
|
preview,
|
|
115103
115331
|
job: active2 ?? (last ? jobs2.get(last) : null),
|
|
115104
115332
|
behind,
|
|
115105
115333
|
liveAddressSet: Boolean(config2?.productionUrl) && normalizeUrl(model.urls.production) === normalizeUrl(config2?.productionUrl),
|
|
115106
|
-
suggestedProject: defaultProjectName(model.name)
|
|
115334
|
+
suggestedProject: defaultProjectName(model.name),
|
|
115335
|
+
domainJob: lastDomainJob.get(site.id) ? jobs2.get(lastDomainJob.get(site.id)) : null,
|
|
115336
|
+
...domainRecords.get(site.id)?.length ? { domainRecords: domainRecords.get(site.id) } : {}
|
|
115107
115337
|
};
|
|
115108
115338
|
},
|
|
115109
115339
|
async configure(site, patch) {
|
|
@@ -115161,6 +115391,79 @@ function createDeployService(options2) {
|
|
|
115161
115391
|
job(id5) {
|
|
115162
115392
|
return jobs2.get(id5);
|
|
115163
115393
|
},
|
|
115394
|
+
async planDomain(site, input2) {
|
|
115395
|
+
const { config: config2, target, hostname: hostname3 } = await domainContext(site, input2);
|
|
115396
|
+
return withHost(target, (ctx) => target.planDomain(ctx, { account: config2.account, project: config2.project, hostname: hostname3 }));
|
|
115397
|
+
},
|
|
115398
|
+
async attachDomain(site, input2) {
|
|
115399
|
+
const { config: config2, target, hostname: hostname3 } = await domainContext(site, input2);
|
|
115400
|
+
const running2 = lastDomainJob.get(site.id) ? jobs2.get(lastDomainJob.get(site.id)) : null;
|
|
115401
|
+
if (running2?.state === "running") throw new DeployError("busy", "An address is being set up right now. Wait for it to finish.");
|
|
115402
|
+
const job = jobs2.start("domain", `Using ${hostname3}`);
|
|
115403
|
+
job.update({ siteId: site.id, detail: `Checking ${hostname3}\u2026`, progress: 0 }, STEP);
|
|
115404
|
+
lastDomainJob.set(site.id, job.id);
|
|
115405
|
+
void (async () => {
|
|
115406
|
+
let ctx = null;
|
|
115407
|
+
try {
|
|
115408
|
+
ctx = await contextFor(target);
|
|
115409
|
+
const input3 = { account: config2.account, project: config2.project, hostname: hostname3 };
|
|
115410
|
+
const plan2 = await target.planDomain(ctx, input3);
|
|
115411
|
+
if (!plan2.canAttach && plan2.status !== "already") throw new DeployError("domain", plan2.summary, plan2.status);
|
|
115412
|
+
let records = [];
|
|
115413
|
+
if (plan2.status !== "already") {
|
|
115414
|
+
job.update({ detail: `Asking ${target.name} to answer ${hostname3}\u2026`, progress: 0.2 }, STEP);
|
|
115415
|
+
records = (await target.attachDomain(ctx, input3)).records ?? [];
|
|
115416
|
+
}
|
|
115417
|
+
const latest = await readDeployConfig(site) ?? config2;
|
|
115418
|
+
const attached = plan2.status !== "already" || latest.domain?.hostname === hostname3 && latest.domain.attached;
|
|
115419
|
+
await writeDeployConfig(site, { ...latest, domain: { hostname: hostname3, attached, pending: true } });
|
|
115420
|
+
await waitForDomain(site, target, ctx, input3, job, records);
|
|
115421
|
+
} catch (error63) {
|
|
115422
|
+
const clean4 = scrubError(error63, [ctx?.token]);
|
|
115423
|
+
job.finish("error", { detail: clean4.message, ...clean4.detail ? { output: clean4.detail } : {} });
|
|
115424
|
+
}
|
|
115425
|
+
})();
|
|
115426
|
+
return job.snapshot();
|
|
115427
|
+
},
|
|
115428
|
+
async checkDomain(site) {
|
|
115429
|
+
const config2 = await readDeployConfig(site);
|
|
115430
|
+
if (!config2?.domain) throw new DeployError("domain", "This site isn't using an address of its own.");
|
|
115431
|
+
const target = targetFor2(config2.target);
|
|
115432
|
+
const hostname3 = config2.domain.hostname;
|
|
115433
|
+
const job = jobs2.start("domain", `Using ${hostname3}`);
|
|
115434
|
+
job.update({ siteId: site.id, detail: `Checking ${hostname3}\u2026`, progress: 0.2 }, STEP);
|
|
115435
|
+
lastDomainJob.set(site.id, job.id);
|
|
115436
|
+
void (async () => {
|
|
115437
|
+
let ctx = null;
|
|
115438
|
+
try {
|
|
115439
|
+
ctx = await contextFor(target);
|
|
115440
|
+
await waitForDomain(site, target, ctx, { account: config2.account, project: config2.project, hostname: hostname3 }, job, domainRecords.get(site.id) ?? []);
|
|
115441
|
+
} catch (error63) {
|
|
115442
|
+
const clean4 = scrubError(error63, [ctx?.token]);
|
|
115443
|
+
job.finish("error", { detail: clean4.message, ...clean4.detail ? { output: clean4.detail } : {} });
|
|
115444
|
+
}
|
|
115445
|
+
})();
|
|
115446
|
+
return job.snapshot();
|
|
115447
|
+
},
|
|
115448
|
+
async detachDomain(site) {
|
|
115449
|
+
const config2 = await readDeployConfig(site);
|
|
115450
|
+
if (!config2?.domain) return service.status(site);
|
|
115451
|
+
const target = targetFor2(config2.target);
|
|
115452
|
+
const { hostname: hostname3, attached } = config2.domain;
|
|
115453
|
+
if (attached && target.detachDomain) {
|
|
115454
|
+
await withHost(target, (ctx) => target.detachDomain(ctx, { account: config2.account, project: config2.project, hostname: hostname3 }));
|
|
115455
|
+
}
|
|
115456
|
+
domainRecords.delete(site.id);
|
|
115457
|
+
const custom2 = `https://${hostname3}`;
|
|
115458
|
+
const { domain: _gone, productionUrl: _was, ...rest } = config2;
|
|
115459
|
+
const next = { ...rest, ...config2.defaultUrl ? { productionUrl: config2.defaultUrl } : {} };
|
|
115460
|
+
await writeDeployConfig(site, next, (file2) => {
|
|
115461
|
+
if (normalizeUrl(file2.urls?.production) !== normalizeUrl(custom2)) return file2;
|
|
115462
|
+
const { production: _old, ...urls } = file2.urls ?? {};
|
|
115463
|
+
return { ...file2, urls: config2.defaultUrl ? { ...urls, production: config2.defaultUrl } : urls };
|
|
115464
|
+
});
|
|
115465
|
+
return service.status(site);
|
|
115466
|
+
},
|
|
115164
115467
|
async suggestName(site) {
|
|
115165
115468
|
return defaultProjectName((await site.model()).name);
|
|
115166
115469
|
},
|
|
@@ -115173,7 +115476,7 @@ function createDeployService(options2) {
|
|
|
115173
115476
|
function deployMessage(error63) {
|
|
115174
115477
|
return error63 instanceof GalleyError ? error63.message : error63 instanceof Error ? error63.message : String(error63);
|
|
115175
115478
|
}
|
|
115176
|
-
var SECRET_ENV_HINT2, STEP;
|
|
115479
|
+
var SECRET_ENV_HINT2, STEP, HOST_ADDRESS;
|
|
115177
115480
|
var init_service4 = __esm({
|
|
115178
115481
|
"../core/src/deploy/service.ts"() {
|
|
115179
115482
|
"use strict";
|
|
@@ -115185,8 +115488,10 @@ var init_service4 = __esm({
|
|
|
115185
115488
|
init_names();
|
|
115186
115489
|
init_registry3();
|
|
115187
115490
|
init_source();
|
|
115491
|
+
init_domains();
|
|
115188
115492
|
SECRET_ENV_HINT2 = { cloudflare: "CLOUDFLARE_API_TOKEN", vercel: "VERCEL_TOKEN" };
|
|
115189
115493
|
STEP = { immediate: true };
|
|
115494
|
+
HOST_ADDRESS = /^https?:\/\/[^/]+\.(workers\.dev|pages\.dev|vercel\.app)\/?$/i;
|
|
115190
115495
|
}
|
|
115191
115496
|
});
|
|
115192
115497
|
|
|
@@ -115203,6 +115508,8 @@ var init_deploy = __esm({
|
|
|
115203
115508
|
init_history();
|
|
115204
115509
|
init_source();
|
|
115205
115510
|
init_info2();
|
|
115511
|
+
init_domains();
|
|
115512
|
+
init_service4();
|
|
115206
115513
|
}
|
|
115207
115514
|
});
|
|
115208
115515
|
|
|
@@ -117373,25 +117680,25 @@ var require_ContainerNode = __commonJS({
|
|
|
117373
117680
|
return this._firstChild;
|
|
117374
117681
|
} },
|
|
117375
117682
|
lastChild: { get: function() {
|
|
117376
|
-
var kids = this._childNodes,
|
|
117683
|
+
var kids = this._childNodes, first3;
|
|
117377
117684
|
if (kids) {
|
|
117378
117685
|
return kids.length === 0 ? null : kids[kids.length - 1];
|
|
117379
117686
|
}
|
|
117380
|
-
|
|
117381
|
-
if (
|
|
117687
|
+
first3 = this._firstChild;
|
|
117688
|
+
if (first3 === null) {
|
|
117382
117689
|
return null;
|
|
117383
117690
|
}
|
|
117384
|
-
return
|
|
117691
|
+
return first3._previousSibling;
|
|
117385
117692
|
} },
|
|
117386
117693
|
_ensureChildNodes: { value: function() {
|
|
117387
117694
|
if (this._childNodes) {
|
|
117388
117695
|
return;
|
|
117389
117696
|
}
|
|
117390
|
-
var
|
|
117391
|
-
if (
|
|
117697
|
+
var first3 = this._firstChild, kid = first3, childNodes = this._childNodes = new NodeList();
|
|
117698
|
+
if (first3) do {
|
|
117392
117699
|
childNodes.push(kid);
|
|
117393
117700
|
kid = kid._nextSibling;
|
|
117394
|
-
} while (kid !==
|
|
117701
|
+
} while (kid !== first3);
|
|
117395
117702
|
this._firstChild = null;
|
|
117396
117703
|
} },
|
|
117397
117704
|
// Remove all of this node's children. This is a minor
|
|
@@ -118862,22 +119169,22 @@ var require_Element = __commonJS({
|
|
|
118862
119169
|
}
|
|
118863
119170
|
},
|
|
118864
119171
|
_insertAdjacent: { value: function _insertAdjacent(position2, node2) {
|
|
118865
|
-
var
|
|
119172
|
+
var first3 = false;
|
|
118866
119173
|
switch (position2) {
|
|
118867
119174
|
case "beforebegin":
|
|
118868
|
-
|
|
119175
|
+
first3 = true;
|
|
118869
119176
|
/* falls through */
|
|
118870
119177
|
case "afterend":
|
|
118871
119178
|
var parent = this.parentNode;
|
|
118872
119179
|
if (parent === null) {
|
|
118873
119180
|
return null;
|
|
118874
119181
|
}
|
|
118875
|
-
return parent.insertBefore(node2,
|
|
119182
|
+
return parent.insertBefore(node2, first3 ? this : this.nextSibling);
|
|
118876
119183
|
case "afterbegin":
|
|
118877
|
-
|
|
119184
|
+
first3 = true;
|
|
118878
119185
|
/* falls through */
|
|
118879
119186
|
case "beforeend":
|
|
118880
|
-
return this.insertBefore(node2,
|
|
119187
|
+
return this.insertBefore(node2, first3 ? this.firstChild : null);
|
|
118881
119188
|
default:
|
|
118882
119189
|
return utils.SyntaxError();
|
|
118883
119190
|
}
|
|
@@ -133555,7 +133862,7 @@ function semaphore(limit2) {
|
|
|
133555
133862
|
let active2 = 0;
|
|
133556
133863
|
const waiting = [];
|
|
133557
133864
|
return async function run4(task) {
|
|
133558
|
-
if (active2 >= limit2) await new Promise((
|
|
133865
|
+
if (active2 >= limit2) await new Promise((resolve25) => waiting.push(resolve25));
|
|
133559
133866
|
active2 += 1;
|
|
133560
133867
|
try {
|
|
133561
133868
|
return await task();
|
|
@@ -133566,11 +133873,11 @@ function semaphore(limit2) {
|
|
|
133566
133873
|
};
|
|
133567
133874
|
}
|
|
133568
133875
|
function sleep2(ms, signal) {
|
|
133569
|
-
return new Promise((
|
|
133876
|
+
return new Promise((resolve25, reject) => {
|
|
133570
133877
|
if (signal?.aborted) return reject(aborted2());
|
|
133571
133878
|
const timer = setTimeout(() => {
|
|
133572
133879
|
signal?.removeEventListener("abort", onAbort);
|
|
133573
|
-
|
|
133880
|
+
resolve25();
|
|
133574
133881
|
}, ms);
|
|
133575
133882
|
const onAbort = () => {
|
|
133576
133883
|
clearTimeout(timer);
|
|
@@ -134087,29 +134394,29 @@ async function readRest(input2, options2 = {}) {
|
|
|
134087
134394
|
}
|
|
134088
134395
|
async function list3(route2, params, limit2) {
|
|
134089
134396
|
const perPage = Math.min(100, limit2 ?? 100);
|
|
134090
|
-
const
|
|
134091
|
-
if (
|
|
134397
|
+
const first3 = await getJson(endpoint(apiRoot, route2, { ...params, per_page: perPage, page: 1 }));
|
|
134398
|
+
if (first3.response.status === 401 || first3.response.status === 403) {
|
|
134092
134399
|
if (authenticated) {
|
|
134093
|
-
throw new ImportError("auth", "WordPress didn't accept the user name and application password. Check both (the password is the one made under Users \u203A Profile \u203A Application passwords) and try again.", `${route2}: ${
|
|
134400
|
+
throw new ImportError("auth", "WordPress didn't accept the user name and application password. Check both (the password is the one made under Users \u203A Profile \u203A Application passwords) and try again.", `${route2}: ${first3.response.status}`);
|
|
134094
134401
|
}
|
|
134095
|
-
throw blocked(siteUrl, `${route2}: ${
|
|
134402
|
+
throw blocked(siteUrl, `${route2}: ${first3.response.status}`);
|
|
134096
134403
|
}
|
|
134097
|
-
if (
|
|
134404
|
+
if (first3.response.status === 400 && authenticated && "status" in params) {
|
|
134098
134405
|
const { status: _ignored, ...rest2 } = params;
|
|
134099
134406
|
notes.push("This account can't list drafts on this site, so only published content was read.");
|
|
134100
134407
|
return list3(route2, rest2, limit2);
|
|
134101
134408
|
}
|
|
134102
|
-
if (!Array.isArray(
|
|
134103
|
-
if (
|
|
134104
|
-
throw blocked(siteUrl, `${route2}: ${
|
|
134409
|
+
if (!Array.isArray(first3.body)) {
|
|
134410
|
+
if (first3.response.status === 404) return [];
|
|
134411
|
+
throw blocked(siteUrl, `${route2}: ${first3.response.status} (not a list)`);
|
|
134105
134412
|
}
|
|
134106
|
-
const totalPages = Number(
|
|
134413
|
+
const totalPages = Number(first3.response.headers["x-wp-totalpages"] ?? 1) || 1;
|
|
134107
134414
|
const needed = limit2 ? Math.min(totalPages, Math.ceil(limit2 / perPage)) : totalPages;
|
|
134108
134415
|
const rest = await Promise.all(
|
|
134109
134416
|
Array.from({ length: Math.max(0, needed - 1) }, (_, i) => getJson(endpoint(apiRoot, route2, { ...params, per_page: perPage, page: i + 2 })))
|
|
134110
134417
|
);
|
|
134111
|
-
const all = [
|
|
134112
|
-
options2.onProgress?.({ phase: "read", label: `Read ${all.length} from ${route2}`, done: all.length, total: Number(
|
|
134418
|
+
const all = [first3.body, ...rest.map((page) => Array.isArray(page.body) ? page.body : [])].flat();
|
|
134419
|
+
options2.onProgress?.({ phase: "read", label: `Read ${all.length} from ${route2}`, done: all.length, total: Number(first3.response.headers["x-wp-total"] ?? all.length) });
|
|
134113
134420
|
return limit2 ? all.slice(0, limit2) : all;
|
|
134114
134421
|
}
|
|
134115
134422
|
function absorbEmbedded(post) {
|
|
@@ -136443,7 +136750,7 @@ async function readWxr(path6, options2 = {}) {
|
|
|
136443
136750
|
list3.push(item);
|
|
136444
136751
|
keepNewest(list3, options2.limit);
|
|
136445
136752
|
}
|
|
136446
|
-
await new Promise((
|
|
136753
|
+
await new Promise((resolve25, reject) => {
|
|
136447
136754
|
const stream2 = createReadStream3(path6, { encoding: "utf8", highWaterMark: 1 << 20 });
|
|
136448
136755
|
let read = 0;
|
|
136449
136756
|
const total2 = statSync14(path6).size;
|
|
@@ -136465,7 +136772,7 @@ async function readWxr(path6, options2 = {}) {
|
|
|
136465
136772
|
} catch {
|
|
136466
136773
|
errors2 += 1;
|
|
136467
136774
|
}
|
|
136468
|
-
|
|
136775
|
+
resolve25();
|
|
136469
136776
|
});
|
|
136470
136777
|
});
|
|
136471
136778
|
if (!sawChannel || !(channel["wp:base_site_url"] || channel["wp:wxr_version"] || channel.link)) {
|
|
@@ -138252,10 +138559,10 @@ function escapeForMdx(text7) {
|
|
|
138252
138559
|
}
|
|
138253
138560
|
function summarize3(markdown, max = 160) {
|
|
138254
138561
|
const paragraphs = markdown.split(/\n{2,}/).map((block2) => block2.trim()).filter((block2) => block2 && !/^(#|!\[|<|```|>|\||-\s|\d+\.\s|\*[^*]+\*$|\{\/\*)/.test(block2));
|
|
138255
|
-
const
|
|
138256
|
-
if (!
|
|
138562
|
+
const first3 = paragraphs[0];
|
|
138563
|
+
if (!first3) return "";
|
|
138257
138564
|
const plain3 = collapse2(
|
|
138258
|
-
|
|
138565
|
+
first3.replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`~]|\\(?=.)/g, "")
|
|
138259
138566
|
);
|
|
138260
138567
|
if (plain3.length <= max) return plain3;
|
|
138261
138568
|
const sentences = plain3.split(/(?<=[.!?…][”’"')]?)\s+(?=[\p{Lu}\p{N}“‘"'(])/u);
|
|
@@ -139777,9 +140084,9 @@ function answerFlag(id5, value) {
|
|
|
139777
140084
|
if (id5.startsWith("default:")) return `--default ${id5.slice("default:".length)}=${value}`;
|
|
139778
140085
|
return `--type ${id5.slice("type:".length)}:${value}`;
|
|
139779
140086
|
}
|
|
139780
|
-
function renderReport(
|
|
140087
|
+
function renderReport(report3) {
|
|
139781
140088
|
const out = [];
|
|
139782
|
-
const { posts, pages, media } =
|
|
140089
|
+
const { posts, pages, media } = report3.counts;
|
|
139783
140090
|
const line = (text7 = "") => out.push(text7);
|
|
139784
140091
|
const section = (title) => {
|
|
139785
140092
|
line();
|
|
@@ -139787,20 +140094,20 @@ function renderReport(report2) {
|
|
|
139787
140094
|
};
|
|
139788
140095
|
const summary3 = (label, tally) => {
|
|
139789
140096
|
const parts = [
|
|
139790
|
-
tally.created ? `${tally.created} ${
|
|
139791
|
-
tally.updated ? `${tally.updated} ${
|
|
140097
|
+
tally.created ? `${tally.created} ${report3.dryRun ? "to add" : "added"}` : "",
|
|
140098
|
+
tally.updated ? `${tally.updated} ${report3.dryRun ? "to update" : "updated"}` : "",
|
|
139792
140099
|
tally.unchanged ? `${tally.unchanged} unchanged` : "",
|
|
139793
140100
|
tally.skipped ? `${tally.skipped} not imported` : ""
|
|
139794
140101
|
].filter(Boolean);
|
|
139795
140102
|
return ` ${label}: ${parts.length ? parts.join(", ") : "none"}`;
|
|
139796
140103
|
};
|
|
139797
|
-
line(`${
|
|
140104
|
+
line(`${report3.dryRun ? "Import plan (nothing was written)" : report3.stopped ? "Import stopped part-way \u2014 what arrived is kept" : "Import finished"} \u2014 ${report3.source.title || report3.source.siteUrl} \u2192 ${report3.siteName}`);
|
|
139798
140105
|
section("What came across");
|
|
139799
140106
|
line(summary3("Posts", posts));
|
|
139800
140107
|
line(summary3("Pages", pages));
|
|
139801
|
-
line(` Images and files: ${
|
|
139802
|
-
if (
|
|
139803
|
-
const seo =
|
|
140108
|
+
line(` Images and files: ${report3.dryRun ? `${media.planned} to download` : `${media.saved} saved${media.reused ? `, ${media.reused} already here` : ""}${media.failed ? `, ${media.failed} couldn't be downloaded` : ""}${media.skipped ? `, ${media.skipped} skipped` : ""}`}`);
|
|
140109
|
+
if (report3.counts.embeds) line(` Videos, maps and other embeds kept: ${report3.counts.embeds}`);
|
|
140110
|
+
const seo = report3.seo;
|
|
139804
140111
|
if (seo.titlesKept || seo.titlesNotKept || seo.descriptions || seo.canonicals) {
|
|
139805
140112
|
line(
|
|
139806
140113
|
` SEO: ${[
|
|
@@ -139811,7 +140118,7 @@ function renderReport(report2) {
|
|
|
139811
140118
|
].filter(Boolean).join("; ")}`
|
|
139812
140119
|
);
|
|
139813
140120
|
}
|
|
139814
|
-
const attention =
|
|
140121
|
+
const attention = report3.needsAttention;
|
|
139815
140122
|
if (attention.questions.length) {
|
|
139816
140123
|
section("Questions to answer first");
|
|
139817
140124
|
for (const question2 of attention.questions) {
|
|
@@ -139822,8 +140129,8 @@ function renderReport(report2) {
|
|
|
139822
140129
|
const hasAttention = attention.shortcodes.length || attention.rebuilds || attention.media.length || attention.links.length || attention.features.length || attention.notes.length;
|
|
139823
140130
|
if (hasAttention) section("What needs a person");
|
|
139824
140131
|
if (attention.rebuilds) {
|
|
139825
|
-
line(` ${count4(attention.rebuilds, "page")} ${attention.rebuilds === 1 ? "was" : "were"} built with a page builder. ${attention.rebuilds === 1 ? "It" : "Each"} ${
|
|
139826
|
-
for (const rebuild of
|
|
140132
|
+
line(` ${count4(attention.rebuilds, "page")} ${attention.rebuilds === 1 ? "was" : "were"} built with a page builder. ${attention.rebuilds === 1 ? "It" : "Each"} ${report3.dryRun ? "would be" : "was"} imported as text, with a brief to rebuild it from this site's sections:`);
|
|
140133
|
+
for (const rebuild of report3.rebuilds) {
|
|
139827
140134
|
const matched = rebuild.suggestions.filter((s) => s.blockType).length;
|
|
139828
140135
|
line(` \xB7 ${rebuild.title}${rebuild.url ? ` (${rebuild.url})` : ""} \u2014 ${count4(rebuild.outline.sections.length, "section")}, ${matched} with a matching section type`);
|
|
139829
140136
|
}
|
|
@@ -139850,26 +140157,26 @@ function renderReport(report2) {
|
|
|
139850
140157
|
for (const note of attention.notes.slice(0, 30)) line(` \xB7 ${note.title}: ${note.note}`);
|
|
139851
140158
|
if (attention.notes.length > 30) line(` \u2026 and ${attention.notes.length - 30} more (see --json)`);
|
|
139852
140159
|
}
|
|
139853
|
-
const skipped =
|
|
140160
|
+
const skipped = report3.items.filter((item) => item.action === "skipped" || item.action === "held-back");
|
|
139854
140161
|
if (skipped.length) {
|
|
139855
140162
|
section("Not imported");
|
|
139856
140163
|
for (const item of skipped.slice(0, 30)) line(` \xB7 ${item.title} \u2014 ${item.reason ?? "skipped"}`);
|
|
139857
140164
|
if (skipped.length > 30) line(` \u2026 and ${skipped.length - 30} more (see --json)`);
|
|
139858
140165
|
}
|
|
139859
140166
|
section("Left behind on purpose");
|
|
139860
|
-
for (const entry of
|
|
139861
|
-
if (
|
|
139862
|
-
section(`Redirects (${
|
|
139863
|
-
for (const redirect3 of
|
|
139864
|
-
if (
|
|
139865
|
-
line(
|
|
139866
|
-
}
|
|
139867
|
-
if (
|
|
140167
|
+
for (const entry of report3.notImported) line(` \xB7 ${entry.what}: ${entry.why}`);
|
|
140168
|
+
if (report3.redirects.length) {
|
|
140169
|
+
section(`Redirects (${report3.redirects.length}) \u2014 old addresses that change`);
|
|
140170
|
+
for (const redirect3 of report3.redirects.slice(0, 15)) line(` ${redirect3.from} \u2192 ${redirect3.to}`);
|
|
140171
|
+
if (report3.redirects.length > 15) line(` \u2026 and ${report3.redirects.length - 15} more`);
|
|
140172
|
+
line(report3.files.some((file2) => /redirects/.test(file2)) ? ` Written to: ${report3.files.filter((file2) => /redirects/.test(file2)).join(", ")}` : " Add --write-redirects to write them as files, or copy them from --json.");
|
|
140173
|
+
}
|
|
140174
|
+
if (report3.files.length) {
|
|
139868
140175
|
section("Files written besides content");
|
|
139869
|
-
for (const file2 of
|
|
140176
|
+
for (const file2 of report3.files) line(` \xB7 ${file2}`);
|
|
139870
140177
|
}
|
|
139871
140178
|
section("What to do next");
|
|
139872
|
-
|
|
140179
|
+
report3.nextSteps.forEach((step, i) => line(` ${i + 1}. ${step}`));
|
|
139873
140180
|
return out.join("\n");
|
|
139874
140181
|
}
|
|
139875
140182
|
var init_report = __esm({
|
|
@@ -140409,7 +140716,7 @@ Options
|
|
|
140409
140716
|
context: await planContext(site, model)
|
|
140410
140717
|
});
|
|
140411
140718
|
for (const note of wp.notes) io.err(`! ${note}`);
|
|
140412
|
-
const
|
|
140719
|
+
const report3 = await runImport(site, wp, plan2, {
|
|
140413
140720
|
dryRun: dryRun || plan2.questions.length > 0,
|
|
140414
140721
|
onProgress,
|
|
140415
140722
|
...values["write-redirects"] ? { writeRedirects: true } : {},
|
|
@@ -140417,7 +140724,7 @@ Options
|
|
|
140417
140724
|
...values["max-total-mb"] ? { maxTotalBytes: positiveNumber("max-total-mb", values["max-total-mb"]) * 1024 * 1024 } : {},
|
|
140418
140725
|
...io.fetch ? { fetch: io.fetch } : {}
|
|
140419
140726
|
});
|
|
140420
|
-
io.out(values.json ? JSON.stringify(
|
|
140727
|
+
io.out(values.json ? JSON.stringify(report3, null, 2) : renderReport(report3));
|
|
140421
140728
|
if (plan2.questions.length) return 1;
|
|
140422
140729
|
const cache2 = cacheDirFor(source2);
|
|
140423
140730
|
if (cache2 && !dryRun) rmSync2(cache2, { recursive: true, force: true });
|
|
@@ -140518,13 +140825,13 @@ function headerRecord(init) {
|
|
|
140518
140825
|
return out;
|
|
140519
140826
|
}
|
|
140520
140827
|
function send3(url2, headers2, pinned, signal) {
|
|
140521
|
-
return new Promise((
|
|
140828
|
+
return new Promise((resolve25, reject) => {
|
|
140522
140829
|
const lookup = (_host, options2, callback2) => {
|
|
140523
140830
|
const done = callback2;
|
|
140524
140831
|
if (options2?.all) done(null, [{ address: pinned.address, family: pinned.family }]);
|
|
140525
140832
|
else done(null, pinned.address, pinned.family);
|
|
140526
140833
|
};
|
|
140527
|
-
const request = (url2.protocol === "https:" ? httpsRequest2 : httpRequest2)(url2, { method: "GET", headers: headers2, lookup },
|
|
140834
|
+
const request = (url2.protocol === "https:" ? httpsRequest2 : httpRequest2)(url2, { method: "GET", headers: headers2, lookup }, resolve25);
|
|
140528
140835
|
const abort = () => request.destroy(signal?.reason instanceof Error ? signal.reason : new Error("The request was stopped."));
|
|
140529
140836
|
request.on("error", reject);
|
|
140530
140837
|
if (signal?.aborted) abort();
|
|
@@ -140534,14 +140841,14 @@ function send3(url2, headers2, pinned, signal) {
|
|
|
140534
140841
|
});
|
|
140535
140842
|
}
|
|
140536
140843
|
function createGuardedFetch2(options2) {
|
|
140537
|
-
const
|
|
140844
|
+
const resolve25 = options2.resolve ?? systemResolver;
|
|
140538
140845
|
const guard = { allowHttp: true, allowPrivate: options2.allowPrivate };
|
|
140539
140846
|
const guarded2 = async (input2, init) => {
|
|
140540
140847
|
let url2 = new URL(typeof input2 === "string" ? input2 : input2 instanceof URL ? input2.href : input2.url);
|
|
140541
140848
|
const headers2 = headerRecord(init);
|
|
140542
140849
|
const signal = init?.signal ?? void 0;
|
|
140543
140850
|
for (let hop = 0; ; hop += 1) {
|
|
140544
|
-
const checked = await checkTarget(url2, guard,
|
|
140851
|
+
const checked = await checkTarget(url2, guard, resolve25);
|
|
140545
140852
|
const pinned = checked && options2.connectTo ? options2.connectTo(checked) : checked;
|
|
140546
140853
|
if (!pinned) throw new Error(`${url2.host} couldn't be found.`);
|
|
140547
140854
|
const response = await send3(url2, headers2, pinned, signal);
|
|
@@ -140888,12 +141195,12 @@ function jobEmitter(events, job) {
|
|
|
140888
141195
|
function stepText(step) {
|
|
140889
141196
|
return step.total ? `${step.label} \u2014 ${step.done ?? 0} of ${step.total}` : step.label;
|
|
140890
141197
|
}
|
|
140891
|
-
function reportView(runId, plan2,
|
|
141198
|
+
function reportView(runId, plan2, report3, kind) {
|
|
140892
141199
|
const pathOf = /* @__PURE__ */ new Map();
|
|
140893
|
-
for (const item of
|
|
141200
|
+
for (const item of report3.items) if (item.path && !pathOf.has(item.title)) pathOf.set(item.title, item.path);
|
|
140894
141201
|
const at = (title, note) => ({ title, ...pathOf.get(title) ? { path: pathOf.get(title) } : {}, note });
|
|
140895
141202
|
const needsLook = [];
|
|
140896
|
-
const attention =
|
|
141203
|
+
const attention = report3.needsAttention;
|
|
140897
141204
|
for (const feature of attention.features) needsLook.push({ id: `feature:${feature.feature}`, title: feature.title, advice: feature.advice, items: feature.where.map((where5) => at(where5.replace(/ \(\/.*\)$/, ""), where5)) });
|
|
140898
141205
|
if (attention.shortcodes.length) {
|
|
140899
141206
|
needsLook.push({
|
|
@@ -140915,29 +141222,29 @@ function reportView(runId, plan2, report2, kind) {
|
|
|
140915
141222
|
grouped.set(key, [...grouped.get(key) ?? [], at(note.title, note.note)]);
|
|
140916
141223
|
}
|
|
140917
141224
|
for (const [key, items] of [...grouped.entries()].sort((a, b) => b[1].length - a[1].length)) {
|
|
140918
|
-
const
|
|
140919
|
-
needsLook.push({ id: `note:${createHash14("sha1").update(key).digest("hex").slice(0, 10)}`, title:
|
|
141225
|
+
const first3 = items[0].note;
|
|
141226
|
+
needsLook.push({ id: `note:${createHash14("sha1").update(key).digest("hex").slice(0, 10)}`, title: first3.replace(/ — check.*$/, "").replace(/\.$/, ""), items });
|
|
140920
141227
|
}
|
|
140921
141228
|
const oldUrl = new Map(plan2.items.map((item) => [item.path, item.oldUrl]));
|
|
140922
|
-
const counted2 = (action) =>
|
|
141229
|
+
const counted2 = (action) => report3.items.filter((item) => item.action === action);
|
|
140923
141230
|
return {
|
|
140924
141231
|
runId,
|
|
140925
141232
|
finishedAt: Date.now(),
|
|
140926
|
-
stopped: Boolean(
|
|
140927
|
-
source: { title:
|
|
141233
|
+
stopped: Boolean(report3.stopped),
|
|
141234
|
+
source: { title: report3.source.title, siteUrl: report3.source.siteUrl, kind },
|
|
140928
141235
|
arrived: {
|
|
140929
|
-
posts:
|
|
140930
|
-
pages:
|
|
140931
|
-
images:
|
|
140932
|
-
updated:
|
|
140933
|
-
unchanged:
|
|
140934
|
-
embeds:
|
|
141236
|
+
posts: report3.counts.posts.created,
|
|
141237
|
+
pages: report3.counts.pages.created,
|
|
141238
|
+
images: report3.counts.media.saved,
|
|
141239
|
+
updated: report3.counts.posts.updated + report3.counts.pages.updated,
|
|
141240
|
+
unchanged: report3.counts.posts.unchanged + report3.counts.pages.unchanged,
|
|
141241
|
+
embeds: report3.counts.embeds
|
|
140935
141242
|
},
|
|
140936
141243
|
entries: [...counted2("created"), ...counted2("updated"), ...counted2("unchanged")].filter((item) => item.path).map((item) => ({ title: item.title, kind: item.kind === "page" ? "page" : "post", path: item.path, newUrl: item.newUrl, oldUrl: item.oldUrl, action: item.action })),
|
|
140937
141244
|
needsLook,
|
|
140938
|
-
notImported:
|
|
140939
|
-
leftBehind:
|
|
140940
|
-
rebuilds:
|
|
141245
|
+
notImported: report3.items.filter((item) => item.action === "skipped" || item.action === "held-back").map((item) => ({ title: item.title, ...item.path ? { path: item.path } : {}, note: item.reason ?? "It wasn't brought over." })),
|
|
141246
|
+
leftBehind: report3.notImported,
|
|
141247
|
+
rebuilds: report3.rebuilds.map((rebuild) => ({
|
|
140941
141248
|
title: rebuild.title,
|
|
140942
141249
|
path: rebuild.path,
|
|
140943
141250
|
url: rebuild.url,
|
|
@@ -140946,9 +141253,9 @@ function reportView(runId, plan2, report2, kind) {
|
|
|
140946
141253
|
sections: rebuild.outline.sections.length,
|
|
140947
141254
|
matched: rebuild.suggestions.filter((suggestion) => suggestion.blockType).length
|
|
140948
141255
|
})),
|
|
140949
|
-
redirects: { count:
|
|
140950
|
-
seo:
|
|
140951
|
-
files:
|
|
141256
|
+
redirects: { count: report3.redirects.length, file: report3.files.find((file2) => file2.endsWith("_redirects")) ?? null, list: report3.redirects },
|
|
141257
|
+
seo: report3.seo,
|
|
141258
|
+
files: report3.files
|
|
140952
141259
|
};
|
|
140953
141260
|
}
|
|
140954
141261
|
async function saveReport(service, siteId4, stored) {
|
|
@@ -141002,7 +141309,7 @@ function startRun(ctx, site, source2, given) {
|
|
|
141002
141309
|
step("read", { state: "done" });
|
|
141003
141310
|
secret = void 0;
|
|
141004
141311
|
held = null;
|
|
141005
|
-
const
|
|
141312
|
+
const report3 = await runImport(site, read.wp, plan2, {
|
|
141006
141313
|
signal: run4.controller.signal,
|
|
141007
141314
|
writeRedirects: true,
|
|
141008
141315
|
redirectFiles: "import-folder",
|
|
@@ -141012,17 +141319,17 @@ function startRun(ctx, site, source2, given) {
|
|
|
141012
141319
|
else if (event.phase === "entries") step(event.kind === "pages" ? "pages" : "posts", { state: "running", done: event.done, total: event.total });
|
|
141013
141320
|
}
|
|
141014
141321
|
});
|
|
141015
|
-
for (const entry of steps) if (entry.state === "waiting" && entry.id !== "finish" && !
|
|
141016
|
-
for (const entry of steps) if (entry.state === "running") entry.state =
|
|
141322
|
+
for (const entry of steps) if (entry.state === "waiting" && entry.id !== "finish" && !report3.stopped) entry.state = "skipped";
|
|
141323
|
+
for (const entry of steps) if (entry.state === "running") entry.state = report3.stopped ? "stopped" : "done";
|
|
141017
141324
|
step("finish", { state: "running" });
|
|
141018
|
-
const view = reportView(id5, plan2,
|
|
141019
|
-
await saveReport(service, site.id, { view, briefs:
|
|
141325
|
+
const view = reportView(id5, plan2, report3, source2.kind);
|
|
141326
|
+
await saveReport(service, site.id, { view, briefs: report3.rebuilds });
|
|
141020
141327
|
step("finish", { state: "done" });
|
|
141021
141328
|
status2.report = view;
|
|
141022
|
-
status2.state =
|
|
141329
|
+
status2.state = report3.stopped ? "stopped" : "done";
|
|
141023
141330
|
const kept = view.arrived.posts + view.arrived.pages + view.arrived.updated;
|
|
141024
|
-
status2.message =
|
|
141025
|
-
emitter.finish("done", { label:
|
|
141331
|
+
status2.message = report3.stopped ? `Stopped. ${kept} ${kept === 1 ? "entry" : "entries"} and ${view.arrived.images} ${view.arrived.images === 1 ? "image" : "images"} had arrived; they're kept as pending changes. Start again to bring the rest \u2014 nothing is duplicated.` : `Done. ${view.arrived.posts} ${view.arrived.posts === 1 ? "post" : "posts"}, ${view.arrived.pages} ${view.arrived.pages === 1 ? "page" : "pages"} and ${view.arrived.images} ${view.arrived.images === 1 ? "image" : "images"} are waiting in Proof.`;
|
|
141332
|
+
emitter.finish("done", { label: report3.stopped ? "Import stopped \u2014 what arrived is kept" : "WordPress import finished", detail: status2.message, progress: 1 });
|
|
141026
141333
|
} catch (error63) {
|
|
141027
141334
|
const clean4 = scrub2(error63, secret);
|
|
141028
141335
|
const aborted3 = clean4 instanceof ImportError && clean4.reason === "aborted";
|
|
@@ -141110,11 +141417,11 @@ function startRebuildAll(ctx, site, stored, paths2) {
|
|
|
141110
141417
|
try {
|
|
141111
141418
|
let threadId = "";
|
|
141112
141419
|
let expected = "";
|
|
141113
|
-
const ended = new Promise((
|
|
141420
|
+
const ended = new Promise((resolve25) => {
|
|
141114
141421
|
const off2 = ctx.services.events.subscribe((event) => {
|
|
141115
141422
|
if ((event.type === "chat.done" || event.type === "chat.error") && event.siteId === site.id && event.threadId === threadId && (!expected || event.turnId === expected)) {
|
|
141116
141423
|
off2();
|
|
141117
|
-
|
|
141424
|
+
resolve25(event.type === "chat.error" ? event.message : null);
|
|
141118
141425
|
}
|
|
141119
141426
|
});
|
|
141120
141427
|
});
|
|
@@ -141688,7 +141995,7 @@ async function waitFor(api, account, operation, onProgress) {
|
|
|
141688
141995
|
if (status2 === "failed") throw new GalleyError("invalid", `Cloudflare couldn't take the redirect list${response.body?.result?.error ? `: \u201C${scrub(response.body.result.error, [api.token]).slice(0, 300)}\u201D` : ""}. The rule wasn't changed.`, `bulk operation ${operation} failed`);
|
|
141689
141996
|
if (Date.now() - started > timeout) throw new GalleyError("busy", "Cloudflare is still working on the list. Check again in a few minutes.", `bulk operation ${operation} still ${status2 ?? "unknown"}`);
|
|
141690
141997
|
onProgress({ detail: status2 === "running" ? "Cloudflare is updating the list\u2026" : "Waiting for Cloudflare to start on the list\u2026" });
|
|
141691
|
-
await new Promise((
|
|
141998
|
+
await new Promise((resolve25) => setTimeout(resolve25, Math.min(pollMs * (attempt < 5 ? 1 : 2), 1e4)));
|
|
141692
141999
|
}
|
|
141693
142000
|
}
|
|
141694
142001
|
async function applyCloudflare(api, target, list3, planId, onProgress) {
|
|
@@ -141790,7 +142097,7 @@ function missingPermissionError(missing) {
|
|
|
141790
142097
|
`missing: ${missing.join(", ")}`
|
|
141791
142098
|
);
|
|
141792
142099
|
}
|
|
141793
|
-
function
|
|
142100
|
+
function hostnameProblem2(hostname3) {
|
|
141794
142101
|
const host3 = hostname3.trim().toLowerCase();
|
|
141795
142102
|
if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host3)) return `\u201C${hostname3}\u201D isn't a domain name, like www.example.com.`;
|
|
141796
142103
|
if (/\.(workers|pages)\.dev$/.test(host3)) return `${host3} is an address Cloudflare provides, not a domain of your own, so Bulk Redirects can't apply there. Add the site's own domain first.`;
|
|
@@ -142135,9 +142442,9 @@ function parseJson4(text7, ctx) {
|
|
|
142135
142442
|
const record3 = value;
|
|
142136
142443
|
const list3 = Array.isArray(value) ? value : Array.isArray(record3?.redirects) ? record3.redirects : null;
|
|
142137
142444
|
if (!list3) return null;
|
|
142138
|
-
const
|
|
142139
|
-
const vercel2 = "source" in
|
|
142140
|
-
const wordpress = !vercel2 && "title" in
|
|
142445
|
+
const first3 = list3.find((item) => item && typeof item === "object") ?? {};
|
|
142446
|
+
const vercel2 = "source" in first3 && "destination" in first3;
|
|
142447
|
+
const wordpress = !vercel2 && "title" in first3 && ("snippets" in record3 || "plan" in record3 || "items" in record3 || "nextSteps" in record3);
|
|
142141
142448
|
const format2 = vercel2 ? "vercel-json" : wordpress ? "wordpress" : "json";
|
|
142142
142449
|
const lines = text7.split("\n");
|
|
142143
142450
|
const lineOf = (index, from) => {
|
|
@@ -142358,14 +142665,14 @@ function reviewImport(existing, parsed, options2) {
|
|
|
142358
142665
|
const duplicates2 = [];
|
|
142359
142666
|
const conflicts = [];
|
|
142360
142667
|
for (const redirect3 of incoming) {
|
|
142361
|
-
const
|
|
142362
|
-
if (!
|
|
142668
|
+
const first3 = firstByFrom.get(redirect3.from);
|
|
142669
|
+
if (!first3) {
|
|
142363
142670
|
firstByFrom.set(redirect3.from, redirect3);
|
|
142364
142671
|
continue;
|
|
142365
142672
|
}
|
|
142366
|
-
if (same(
|
|
142673
|
+
if (same(first3, redirect3)) duplicates2.push(redirect3);
|
|
142367
142674
|
else {
|
|
142368
|
-
conflicts.push({ kept:
|
|
142675
|
+
conflicts.push({ kept: first3, other: redirect3 });
|
|
142369
142676
|
if (resolutions2.conflicts === "keep-last") firstByFrom.set(redirect3.from, redirect3);
|
|
142370
142677
|
}
|
|
142371
142678
|
}
|
|
@@ -142774,7 +143081,7 @@ function createRedirectsService(options2) {
|
|
|
142774
143081
|
function cloudflareHostnames(model) {
|
|
142775
143082
|
if (model.redirects?.cloudflare?.hostnames?.length) return model.redirects.cloudflare.hostnames;
|
|
142776
143083
|
const production = model.urls.production ? hostOf3(model.urls.production) : null;
|
|
142777
|
-
return production && !
|
|
143084
|
+
return production && !hostnameProblem2(production) ? [production] : [];
|
|
142778
143085
|
}
|
|
142779
143086
|
async function cloudflareContext(site) {
|
|
142780
143087
|
const model = await site.model();
|
|
@@ -142785,7 +143092,7 @@ function createRedirectsService(options2) {
|
|
|
142785
143092
|
const hostnames = cloudflareHostnames(model);
|
|
142786
143093
|
if (hostnames.length === 0) throw new GalleyError("unconfigured", "Add the site's own domain first (like www.example.com). Bulk Redirects apply on a domain in your Cloudflare account, not on a workers.dev address.");
|
|
142787
143094
|
for (const hostname3 of hostnames) {
|
|
142788
|
-
const problem =
|
|
143095
|
+
const problem = hostnameProblem2(hostname3);
|
|
142789
143096
|
if (problem) throw new GalleyError("invalid", problem);
|
|
142790
143097
|
}
|
|
142791
143098
|
const loaded = await loadList(site, model);
|
|
@@ -142955,7 +143262,7 @@ function createRedirectsService(options2) {
|
|
|
142955
143262
|
if (patch.cloudflare.hostnames !== void 0) {
|
|
142956
143263
|
const hostnames = [...new Set((patch.cloudflare.hostnames ?? []).map((host3) => host3.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "")).filter(Boolean))];
|
|
142957
143264
|
for (const hostname3 of hostnames) {
|
|
142958
|
-
const problem =
|
|
143265
|
+
const problem = hostnameProblem2(hostname3);
|
|
142959
143266
|
if (problem) throw new GalleyError("invalid", problem);
|
|
142960
143267
|
}
|
|
142961
143268
|
if (hostnames.length) cloudflare.hostnames = hostnames;
|
|
@@ -144486,8 +144793,8 @@ async function readInventory(site, model, files) {
|
|
|
144486
144793
|
const list3 = await site.listEntries(collection.id, { limit: 200 }).catch(() => null);
|
|
144487
144794
|
if (!list3) continue;
|
|
144488
144795
|
const items = [...list3.items].sort((a, b) => a.url === "/" ? -1 : b.url === "/" ? 1 : (a.url ?? "").localeCompare(b.url ?? ""));
|
|
144489
|
-
const
|
|
144490
|
-
if (
|
|
144796
|
+
const first3 = items.find((item) => item.url && !item.draft);
|
|
144797
|
+
if (first3?.url && !representative.includes(first3.url)) representative.push(first3.url);
|
|
144491
144798
|
for (const item of items) {
|
|
144492
144799
|
if (item.url && !item.draft) pages.push(item.url);
|
|
144493
144800
|
if (item.title && item.titleSource === "field") copy.push({ text: item.title, where: item.url ?? item.path });
|
|
@@ -146097,8 +146404,8 @@ var init_client3 = __esm({
|
|
|
146097
146404
|
kind;
|
|
146098
146405
|
detail;
|
|
146099
146406
|
};
|
|
146100
|
-
sleep3 = (ms, signal) => new Promise((
|
|
146101
|
-
const timer = setTimeout(
|
|
146407
|
+
sleep3 = (ms, signal) => new Promise((resolve25, reject) => {
|
|
146408
|
+
const timer = setTimeout(resolve25, ms);
|
|
146102
146409
|
signal?.addEventListener(
|
|
146103
146410
|
"abort",
|
|
146104
146411
|
() => {
|
|
@@ -146140,10 +146447,10 @@ async function shopInfo(ctx, connection, signal) {
|
|
|
146140
146447
|
return { ...result.data.shop, answeredVersion: result.version };
|
|
146141
146448
|
}
|
|
146142
146449
|
async function searchProducts(ctx, connection, words3, limit2, signal) {
|
|
146143
|
-
const
|
|
146450
|
+
const first3 = Math.max(1, Math.min(limit2, 50));
|
|
146144
146451
|
const text7 = words3.trim();
|
|
146145
146452
|
if (!text7) {
|
|
146146
|
-
const result2 = await graphql(ctx, connection, "storefront", `query Products($first: Int!) { products(first: $first) { nodes { ${SUMMARY_FIELDS} } } }`, { first:
|
|
146453
|
+
const result2 = await graphql(ctx, connection, "storefront", `query Products($first: Int!) { products(first: $first) { nodes { ${SUMMARY_FIELDS} } } }`, { first: first3 }, signal ? { signal } : {});
|
|
146147
146454
|
return result2.data.products.nodes.map(summary);
|
|
146148
146455
|
}
|
|
146149
146456
|
const result = await graphql(
|
|
@@ -146151,7 +146458,7 @@ async function searchProducts(ctx, connection, words3, limit2, signal) {
|
|
|
146151
146458
|
connection,
|
|
146152
146459
|
"storefront",
|
|
146153
146460
|
`query Search($query: String!, $first: Int!) { search(query: $query, first: $first, types: [PRODUCT]) { nodes { __typename ... on Product { ${SUMMARY_FIELDS} } } } }`,
|
|
146154
|
-
{ query: text7, first:
|
|
146461
|
+
{ query: text7, first: first3 },
|
|
146155
146462
|
signal ? { signal } : {}
|
|
146156
146463
|
);
|
|
146157
146464
|
return result.data.search.nodes.filter((node2) => node2.__typename === "Product").map(summary);
|
|
@@ -149175,11 +149482,11 @@ var LoginLimiter = class {
|
|
|
149175
149482
|
}
|
|
149176
149483
|
};
|
|
149177
149484
|
var LOOPBACK_NAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
|
|
149178
|
-
function
|
|
149485
|
+
function normalizeHostname2(hostname3) {
|
|
149179
149486
|
return hostname3.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
149180
149487
|
}
|
|
149181
149488
|
function isLoopbackHost(host3) {
|
|
149182
|
-
const name3 =
|
|
149489
|
+
const name3 = normalizeHostname2(host3);
|
|
149183
149490
|
return LOOPBACK_NAMES.has(name3) || /^127(\.\d{1,3}){3}$/.test(name3);
|
|
149184
149491
|
}
|
|
149185
149492
|
function loopbackHostnames() {
|
|
@@ -149526,9 +149833,9 @@ var util4;
|
|
|
149526
149833
|
})(util4 || (util4 = {}));
|
|
149527
149834
|
var objectUtil;
|
|
149528
149835
|
(function(objectUtil2) {
|
|
149529
|
-
objectUtil2.mergeShapes = (
|
|
149836
|
+
objectUtil2.mergeShapes = (first3, second) => {
|
|
149530
149837
|
return {
|
|
149531
|
-
...
|
|
149838
|
+
...first3,
|
|
149532
149839
|
...second
|
|
149533
149840
|
// second overwrites first
|
|
149534
149841
|
};
|
|
@@ -152461,10 +152768,10 @@ var ZodRecord2 = class _ZodRecord extends ZodType2 {
|
|
|
152461
152768
|
get element() {
|
|
152462
152769
|
return this._def.valueType;
|
|
152463
152770
|
}
|
|
152464
|
-
static create(
|
|
152771
|
+
static create(first3, second, third) {
|
|
152465
152772
|
if (second instanceof ZodType2) {
|
|
152466
152773
|
return new _ZodRecord({
|
|
152467
|
-
keyType:
|
|
152774
|
+
keyType: first3,
|
|
152468
152775
|
valueType: second,
|
|
152469
152776
|
typeName: ZodFirstPartyTypeKind2.ZodRecord,
|
|
152470
152777
|
...processCreateParams(third)
|
|
@@ -152472,7 +152779,7 @@ var ZodRecord2 = class _ZodRecord extends ZodType2 {
|
|
|
152472
152779
|
}
|
|
152473
152780
|
return new _ZodRecord({
|
|
152474
152781
|
keyType: ZodString2.create(),
|
|
152475
|
-
valueType:
|
|
152782
|
+
valueType: first3,
|
|
152476
152783
|
typeName: ZodFirstPartyTypeKind2.ZodRecord,
|
|
152477
152784
|
...processCreateParams(second)
|
|
152478
152785
|
});
|
|
@@ -156984,7 +157291,7 @@ var Protocol = class {
|
|
|
156984
157291
|
return;
|
|
156985
157292
|
}
|
|
156986
157293
|
const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
|
|
156987
|
-
await new Promise((
|
|
157294
|
+
await new Promise((resolve25) => setTimeout(resolve25, pollInterval));
|
|
156988
157295
|
options2?.signal?.throwIfAborted();
|
|
156989
157296
|
}
|
|
156990
157297
|
} catch (error63) {
|
|
@@ -157001,7 +157308,7 @@ var Protocol = class {
|
|
|
157001
157308
|
*/
|
|
157002
157309
|
request(request, resultSchema, options2) {
|
|
157003
157310
|
const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options2 ?? {};
|
|
157004
|
-
return new Promise((
|
|
157311
|
+
return new Promise((resolve25, reject) => {
|
|
157005
157312
|
const earlyReject = (error63) => {
|
|
157006
157313
|
reject(error63);
|
|
157007
157314
|
};
|
|
@@ -157079,7 +157386,7 @@ var Protocol = class {
|
|
|
157079
157386
|
if (!parseResult.success) {
|
|
157080
157387
|
reject(parseResult.error);
|
|
157081
157388
|
} else {
|
|
157082
|
-
|
|
157389
|
+
resolve25(parseResult.data);
|
|
157083
157390
|
}
|
|
157084
157391
|
} catch (error63) {
|
|
157085
157392
|
reject(error63);
|
|
@@ -157341,12 +157648,12 @@ var Protocol = class {
|
|
|
157341
157648
|
}
|
|
157342
157649
|
} catch {
|
|
157343
157650
|
}
|
|
157344
|
-
return new Promise((
|
|
157651
|
+
return new Promise((resolve25, reject) => {
|
|
157345
157652
|
if (signal.aborted) {
|
|
157346
157653
|
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
157347
157654
|
return;
|
|
157348
157655
|
}
|
|
157349
|
-
const timeoutId = setTimeout(
|
|
157656
|
+
const timeoutId = setTimeout(resolve25, interval);
|
|
157350
157657
|
signal.addEventListener("abort", () => {
|
|
157351
157658
|
clearTimeout(timeoutId);
|
|
157352
157659
|
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
@@ -158709,7 +159016,7 @@ var McpServer = class {
|
|
|
158709
159016
|
let task = createTaskResult.task;
|
|
158710
159017
|
const pollInterval = task.pollInterval ?? 5e3;
|
|
158711
159018
|
while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
|
|
158712
|
-
await new Promise((
|
|
159019
|
+
await new Promise((resolve25) => setTimeout(resolve25, pollInterval));
|
|
158713
159020
|
const updatedTask = await extra2.taskStore.getTask(taskId);
|
|
158714
159021
|
if (!updatedTask) {
|
|
158715
159022
|
throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
|
|
@@ -160316,12 +160623,12 @@ var StdioServerTransport = class {
|
|
|
160316
160623
|
this.onclose?.();
|
|
160317
160624
|
}
|
|
160318
160625
|
send(message2) {
|
|
160319
|
-
return new Promise((
|
|
160626
|
+
return new Promise((resolve25) => {
|
|
160320
160627
|
const json10 = serializeMessage(message2);
|
|
160321
160628
|
if (this._stdout.write(json10)) {
|
|
160322
|
-
|
|
160629
|
+
resolve25();
|
|
160323
160630
|
} else {
|
|
160324
|
-
this._stdout.once("drain",
|
|
160631
|
+
this._stdout.once("drain", resolve25);
|
|
160325
160632
|
}
|
|
160326
160633
|
});
|
|
160327
160634
|
}
|
|
@@ -160354,12 +160661,12 @@ async function serveStdio(server, streams = {}) {
|
|
|
160354
160661
|
const stdout = streams.stdout ?? reserveStdout();
|
|
160355
160662
|
const transport = new StdioServerTransport(stdin, stdout);
|
|
160356
160663
|
let resolveClosed;
|
|
160357
|
-
const closed = new Promise((
|
|
160664
|
+
const closed = new Promise((resolve25) => resolveClosed = resolve25);
|
|
160358
160665
|
let closing = null;
|
|
160359
160666
|
const close = () => {
|
|
160360
160667
|
if (closing) return closing;
|
|
160361
160668
|
let finish3;
|
|
160362
|
-
closing = new Promise((
|
|
160669
|
+
closing = new Promise((resolve25) => finish3 = resolve25);
|
|
160363
160670
|
stdin.off("end", close);
|
|
160364
160671
|
stdin.off("close", close);
|
|
160365
160672
|
void server.close().catch(() => void 0).then(() => {
|
|
@@ -160912,9 +161219,9 @@ data:
|
|
|
160912
161219
|
const initRequest = messages.find((m) => isInitializeRequest(m));
|
|
160913
161220
|
const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req2.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
|
|
160914
161221
|
if (this._enableJsonResponse) {
|
|
160915
|
-
return new Promise((
|
|
161222
|
+
return new Promise((resolve25) => {
|
|
160916
161223
|
this._streamMapping.set(streamId, {
|
|
160917
|
-
resolveJson:
|
|
161224
|
+
resolveJson: resolve25,
|
|
160918
161225
|
cleanup: () => {
|
|
160919
161226
|
this._streamMapping.delete(streamId);
|
|
160920
161227
|
}
|
|
@@ -161660,6 +161967,7 @@ var deploySettingsBody = external_exports.object({
|
|
|
161660
161967
|
previewOnShare: external_exports.boolean().optional()
|
|
161661
161968
|
}).strict();
|
|
161662
161969
|
var deployStartBody = external_exports.object({ kind: external_exports.enum(["production", "preview"]), label: external_exports.string().trim().max(200).optional() }).strict();
|
|
161970
|
+
var domainBody = external_exports.object({ hostname: external_exports.string().trim().min(1, "it can't be empty").max(300) }).strict();
|
|
161663
161971
|
var deploymentsQuery = external_exports.object({ limit: external_exports.coerce.number().int().min(1).max(200).optional() });
|
|
161664
161972
|
function deployOf(ctx) {
|
|
161665
161973
|
const deploy = ctx.services.deploy;
|
|
@@ -161708,6 +162016,26 @@ var deployRoutes = {
|
|
|
161708
162016
|
const site = await siteOf(c, ctx);
|
|
161709
162017
|
return host(() => deploy.start(site, { kind, ...label ? { label } : {} }));
|
|
161710
162018
|
},
|
|
162019
|
+
"POST /api/sites/:siteId/deploy/domain/plan": async (c, ctx) => {
|
|
162020
|
+
const deploy = deployOf(ctx);
|
|
162021
|
+
const { hostname: hostname3 } = await body(c, domainBody);
|
|
162022
|
+
const site = await siteOf(c, ctx);
|
|
162023
|
+
return host(() => deploy.planDomain(site, hostname3));
|
|
162024
|
+
},
|
|
162025
|
+
"POST /api/sites/:siteId/deploy/domain": async (c, ctx) => {
|
|
162026
|
+
const deploy = deployOf(ctx);
|
|
162027
|
+
const { hostname: hostname3 } = await body(c, domainBody);
|
|
162028
|
+
const site = await siteOf(c, ctx);
|
|
162029
|
+
return host(() => deploy.attachDomain(site, hostname3));
|
|
162030
|
+
},
|
|
162031
|
+
"POST /api/sites/:siteId/deploy/domain/check": async (c, ctx) => {
|
|
162032
|
+
const deploy = deployOf(ctx);
|
|
162033
|
+
return host(async () => deploy.checkDomain(await siteOf(c, ctx)));
|
|
162034
|
+
},
|
|
162035
|
+
"DELETE /api/sites/:siteId/deploy/domain": async (c, ctx) => {
|
|
162036
|
+
const deploy = deployOf(ctx);
|
|
162037
|
+
return host(async () => deploy.detachDomain(await siteOf(c, ctx)));
|
|
162038
|
+
},
|
|
161711
162039
|
"GET /api/sites/:siteId/deployments": async (c, ctx) => {
|
|
161712
162040
|
const deploy = deployOf(ctx);
|
|
161713
162041
|
const { limit: limit2 } = query(c, deploymentsQuery);
|
|
@@ -161888,7 +162216,7 @@ init_detect();
|
|
|
161888
162216
|
|
|
161889
162217
|
// ../core/src/site-kit/source.ts
|
|
161890
162218
|
function loadKitBundle() {
|
|
161891
|
-
return Promise.resolve({ "version": "0.1.0", "files": { "kit.d.ts": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// Generated by scripts/sync-contract.mjs from packages/core/src/kit.ts \u2014 do not edit by hand.\n/**\n * The site-kit contract: forms and third-party scripts.\n *\n * These are the shapes of files that live in the *site\'s* repository \u2014 a form\n * is one JSON file, the scripts setup is one JSON file \u2014 so that they are\n * edited like any other content (by hand, in the app\'s builders, by the\n * assistant, over MCP), proofed, and published. The site renders them with a\n * small runtime (`@galley/astro` for Astro sites); the app edits them with\n * dedicated screens. Types only \u2014 no runtime code \u2014 so the site runtime, the\n * web UI and the engine can all import this file.\n */\n/** Any value JSON can hold. (Mirrors JsonValue in @galley/core/types.) */\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 forms\n\nexport type FormFieldType =\n | "text"\n | "email"\n | "tel"\n | "url"\n | "number"\n | "textarea"\n | "select"\n | "radio"\n | "checkbox" // one yes/no box\n | "checkboxes" // several choices\n | "date"\n | "hidden"\n | "consent" // a required-or-not agreement with its own text\n | "heading" // layout only: a sub-heading inside the form\n | "paragraph"; // layout only: a line of explanatory text\n\nexport interface FormFieldOption {\n value: string;\n label: string;\n}\n\n/** Where a hidden (or prefilled) field takes its value from on the page. */\nexport interface FormAutofill {\n /**\n * "query": a query-string parameter (`key`); "utm": the UTM parameter `key`,\n * remembered from the visitor\'s first and latest landing; "referrer";\n * "page-url"; "page-title"; "cookie": a first-party cookie (`key`).\n */\n from: "query" | "utm" | "referrer" | "page-url" | "page-title" | "cookie";\n key?: string;\n /** For "utm": which landing to report. Default "last". */\n touch?: "first" | "last";\n}\n\nexport interface FormField {\n /** Stable id within the form (lowercase, hyphens/underscores). */\n id: string;\n type: FormFieldType;\n label?: string;\n /** Name sent to a destination when its mapping has no entry. Default: `id`. */\n name?: string;\n placeholder?: string;\n /** A line of help under the field. */\n help?: string;\n required?: boolean;\n /** select / radio / checkboxes. */\n options?: FormFieldOption[];\n defaultValue?: string;\n /** Two "half" fields sit side by side on wide screens. Default "full". */\n width?: "full" | "half";\n validation?: {\n /** A regular expression the value must match. */\n pattern?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n /** Shown when the value is refused. */\n message?: string;\n /** email: refuse free mailbox providers (gmail.com, outlook.com, \u2026). */\n businessEmailOnly?: boolean;\n };\n /** Show (and submit) this field only when another field has a given value. */\n showWhen?: { field: string; equals?: string; notEquals?: string; in?: string[] };\n autofill?: FormAutofill;\n /** consent / paragraph / heading: the text itself (inline markdown allowed). */\n text?: string;\n /** Which step it belongs to in a multi-step form (0-based). Default 0. */\n step?: number;\n}\n\n/**\n * Where submissions go. Built-in providers:\n * "galley" \u2014 the Galley capture endpoint (the default; settings: { endpoint? })\n * "hubspot" \u2014 HubSpot Forms API (settings: { portalId, formId, region? })\n * "marketo" \u2014 Marketo Forms 2.0 (settings: { munchkinId, formId, host })\n * "salesforce" \u2014 Salesforce Web-to-Lead (settings: { orgId, returnUrl?, mode?: "frame" | "navigate" })\n * "pardot" \u2014 Account Engagement form handler (settings: { handlerUrl, successLocation?, errorLocation?, mode?: "frame" | "navigate" })\n * "webhook" \u2014 any endpoint that accepts a POST (settings: { url, format?: "json" | "form" })\n * "mailto" \u2014 the visitor\'s own mail program (settings: { to, subject? }) \u2014 last resort\n * Plugins may add more.\n */\nexport type FormProviderId =\n | "galley"\n | "hubspot"\n | "marketo"\n | "salesforce"\n | "pardot"\n | "webhook"\n | "mailto"\n | (string & {});\n\nexport interface FormDestination {\n provider: FormProviderId;\n settings: { [key: string]: JsonValue };\n /** Form field id \u2192 the provider\'s field name. Unmapped fields use `name ?? id`. */\n mapping?: { [fieldId: string]: string };\n /** Extra fixed values sent with every submission (campaign ids, lead source). */\n constants?: { [providerField: string]: string };\n /** Send to this destination only when a field has a given value. */\n when?: { field: string; equals: string };\n}\n\n/** What happens after a successful submission. Run in order. */\nexport type FormAction =\n /** Replace the form with a thank-you (inline markdown; `{{field}}` placeholders). */\n | { type: "message"; title?: string; text: string }\n /** Go to another page. `passFields` are appended as query parameters. */\n | { type: "redirect"; url: string; passFields?: string[]; delaySeconds?: number }\n /** Offer (or start) a download. */\n | { type: "download"; url: string; label?: string; auto?: boolean }\n /** Record a conversion: pushed to `dataLayer` / `gtag` / a DOM CustomEvent. */\n | { type: "event"; name: string; target?: "dataLayer" | "gtag" | "dom"; params?: { [key: string]: string } }\n /** An extra POST of the submission, not awaited (a chat alert, a spreadsheet). */\n | { type: "webhook"; url: string }\n /** Custom JavaScript, called with the submitted values. Build mode only. */\n | { type: "script"; code: string };\n\nexport interface FormDefinition {\n /** Shown in the app and to screen readers as the form\'s name. */\n name: string;\n description?: string;\n fields: FormField[];\n submitLabel: string;\n /** Titles for a multi-step form; absent or one entry = a single step. */\n steps?: Array<{ title?: string; nextLabel?: string }>;\n /** Every destination receives the submission; the first decides success. */\n destinations: FormDestination[];\n afterSubmit: FormAction[];\n /** Shown when the submission could not be sent. */\n errorMessage?: string;\n /**\n * Replaces the runtime\'s default wording for this form, by key: "required",\n * "email", "businessEmail", "summary", "sending", "next", "back", "step",\n * "tooFast", "rateLimited", "noScript", "thanksTitle", "thanksText" \u2026 (the\n * site runtime documents the full list and the `{placeholders}` each takes).\n */\n messages?: { [key: string]: string };\n spam?: {\n /** A hidden field bots fill in. Default true. */\n honeypot?: boolean;\n /** Refuse submissions made faster than this after the form appeared. */\n minSeconds?: number;\n /** Cloudflare Turnstile site key, when the destination verifies it. */\n turnstileSiteKey?: string;\n };\n appearance?: {\n layout?: "stacked" | "inline";\n size?: "regular" | "compact";\n /** Where labels sit. */\n labels?: "above" | "floating" | "hidden";\n };\n}\n\n/** One submission as the Galley capture endpoint stores it. */\nexport interface FormSubmission {\n id: string;\n siteId: string;\n /** The form\'s id (its file name without extension). */\n form: string;\n /** ISO 8601. */\n at: string;\n values: { [fieldId: string]: string | string[] };\n /** Page it was sent from, and how the visitor arrived. */\n page?: { url?: string; title?: string; referrer?: string };\n /** Per-destination forwarding results (for forms that also forward). */\n delivery?: Array<{\n provider: string;\n ok: boolean;\n detail?: string;\n /** Index into the form\'s `destinations`; absent for the e-mail notification (`provider: "email"`). */\n destination?: number;\n /** How many tries the last result took. */\n attempts?: number;\n /** ISO 8601 time of the last try. */\n at?: string;\n }>;\n /** Marked by the spam checks; kept but hidden by default. */\n spam?: boolean;\n /** Which spam check marked it: "honeypot", "too-fast", "turnstile". */\n spamReason?: string;\n read?: boolean;\n /** Sent with "Send a test submission" from the app. */\n test?: boolean;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scripts\n\n/** What a visitor must have agreed to before a script may load. */\nexport type ConsentCategory = "necessary" | "analytics" | "marketing" | "preferences";\n\n/**\n * One third-party script. `kind` names a known integration whose snippet the\n * runtime writes correctly from a few settings \u2014 "gtm" ({ containerId }),\n * "ga4" ({ measurementId }), "meta-pixel" ({ pixelId }), "linkedin-insight"\n * ({ partnerId }), "hubspot" ({ portalId }), "marketo-munchkin"\n * ({ munchkinId }), "plausible" ({ domain }), "segment" ({ writeKey }),\n * "hotjar" ({ siteId }), "clarity" ({ projectId }), "intercom" ({ appId }) \u2014\n * or "custom" ({ src?, inline?, attributes? }). Plugins may add kinds.\n */\nexport interface ScriptEntry {\n id: string;\n kind: string;\n /** Shown in the app. Default: the integration\'s name. */\n label?: string;\n enabled: boolean;\n settings: { [key: string]: JsonValue };\n placement?: "head" | "body-start" | "body-end";\n /**\n * "eager": in the page\'s initial HTML. "idle": once the page is idle.\n * "interaction": on the visitor\'s first scroll, tap or key press.\n */\n load?: "eager" | "idle" | "interaction";\n /** Absent = "necessary" for nothing known; integrations declare a default. */\n consent?: ConsentCategory;\n /** Page-path globs. Empty or absent `include` = every page. */\n include?: string[];\n exclude?: string[];\n /** Load in development and in the editor\'s preview too. Default false. */\n inPreview?: boolean;\n /** A note for colleagues: who asked for it and why. */\n note?: string;\n}\n\nexport interface ConsentSettings {\n /**\n * "none": everything enabled loads. "banner": the built-in consent banner\n * asks first. "external": another consent tool decides and signals through\n * `window.galleyConsent.set(...)` or Google Consent Mode.\n */\n mode: "none" | "banner" | "external";\n /** Categories on before the visitor chooses. "necessary" is always on. */\n defaults?: ConsentCategory[];\n banner?: {\n title?: string;\n text?: string;\n acceptLabel?: string;\n rejectLabel?: string;\n settingsLabel?: string;\n /** The button that saves the choices made under "settings". */\n saveLabel?: string;\n policyUrl?: string;\n policyLabel?: string;\n /** Name and one-line description of each category, as the banner lists them. */\n categories?: { [category in ConsentCategory]?: { label?: string; description?: string } };\n };\n /** Send Google Consent Mode v2 signals to gtag/GTM. */\n googleConsentMode?: boolean;\n}\n\nexport interface ScriptsConfig {\n scripts: ScriptEntry[];\n consent?: ConsentSettings;\n}\n\n/** What a known integration needs, for the app\'s "add a script" catalogue. */\nexport interface ScriptIntegrationInfo {\n kind: string;\n name: string;\n description: string;\n category: "tag-manager" | "analytics" | "advertising" | "marketing" | "support" | "other";\n defaultConsent: ConsentCategory;\n defaultPlacement: "head" | "body-start" | "body-end";\n /** The settings it asks for. */\n settings: Array<{ key: string; label: string; placeholder?: string; pattern?: string; help?: string; required?: boolean }>;\n docsUrl?: string;\n}\n\n/** What a form provider needs, for the app\'s destination picker. */\nexport interface FormProviderInfo {\n id: string;\n name: string;\n description: string;\n settings: Array<{ key: string; label: string; placeholder?: string; pattern?: string; help?: string; required?: boolean }>;\n /** Whether its field list can be read from an existing form on the provider\'s side. */\n canImportFields: boolean;\n docsUrl?: string;\n}\n', "catalog-data.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162219
|
+
return Promise.resolve({ "version": "0.1.1", "files": { "kit.d.ts": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// Generated by scripts/sync-contract.mjs from packages/core/src/kit.ts \u2014 do not edit by hand.\n/**\n * The site-kit contract: forms and third-party scripts.\n *\n * These are the shapes of files that live in the *site\'s* repository \u2014 a form\n * is one JSON file, the scripts setup is one JSON file \u2014 so that they are\n * edited like any other content (by hand, in the app\'s builders, by the\n * assistant, over MCP), proofed, and published. The site renders them with a\n * small runtime (`@galley/astro` for Astro sites); the app edits them with\n * dedicated screens. Types only \u2014 no runtime code \u2014 so the site runtime, the\n * web UI and the engine can all import this file.\n */\n/** Any value JSON can hold. (Mirrors JsonValue in @galley/core/types.) */\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 forms\n\nexport type FormFieldType =\n | "text"\n | "email"\n | "tel"\n | "url"\n | "number"\n | "textarea"\n | "select"\n | "radio"\n | "checkbox" // one yes/no box\n | "checkboxes" // several choices\n | "date"\n | "hidden"\n | "consent" // a required-or-not agreement with its own text\n | "heading" // layout only: a sub-heading inside the form\n | "paragraph"; // layout only: a line of explanatory text\n\nexport interface FormFieldOption {\n value: string;\n label: string;\n}\n\n/** Where a hidden (or prefilled) field takes its value from on the page. */\nexport interface FormAutofill {\n /**\n * "query": a query-string parameter (`key`); "utm": the UTM parameter `key`,\n * remembered from the visitor\'s first and latest landing; "referrer";\n * "page-url"; "page-title"; "cookie": a first-party cookie (`key`).\n */\n from: "query" | "utm" | "referrer" | "page-url" | "page-title" | "cookie";\n key?: string;\n /** For "utm": which landing to report. Default "last". */\n touch?: "first" | "last";\n}\n\nexport interface FormField {\n /** Stable id within the form (lowercase, hyphens/underscores). */\n id: string;\n type: FormFieldType;\n label?: string;\n /** Name sent to a destination when its mapping has no entry. Default: `id`. */\n name?: string;\n placeholder?: string;\n /** A line of help under the field. */\n help?: string;\n required?: boolean;\n /** select / radio / checkboxes. */\n options?: FormFieldOption[];\n defaultValue?: string;\n /** Two "half" fields sit side by side on wide screens. Default "full". */\n width?: "full" | "half";\n validation?: {\n /** A regular expression the value must match. */\n pattern?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n /** Shown when the value is refused. */\n message?: string;\n /** email: refuse free mailbox providers (gmail.com, outlook.com, \u2026). */\n businessEmailOnly?: boolean;\n };\n /** Show (and submit) this field only when another field has a given value. */\n showWhen?: { field: string; equals?: string; notEquals?: string; in?: string[] };\n autofill?: FormAutofill;\n /** consent / paragraph / heading: the text itself (inline markdown allowed). */\n text?: string;\n /** Which step it belongs to in a multi-step form (0-based). Default 0. */\n step?: number;\n}\n\n/**\n * Where submissions go. Built-in providers:\n * "galley" \u2014 the Galley capture endpoint (the default; settings: { endpoint? })\n * "hubspot" \u2014 HubSpot Forms API (settings: { portalId, formId, region? })\n * "marketo" \u2014 Marketo Forms 2.0 (settings: { munchkinId, formId, host })\n * "salesforce" \u2014 Salesforce Web-to-Lead (settings: { orgId, returnUrl?, mode?: "frame" | "navigate" })\n * "pardot" \u2014 Account Engagement form handler (settings: { handlerUrl, successLocation?, errorLocation?, mode?: "frame" | "navigate" })\n * "webhook" \u2014 any endpoint that accepts a POST (settings: { url, format?: "json" | "form" })\n * "mailto" \u2014 the visitor\'s own mail program (settings: { to, subject? }) \u2014 last resort\n * Plugins may add more.\n */\nexport type FormProviderId =\n | "galley"\n | "hubspot"\n | "marketo"\n | "salesforce"\n | "pardot"\n | "webhook"\n | "mailto"\n | (string & {});\n\nexport interface FormDestination {\n provider: FormProviderId;\n settings: { [key: string]: JsonValue };\n /** Form field id \u2192 the provider\'s field name. Unmapped fields use `name ?? id`. */\n mapping?: { [fieldId: string]: string };\n /** Extra fixed values sent with every submission (campaign ids, lead source). */\n constants?: { [providerField: string]: string };\n /** Send to this destination only when a field has a given value. */\n when?: { field: string; equals: string };\n}\n\n/** What happens after a successful submission. Run in order. */\nexport type FormAction =\n /** Replace the form with a thank-you (inline markdown; `{{field}}` placeholders). */\n | { type: "message"; title?: string; text: string }\n /** Go to another page. `passFields` are appended as query parameters. */\n | { type: "redirect"; url: string; passFields?: string[]; delaySeconds?: number }\n /** Offer (or start) a download. */\n | { type: "download"; url: string; label?: string; auto?: boolean }\n /** Record a conversion: pushed to `dataLayer` / `gtag` / a DOM CustomEvent. */\n | { type: "event"; name: string; target?: "dataLayer" | "gtag" | "dom"; params?: { [key: string]: string } }\n /** An extra POST of the submission, not awaited (a chat alert, a spreadsheet). */\n | { type: "webhook"; url: string }\n /** Custom JavaScript, called with the submitted values. Build mode only. */\n | { type: "script"; code: string };\n\nexport interface FormDefinition {\n /** Shown in the app and to screen readers as the form\'s name. */\n name: string;\n description?: string;\n fields: FormField[];\n submitLabel: string;\n /** Titles for a multi-step form; absent or one entry = a single step. */\n steps?: Array<{ title?: string; nextLabel?: string }>;\n /** Every destination receives the submission; the first decides success. */\n destinations: FormDestination[];\n afterSubmit: FormAction[];\n /** Shown when the submission could not be sent. */\n errorMessage?: string;\n /**\n * Replaces the runtime\'s default wording for this form, by key: "required",\n * "email", "businessEmail", "summary", "sending", "next", "back", "step",\n * "tooFast", "rateLimited", "noScript", "thanksTitle", "thanksText" \u2026 (the\n * site runtime documents the full list and the `{placeholders}` each takes).\n */\n messages?: { [key: string]: string };\n spam?: {\n /** A hidden field bots fill in. Default true. */\n honeypot?: boolean;\n /** Refuse submissions made faster than this after the form appeared. */\n minSeconds?: number;\n /** Cloudflare Turnstile site key, when the destination verifies it. */\n turnstileSiteKey?: string;\n };\n appearance?: {\n layout?: "stacked" | "inline";\n size?: "regular" | "compact";\n /** Where labels sit. */\n labels?: "above" | "floating" | "hidden";\n };\n}\n\n/** One submission as the Galley capture endpoint stores it. */\nexport interface FormSubmission {\n id: string;\n siteId: string;\n /** The form\'s id (its file name without extension). */\n form: string;\n /** ISO 8601. */\n at: string;\n values: { [fieldId: string]: string | string[] };\n /** Page it was sent from, and how the visitor arrived. */\n page?: { url?: string; title?: string; referrer?: string };\n /** Per-destination forwarding results (for forms that also forward). */\n delivery?: Array<{\n provider: string;\n ok: boolean;\n detail?: string;\n /** Index into the form\'s `destinations`; absent for the e-mail notification (`provider: "email"`). */\n destination?: number;\n /** How many tries the last result took. */\n attempts?: number;\n /** ISO 8601 time of the last try. */\n at?: string;\n }>;\n /** Marked by the spam checks; kept but hidden by default. */\n spam?: boolean;\n /** Which spam check marked it: "honeypot", "too-fast", "turnstile". */\n spamReason?: string;\n read?: boolean;\n /** Sent with "Send a test submission" from the app. */\n test?: boolean;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scripts\n\n/** What a visitor must have agreed to before a script may load. */\nexport type ConsentCategory = "necessary" | "analytics" | "marketing" | "preferences";\n\n/**\n * One third-party script. `kind` names a known integration whose snippet the\n * runtime writes correctly from a few settings \u2014 "gtm" ({ containerId }),\n * "ga4" ({ measurementId }), "meta-pixel" ({ pixelId }), "linkedin-insight"\n * ({ partnerId }), "hubspot" ({ portalId }), "marketo-munchkin"\n * ({ munchkinId }), "plausible" ({ domain }), "segment" ({ writeKey }),\n * "hotjar" ({ siteId }), "clarity" ({ projectId }), "intercom" ({ appId }) \u2014\n * or "custom" ({ src?, inline?, attributes? }). Plugins may add kinds.\n */\nexport interface ScriptEntry {\n id: string;\n kind: string;\n /** Shown in the app. Default: the integration\'s name. */\n label?: string;\n enabled: boolean;\n settings: { [key: string]: JsonValue };\n placement?: "head" | "body-start" | "body-end";\n /**\n * "eager": in the page\'s initial HTML. "idle": once the page is idle.\n * "interaction": on the visitor\'s first scroll, tap or key press.\n */\n load?: "eager" | "idle" | "interaction";\n /** Absent = "necessary" for nothing known; integrations declare a default. */\n consent?: ConsentCategory;\n /** Page-path globs. Empty or absent `include` = every page. */\n include?: string[];\n exclude?: string[];\n /** Load in development and in the editor\'s preview too. Default false. */\n inPreview?: boolean;\n /** A note for colleagues: who asked for it and why. */\n note?: string;\n}\n\nexport interface ConsentSettings {\n /**\n * "none": everything enabled loads. "banner": the built-in consent banner\n * asks first. "external": another consent tool decides and signals through\n * `window.galleyConsent.set(...)` or Google Consent Mode.\n */\n mode: "none" | "banner" | "external";\n /** Categories on before the visitor chooses. "necessary" is always on. */\n defaults?: ConsentCategory[];\n banner?: {\n title?: string;\n text?: string;\n acceptLabel?: string;\n rejectLabel?: string;\n settingsLabel?: string;\n /** The button that saves the choices made under "settings". */\n saveLabel?: string;\n policyUrl?: string;\n policyLabel?: string;\n /** Name and one-line description of each category, as the banner lists them. */\n categories?: { [category in ConsentCategory]?: { label?: string; description?: string } };\n };\n /** Send Google Consent Mode v2 signals to gtag/GTM. */\n googleConsentMode?: boolean;\n}\n\nexport interface ScriptsConfig {\n scripts: ScriptEntry[];\n consent?: ConsentSettings;\n}\n\n/** What a known integration needs, for the app\'s "add a script" catalogue. */\nexport interface ScriptIntegrationInfo {\n kind: string;\n name: string;\n description: string;\n category: "tag-manager" | "analytics" | "advertising" | "marketing" | "support" | "other";\n defaultConsent: ConsentCategory;\n defaultPlacement: "head" | "body-start" | "body-end";\n /** The settings it asks for. */\n settings: Array<{ key: string; label: string; placeholder?: string; pattern?: string; help?: string; required?: boolean }>;\n docsUrl?: string;\n}\n\n/** What a form provider needs, for the app\'s destination picker. */\nexport interface FormProviderInfo {\n id: string;\n name: string;\n description: string;\n settings: Array<{ key: string; label: string; placeholder?: string; pattern?: string; help?: string; required?: boolean }>;\n /** Whether its field list can be read from an existing form on the provider\'s side. */\n canImportFields: boolean;\n docsUrl?: string;\n}\n', "catalog-data.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
161892
162220
|
// @ts-check
|
|
161893
162221
|
// Generated by scripts/sync-contract.mjs from packages/core/src/kit-catalog.ts \u2014 do not edit by hand.
|
|
161894
162222
|
/** @typedef {import("./kit").FormProviderInfo} FormProviderInfo */
|
|
@@ -162181,7 +162509,7 @@ export const SCRIPT_INTEGRATIONS = [
|
|
|
162181
162509
|
],
|
|
162182
162510
|
},
|
|
162183
162511
|
];
|
|
162184
|
-
`, "catalog.js": `// Vendored from @galley/astro 0.1.
|
|
162512
|
+
`, "catalog.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162185
162513
|
// @ts-check
|
|
162186
162514
|
// \`@galley/astro/catalog\` \u2014 what the site kit knows how to do, as JSON-able
|
|
162187
162515
|
// data, so an app can list it: the form destinations, the third-party
|
|
@@ -162223,8 +162551,8 @@ export function scriptIntegration(kind) {
|
|
|
162223
162551
|
export function formProvider(id) {
|
|
162224
162552
|
return FORM_PROVIDERS.find((entry) => entry.id === id);
|
|
162225
162553
|
}
|
|
162226
|
-
`, "schema.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// `@galley/astro/schema` \u2014 zod schemas for the two kinds of file the site kit\n// reads: a form (src/content/forms/<id>.json) and the scripts setup\n// (src/data/scripts.json). They match the contract in kit.d.ts exactly\n// (test/contract.test.ts fails if they drift) and add the checks a type\n// cannot express \u2014 unknown field references, ids that don\'t look like the\n// vendor\'s ids \u2014 with messages a person can act on.\n//\n// zod comes from Astro (`astro/zod`), so the schema is the same zod the\n// site\'s content config uses and the package adds no dependency.\nimport { z } from "astro/zod";\nimport { FORM_PROVIDERS, SCRIPT_INTEGRATIONS } from "./catalog-data.js";\n\n/** @typedef {import("./kit").JsonValue} JsonValue */\n\n/** @type {z.ZodType<JsonValue>} */\nconst json = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(json), z.record(z.string(), json)]));\nconst settings = z.record(z.string(), json);\nconst stringMap = z.record(z.string(), z.string());\n\nexport const FIELD_TYPES = /** @type {const} */ ([\n "text",\n "email",\n "tel",\n "url",\n "number",\n "textarea",\n "select",\n "radio",\n "checkbox",\n "checkboxes",\n "date",\n "hidden",\n "consent",\n "heading",\n "paragraph",\n]);\n\n/** Types that are only layout: they have no value and are never submitted. */\nexport const LAYOUT_TYPES = new Set(["heading", "paragraph"]);\n/** Types that need `options`. */\nexport const OPTION_TYPES = new Set(["select", "radio", "checkboxes"]);\n\nconst FIELD_ID = /^[a-z][a-z0-9_-]*$/;\n\nexport const formFieldSchema = z.object({\n id: z.string().regex(FIELD_ID, "Use lowercase letters, digits, hyphens and underscores, starting with a letter."),\n type: z.enum(FIELD_TYPES),\n label: z.string().optional(),\n name: z.string().optional(),\n placeholder: z.string().optional(),\n help: z.string().optional(),\n required: z.boolean().optional(),\n options: z.array(z.object({ value: z.string(), label: z.string() })).optional(),\n defaultValue: z.string().optional(),\n width: z.enum(["full", "half"]).optional(),\n validation: z\n .object({\n pattern: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n message: z.string().optional(),\n businessEmailOnly: z.boolean().optional(),\n })\n .optional(),\n showWhen: z\n .object({\n field: z.string(),\n equals: z.string().optional(),\n notEquals: z.string().optional(),\n in: z.array(z.string()).optional(),\n })\n .optional(),\n autofill: z\n .object({\n from: z.enum(["query", "utm", "referrer", "page-url", "page-title", "cookie"]),\n key: z.string().optional(),\n touch: z.enum(["first", "last"]).optional(),\n })\n .optional(),\n text: z.string().optional(),\n step: z.number().int().min(0).optional(),\n});\n\nexport const formDestinationSchema = z.object({\n provider: z.string().min(1),\n settings,\n mapping: stringMap.optional(),\n constants: stringMap.optional(),\n when: z.object({ field: z.string(), equals: z.string() }).optional(),\n});\n\nexport const formActionSchema = z.discriminatedUnion("type", [\n z.object({ type: z.literal("message"), title: z.string().optional(), text: z.string() }),\n z.object({ type: z.literal("redirect"), url: z.string(), passFields: z.array(z.string()).optional(), delaySeconds: z.number().optional() }),\n z.object({ type: z.literal("download"), url: z.string(), label: z.string().optional(), auto: z.boolean().optional() }),\n z.object({\n type: z.literal("event"),\n name: z.string(),\n target: z.enum(["dataLayer", "gtag", "dom"]).optional(),\n params: stringMap.optional(),\n }),\n z.object({ type: z.literal("webhook"), url: z.string() }),\n z.object({ type: z.literal("script"), code: z.string() }),\n]);\n\nconst formShape = z.object({\n name: z.string(),\n description: z.string().optional(),\n fields: z.array(formFieldSchema),\n submitLabel: z.string(),\n steps: z.array(z.object({ title: z.string().optional(), nextLabel: z.string().optional() })).optional(),\n destinations: z.array(formDestinationSchema),\n afterSubmit: z.array(formActionSchema),\n errorMessage: z.string().optional(),\n messages: stringMap.optional(),\n spam: z\n .object({\n honeypot: z.boolean().optional(),\n minSeconds: z.number().optional(),\n turnstileSiteKey: z.string().optional(),\n })\n .optional(),\n appearance: z\n .object({\n layout: z.enum(["stacked", "inline"]).optional(),\n size: z.enum(["regular", "compact"]).optional(),\n labels: z.enum(["above", "floating", "hidden"]).optional(),\n })\n .optional(),\n});\n\n/**\n * The checks across fields: references point at real fields, ids are unique,\n * choices have options, each built-in destination has the settings it needs.\n *\n * @param {import("./kit").FormDefinition} form\n * @param {z.RefinementCtx} ctx\n */\nfunction checkForm(form, ctx) {\n const ids = new Set();\n const issue = (/** @type {(string | number)[]} */ path, /** @type {string} */ message) => ctx.addIssue({ code: "custom", path, message });\n\n form.fields.forEach((field, index) => {\n if (ids.has(field.id)) issue(["fields", index, "id"], `Two fields are called \u201C${field.id}\u201D. Each field needs its own id.`);\n ids.add(field.id);\n if (OPTION_TYPES.has(field.type) && !(field.options && field.options.length > 0)) {\n issue(["fields", index, "options"], `\u201C${field.id}\u201D is a ${field.type} field, so it needs at least one option.`);\n }\n if ((field.type === "heading" || field.type === "paragraph" || field.type === "consent") && !field.text && !field.label) {\n issue(["fields", index, "text"], `\u201C${field.id}\u201D is a ${field.type}, so it needs its text.`);\n }\n if (field.validation?.pattern !== undefined) {\n try {\n new RegExp(field.validation.pattern, "u");\n } catch {\n issue(["fields", index, "validation", "pattern"], `The pattern for \u201C${field.id}\u201D isn\'t a regular expression a browser can read.`);\n }\n }\n if (field.step !== undefined && (form.steps?.length ?? 1) <= field.step) {\n issue(["fields", index, "step"], `\u201C${field.id}\u201D is on step ${field.step + 1}, but the form has ${form.steps?.length ?? 1} step${(form.steps?.length ?? 1) === 1 ? "" : "s"}.`);\n }\n });\n form.fields.forEach((field, index) => {\n if (field.showWhen && !ids.has(field.showWhen.field)) issue(["fields", index, "showWhen", "field"], `\u201C${field.id}\u201D depends on \u201C${field.showWhen.field}\u201D, which isn\'t a field of this form.`);\n });\n if (form.destinations.length === 0) issue(["destinations"], "Add at least one destination, so submissions go somewhere.");\n form.destinations.forEach((destination, index) => {\n if (destination.when && !ids.has(destination.when.field)) issue(["destinations", index, "when", "field"], `This destination depends on \u201C${destination.when.field}\u201D, which isn\'t a field of this form.`);\n for (const key of Object.keys(destination.mapping ?? {})) {\n if (!ids.has(key)) issue(["destinations", index, "mapping", key], `The mapping names \u201C${key}\u201D, which isn\'t a field of this form.`);\n }\n const info = FORM_PROVIDERS.find((entry) => entry.id === destination.provider);\n\n for (const setting of info?.settings ?? []) {\n const value = destination.settings[setting.key];\n\n if (value === undefined || value === "" || value === null) {\n if (setting.required) issue(["destinations", index, "settings", setting.key], `${info?.name} needs its ${setting.label.toLowerCase()} (settings.${setting.key}).`);\n continue;\n }\n if (setting.pattern && !new RegExp(setting.pattern).test(String(value))) {\n issue(["destinations", index, "settings", setting.key], `\u201C${String(value)}\u201D doesn\'t look like a ${info?.name} ${setting.label.toLowerCase()}${setting.placeholder ? ` (for example ${setting.placeholder})` : ""}.`);\n }\n }\n });\n form.afterSubmit.forEach((action, index) => {\n if (action.type === "redirect") {\n for (const field of action.passFields ?? []) if (!ids.has(field)) issue(["afterSubmit", index, "passFields"], `The redirect passes \u201C${field}\u201D, which isn\'t a field of this form.`);\n }\n });\n}\n\n/** A form file: src/content/forms/<id>.json. */\nexport const formSchema = formShape.superRefine(checkForm);\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scripts\n\nconst consentCategory = z.enum(["necessary", "analytics", "marketing", "preferences"]);\nconst placement = z.enum(["head", "body-start", "body-end"]);\n\nexport const scriptEntrySchema = z.object({\n id: z.string().regex(FIELD_ID, "Use lowercase letters, digits, hyphens and underscores, starting with a letter."),\n kind: z.string().min(1),\n label: z.string().optional(),\n enabled: z.boolean(),\n settings,\n placement: placement.optional(),\n load: z.enum(["eager", "idle", "interaction"]).optional(),\n consent: consentCategory.optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n inPreview: z.boolean().optional(),\n note: z.string().optional(),\n});\n\nconst categoryText = z.object({ label: z.string().optional(), description: z.string().optional() });\n\nexport const consentSettingsSchema = z.object({\n mode: z.enum(["none", "banner", "external"]),\n defaults: z.array(consentCategory).optional(),\n banner: z\n .object({\n title: z.string().optional(),\n text: z.string().optional(),\n acceptLabel: z.string().optional(),\n rejectLabel: z.string().optional(),\n settingsLabel: z.string().optional(),\n saveLabel: z.string().optional(),\n policyUrl: z.string().optional(),\n policyLabel: z.string().optional(),\n categories: z\n .object({\n necessary: categoryText.optional(),\n analytics: categoryText.optional(),\n marketing: categoryText.optional(),\n preferences: categoryText.optional(),\n })\n .optional(),\n })\n .optional(),\n googleConsentMode: z.boolean().optional(),\n});\n\n/**\n * Each enabled entry of a known kind has the settings its snippet needs, in\n * the shape the vendor issues them \u2014 so a typo is a build error, not a tag\n * that silently does nothing.\n *\n * @param {import("./kit").ScriptsConfig} config\n * @param {z.RefinementCtx} ctx\n */\nfunction checkScripts(config, ctx) {\n const ids = new Set();\n\n config.scripts.forEach((entry, index) => {\n const at = (/** @type {string} */ key) => ["scripts", index, "settings", key];\n\n if (ids.has(entry.id)) ctx.addIssue({ code: "custom", path: ["scripts", index, "id"], message: `Two scripts are called \u201C${entry.id}\u201D. Each needs its own id.` });\n ids.add(entry.id);\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n // A kind this kit doesn\'t know (a plugin\'s) is written like "custom".\n const custom = entry.kind === "custom" || !info;\n\n if (custom) checkCustom(entry, at, ctx);\n if (!info) return;\n for (const setting of info.settings) {\n const value = entry.settings[setting.key];\n\n if (value === undefined || value === null || value === "") {\n if (setting.required && entry.enabled) ctx.addIssue({ code: "custom", path: at(setting.key), message: `${info.name} needs its ${setting.label} (settings.${setting.key}${setting.placeholder ? `, like ${setting.placeholder}` : ""}).` });\n continue;\n }\n if (setting.pattern && !new RegExp(setting.pattern).test(String(value))) {\n ctx.addIssue({\n code: "custom",\n path: at(setting.key),\n message: `\u201C${String(value)}\u201D doesn\'t look like a ${info.name} ${setting.label}${setting.placeholder ? ` (it looks like ${setting.placeholder})` : ""}.`,\n });\n }\n }\n if (entry.enabled && entry.kind === "plausible" && !entry.settings.scriptId && !entry.settings.domain) {\n ctx.addIssue({ code: "custom", path: at("scriptId"), message: "Plausible needs its script ID (pa-\u2026, from Site installation) or, for the older script, the site\'s domain." });\n }\n });\n}\n\n/**\n * The rules for a script written from its own src / inline: "custom", and\n * any kind this kit has no snippet for.\n *\n * @param {import("./kit").ScriptEntry} entry\n * @param {(key: string) => (string | number)[]} at\n * @param {z.RefinementCtx} ctx\n */\nfunction checkCustom(entry, at, ctx) {\n if (entry.enabled && !entry.settings.src && !entry.settings.inline) {\n ctx.addIssue({\n code: "custom",\n path: at("src"),\n message: entry.kind === "custom" ? "A custom script needs a script address (settings.src) or code (settings.inline)." : `A \u201C${entry.kind}\u201D script is written from its own settings.src (the script\'s address) or settings.inline (its code); give it one of them.`,\n });\n }\n if (entry.settings.attributes !== undefined) {\n const attributes = entry.settings.attributes;\n\n if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes) || Object.values(attributes).some((value) => typeof value !== "string" && typeof value !== "boolean")) {\n ctx.addIssue({ code: "custom", path: at("attributes"), message: "settings.attributes is a list of attribute names and their text (or true for a bare attribute)." });\n } else if (Object.keys(attributes).some((name) => !/^[a-z][a-z0-9-]*$/i.test(name) || /^on/i.test(name) || name.toLowerCase() === "src" || name.toLowerCase() === "type")) {\n ctx.addIssue({ code: "custom", path: at("attributes"), message: "settings.attributes can\'t set src, type or on\u2026 handlers; use settings.src and settings.inline." });\n }\n }\n}\n\nconst scriptsShape = z.object({\n scripts: z.array(scriptEntrySchema),\n consent: consentSettingsSchema.optional(),\n});\n\n/** The scripts setup: src/data/scripts.json. */\nexport const scriptsSchema = scriptsShape.superRefine(checkScripts);\n\n/**\n * A zod error as plain lines: \u201Cscripts[0].settings.containerId: \u2026 \u201D.\n *\n * @param {z.ZodError} error\n * @returns {string[]}\n */\nexport function describeIssues(error) {\n return error.issues.map((issue) => {\n const path = issue.path.map((part, index) => (typeof part === "number" ? `[${part}]` : `${index === 0 ? "" : "."}${String(part)}`)).join("");\n\n return path ? `${path}: ${issue.message}` : issue.message;\n });\n}\n', "components/Form.astro": '---\n// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// <Form id="contact" /> renders src/content/forms/contact.json (the `forms`\n// collection); <Form definition={\u2026} /> renders a definition given directly.\n// The whole form is server-rendered; one small script per page (bundled by\n// Astro) runs every form on it. See docs/forms.md.\n//\n// Props: id, definition, collection, endpoint, class, submitClass,\n// backClass, headingLevel, unstyled. Slots: before, after, submit, success.\nimport { getEntry } from "astro:content";\nimport type { FormDefinition } from "../kit";\nimport { renderForm } from "../forms/render.js";\nimport { describeIssues, formSchema } from "../schema.js";\nimport { options } from "../runtime/site-config.js";\nimport css from "../forms/forms.css?raw";\n\ninterface Props {\n /** The form\'s id: its file name in the forms collection. */\n id?: string;\n /** A definition to render instead of looking one up. */\n definition?: FormDefinition;\n /** The collection to look in. Default: the integration\'s `forms.collection` ("forms"). */\n collection?: string;\n /** Capture address for "galley" destinations, instead of the site-wide one. */\n endpoint?: string;\n /** Extra classes on the <form>. */\n class?: string;\n /** Extra classes on the submit (and next) button, e.g. the site\'s own "button". */\n submitClass?: string;\n /** Extra classes on a multi-step form\'s back button, e.g. "button button--secondary". */\n backClass?: string;\n /** Level of `heading` fields (2\u20136). Default 3. */\n headingLevel?: number;\n /** Emit no CSS at all; style every part yourself. */\n unstyled?: boolean;\n}\n\nconst { id, definition, collection = options.collection, endpoint, class: className, submitClass, backClass, headingLevel, unstyled = false } = Astro.props;\nlet form: FormDefinition;\nlet formId = id;\n\nif (definition) {\n const parsed = formSchema.safeParse(definition);\n if (!parsed.success) throw new Error(`The form ${id ? `\u201C${id}\u201D` : "given to <Form>"} has problems:\\n${describeIssues(parsed.error).map((line) => ` - ${line}`).join("\\n")}`);\n form = parsed.data as FormDefinition;\n formId ??= form.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "form";\n} else {\n if (!id) throw new Error("<Form> needs an id (a file in the forms collection) or a definition.");\n const entry = await getEntry(collection as any, id).catch(() => undefined);\n if (!entry) throw new Error(`No form called \u201C${id}\u201D in the \u201C${collection}\u201D collection. Add src/content/forms/${id}.json, or check the collection in src/content.config.ts.`);\n form = (entry as any).data as FormDefinition;\n}\n\n// Ids stay unique when one form appears twice on a page; the CSS is written once.\nconst locals = Astro.locals as Record<string, any>;\nconst seen: Record<string, number> = (locals.__galleyForms ??= {});\nconst count = (seen[formId!] = (seen[formId!] ?? 0) + 1);\nconst writeCss = !unstyled && !locals.__galleyFormCss;\nif (writeCss) locals.__galleyFormCss = true;\nconst pageUrl = new URL(Astro.url.pathname, Astro.site ?? Astro.url).href;\nconst parts = renderForm(form, formId!, {\n endpoint: endpoint ?? options.endpoint,\n pageUrl,\n messages: options.messages,\n instance: count > 1 ? String(count) : undefined,\n className,\n submitClass,\n backClass,\n headingLevel,\n allowFormScripts: options.allowFormScripts,\n unstyled,\n freeEmailDomains: options.freeEmailDomains,\n base: import.meta.env.BASE_URL,\n});\n// Each note once per build (or dev server): "no capture address" is one note\n// for the whole site however many forms it applies to.\nconst warned: Set<string> = ((globalThis as any).__galleyFormWarnings ??= new Set());\nfor (const notice of parts.notices) {\n if (!warned.has(notice.key)) {\n warned.add(notice.key);\n console.warn(`[galley] ${notice.text}`);\n }\n}\nconst styles = writeCss ? css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, "").replace(/\\s+/g, " ").replace(/\\s*([{};,>])\\s*/g, "$1").trim() : "";\n---\n\n{styles && <style is:inline set:html={styles} data-galley-form-css />}\n<Fragment set:html={parts.start} />\n<slot name="before" />\n<Fragment set:html={parts.middle + parts.actionsStart} />\n{Astro.slots.has("submit") ? <slot name="submit" /> : <Fragment set:html={parts.submit} />}\n<Fragment set:html={parts.actionsEnd} />\n<slot name="after" />\n<Fragment set:html={parts.formEnd + parts.successStart} />\n{Astro.slots.has("success") ? <slot name="success" /> : <Fragment set:html={parts.successDefault} />}\n<Fragment set:html={parts.end} />\n\n<script>\n import { initForms } from "../client/forms.js";\n\n initForms();\n</script>\n', "components/Scripts.astro": `---
|
|
162227
|
-
// Vendored from @galley/astro 0.1.
|
|
162554
|
+
`, "schema.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// `@galley/astro/schema` \u2014 zod schemas for the two kinds of file the site kit\n// reads: a form (src/content/forms/<id>.json) and the scripts setup\n// (src/data/scripts.json). They match the contract in kit.d.ts exactly\n// (test/contract.test.ts fails if they drift) and add the checks a type\n// cannot express \u2014 unknown field references, ids that don\'t look like the\n// vendor\'s ids \u2014 with messages a person can act on.\n//\n// zod comes from Astro (`astro/zod`), so the schema is the same zod the\n// site\'s content config uses and the package adds no dependency.\nimport { z } from "astro/zod";\nimport { FORM_PROVIDERS, SCRIPT_INTEGRATIONS } from "./catalog-data.js";\n\n/** @typedef {import("./kit").JsonValue} JsonValue */\n\n/** @type {z.ZodType<JsonValue>} */\nconst json = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(json), z.record(z.string(), json)]));\nconst settings = z.record(z.string(), json);\nconst stringMap = z.record(z.string(), z.string());\n\nexport const FIELD_TYPES = /** @type {const} */ ([\n "text",\n "email",\n "tel",\n "url",\n "number",\n "textarea",\n "select",\n "radio",\n "checkbox",\n "checkboxes",\n "date",\n "hidden",\n "consent",\n "heading",\n "paragraph",\n]);\n\n/** Types that are only layout: they have no value and are never submitted. */\nexport const LAYOUT_TYPES = new Set(["heading", "paragraph"]);\n/** Types that need `options`. */\nexport const OPTION_TYPES = new Set(["select", "radio", "checkboxes"]);\n\nconst FIELD_ID = /^[a-z][a-z0-9_-]*$/;\n\nexport const formFieldSchema = z.object({\n id: z.string().regex(FIELD_ID, "Use lowercase letters, digits, hyphens and underscores, starting with a letter."),\n type: z.enum(FIELD_TYPES),\n label: z.string().optional(),\n name: z.string().optional(),\n placeholder: z.string().optional(),\n help: z.string().optional(),\n required: z.boolean().optional(),\n options: z.array(z.object({ value: z.string(), label: z.string() })).optional(),\n defaultValue: z.string().optional(),\n width: z.enum(["full", "half"]).optional(),\n validation: z\n .object({\n pattern: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n message: z.string().optional(),\n businessEmailOnly: z.boolean().optional(),\n })\n .optional(),\n showWhen: z\n .object({\n field: z.string(),\n equals: z.string().optional(),\n notEquals: z.string().optional(),\n in: z.array(z.string()).optional(),\n })\n .optional(),\n autofill: z\n .object({\n from: z.enum(["query", "utm", "referrer", "page-url", "page-title", "cookie"]),\n key: z.string().optional(),\n touch: z.enum(["first", "last"]).optional(),\n })\n .optional(),\n text: z.string().optional(),\n step: z.number().int().min(0).optional(),\n});\n\nexport const formDestinationSchema = z.object({\n provider: z.string().min(1),\n settings,\n mapping: stringMap.optional(),\n constants: stringMap.optional(),\n when: z.object({ field: z.string(), equals: z.string() }).optional(),\n});\n\nexport const formActionSchema = z.discriminatedUnion("type", [\n z.object({ type: z.literal("message"), title: z.string().optional(), text: z.string() }),\n z.object({ type: z.literal("redirect"), url: z.string(), passFields: z.array(z.string()).optional(), delaySeconds: z.number().optional() }),\n z.object({ type: z.literal("download"), url: z.string(), label: z.string().optional(), auto: z.boolean().optional() }),\n z.object({\n type: z.literal("event"),\n name: z.string(),\n target: z.enum(["dataLayer", "gtag", "dom"]).optional(),\n params: stringMap.optional(),\n }),\n z.object({ type: z.literal("webhook"), url: z.string() }),\n z.object({ type: z.literal("script"), code: z.string() }),\n]);\n\nconst formShape = z.object({\n name: z.string(),\n description: z.string().optional(),\n fields: z.array(formFieldSchema),\n submitLabel: z.string(),\n steps: z.array(z.object({ title: z.string().optional(), nextLabel: z.string().optional() })).optional(),\n destinations: z.array(formDestinationSchema),\n afterSubmit: z.array(formActionSchema),\n errorMessage: z.string().optional(),\n messages: stringMap.optional(),\n spam: z\n .object({\n honeypot: z.boolean().optional(),\n minSeconds: z.number().optional(),\n turnstileSiteKey: z.string().optional(),\n })\n .optional(),\n appearance: z\n .object({\n layout: z.enum(["stacked", "inline"]).optional(),\n size: z.enum(["regular", "compact"]).optional(),\n labels: z.enum(["above", "floating", "hidden"]).optional(),\n })\n .optional(),\n});\n\n/**\n * The checks across fields: references point at real fields, ids are unique,\n * choices have options, each built-in destination has the settings it needs.\n *\n * @param {import("./kit").FormDefinition} form\n * @param {z.RefinementCtx} ctx\n */\nfunction checkForm(form, ctx) {\n const ids = new Set();\n const issue = (/** @type {(string | number)[]} */ path, /** @type {string} */ message) => ctx.addIssue({ code: "custom", path, message });\n\n form.fields.forEach((field, index) => {\n if (ids.has(field.id)) issue(["fields", index, "id"], `Two fields are called \u201C${field.id}\u201D. Each field needs its own id.`);\n ids.add(field.id);\n if (OPTION_TYPES.has(field.type) && !(field.options && field.options.length > 0)) {\n issue(["fields", index, "options"], `\u201C${field.id}\u201D is a ${field.type} field, so it needs at least one option.`);\n }\n if ((field.type === "heading" || field.type === "paragraph" || field.type === "consent") && !field.text && !field.label) {\n issue(["fields", index, "text"], `\u201C${field.id}\u201D is a ${field.type}, so it needs its text.`);\n }\n if (field.validation?.pattern !== undefined) {\n try {\n new RegExp(field.validation.pattern, "u");\n } catch {\n issue(["fields", index, "validation", "pattern"], `The pattern for \u201C${field.id}\u201D isn\'t a regular expression a browser can read.`);\n }\n }\n if (field.step !== undefined && (form.steps?.length ?? 1) <= field.step) {\n issue(["fields", index, "step"], `\u201C${field.id}\u201D is on step ${field.step + 1}, but the form has ${form.steps?.length ?? 1} step${(form.steps?.length ?? 1) === 1 ? "" : "s"}.`);\n }\n });\n form.fields.forEach((field, index) => {\n if (field.showWhen && !ids.has(field.showWhen.field)) issue(["fields", index, "showWhen", "field"], `\u201C${field.id}\u201D depends on \u201C${field.showWhen.field}\u201D, which isn\'t a field of this form.`);\n });\n if (form.destinations.length === 0) issue(["destinations"], "Add at least one destination, so submissions go somewhere.");\n form.destinations.forEach((destination, index) => {\n if (destination.when && !ids.has(destination.when.field)) issue(["destinations", index, "when", "field"], `This destination depends on \u201C${destination.when.field}\u201D, which isn\'t a field of this form.`);\n for (const key of Object.keys(destination.mapping ?? {})) {\n if (!ids.has(key)) issue(["destinations", index, "mapping", key], `The mapping names \u201C${key}\u201D, which isn\'t a field of this form.`);\n }\n const info = FORM_PROVIDERS.find((entry) => entry.id === destination.provider);\n\n for (const setting of info?.settings ?? []) {\n const value = destination.settings[setting.key];\n\n if (value === undefined || value === "" || value === null) {\n if (setting.required) issue(["destinations", index, "settings", setting.key], `${info?.name} needs its ${setting.label.toLowerCase()} (settings.${setting.key}).`);\n continue;\n }\n if (setting.pattern && !new RegExp(setting.pattern).test(String(value))) {\n issue(["destinations", index, "settings", setting.key], `\u201C${String(value)}\u201D doesn\'t look like a ${info?.name} ${setting.label.toLowerCase()}${setting.placeholder ? ` (for example ${setting.placeholder})` : ""}.`);\n }\n }\n });\n form.afterSubmit.forEach((action, index) => {\n if (action.type === "redirect") {\n for (const field of action.passFields ?? []) if (!ids.has(field)) issue(["afterSubmit", index, "passFields"], `The redirect passes \u201C${field}\u201D, which isn\'t a field of this form.`);\n }\n });\n}\n\n/** A form file: src/content/forms/<id>.json. */\nexport const formSchema = formShape.superRefine(checkForm);\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scripts\n\nconst consentCategory = z.enum(["necessary", "analytics", "marketing", "preferences"]);\nconst placement = z.enum(["head", "body-start", "body-end"]);\n\nexport const scriptEntrySchema = z.object({\n id: z.string().regex(FIELD_ID, "Use lowercase letters, digits, hyphens and underscores, starting with a letter."),\n kind: z.string().min(1),\n label: z.string().optional(),\n enabled: z.boolean(),\n settings,\n placement: placement.optional(),\n load: z.enum(["eager", "idle", "interaction"]).optional(),\n consent: consentCategory.optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n inPreview: z.boolean().optional(),\n note: z.string().optional(),\n});\n\nconst categoryText = z.object({ label: z.string().optional(), description: z.string().optional() });\n\nexport const consentSettingsSchema = z.object({\n mode: z.enum(["none", "banner", "external"]),\n defaults: z.array(consentCategory).optional(),\n banner: z\n .object({\n title: z.string().optional(),\n text: z.string().optional(),\n acceptLabel: z.string().optional(),\n rejectLabel: z.string().optional(),\n settingsLabel: z.string().optional(),\n saveLabel: z.string().optional(),\n policyUrl: z.string().optional(),\n policyLabel: z.string().optional(),\n categories: z\n .object({\n necessary: categoryText.optional(),\n analytics: categoryText.optional(),\n marketing: categoryText.optional(),\n preferences: categoryText.optional(),\n })\n .optional(),\n })\n .optional(),\n googleConsentMode: z.boolean().optional(),\n});\n\n/**\n * Each enabled entry of a known kind has the settings its snippet needs, in\n * the shape the vendor issues them \u2014 so a typo is a build error, not a tag\n * that silently does nothing.\n *\n * @param {import("./kit").ScriptsConfig} config\n * @param {z.RefinementCtx} ctx\n */\nfunction checkScripts(config, ctx) {\n const ids = new Set();\n\n config.scripts.forEach((entry, index) => {\n const at = (/** @type {string} */ key) => ["scripts", index, "settings", key];\n\n if (ids.has(entry.id)) ctx.addIssue({ code: "custom", path: ["scripts", index, "id"], message: `Two scripts are called \u201C${entry.id}\u201D. Each needs its own id.` });\n ids.add(entry.id);\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n // A kind this kit doesn\'t know (a plugin\'s) is written like "custom".\n const custom = entry.kind === "custom" || !info;\n\n if (custom) checkCustom(entry, at, ctx);\n if (!info) return;\n for (const setting of info.settings) {\n const value = entry.settings[setting.key];\n\n if (value === undefined || value === null || value === "") {\n if (setting.required && entry.enabled) ctx.addIssue({ code: "custom", path: at(setting.key), message: `${info.name} needs its ${setting.label} (settings.${setting.key}${setting.placeholder ? `, like ${setting.placeholder}` : ""}).` });\n continue;\n }\n if (setting.pattern && !new RegExp(setting.pattern).test(String(value))) {\n ctx.addIssue({\n code: "custom",\n path: at(setting.key),\n message: `\u201C${String(value)}\u201D doesn\'t look like a ${info.name} ${setting.label}${setting.placeholder ? ` (it looks like ${setting.placeholder})` : ""}.`,\n });\n }\n }\n if (entry.enabled && entry.kind === "plausible" && !entry.settings.scriptId && !entry.settings.domain) {\n ctx.addIssue({ code: "custom", path: at("scriptId"), message: "Plausible needs its script ID (pa-\u2026, from Site installation) or, for the older script, the site\'s domain." });\n }\n });\n}\n\n/**\n * The rules for a script written from its own src / inline: "custom", and\n * any kind this kit has no snippet for.\n *\n * @param {import("./kit").ScriptEntry} entry\n * @param {(key: string) => (string | number)[]} at\n * @param {z.RefinementCtx} ctx\n */\nfunction checkCustom(entry, at, ctx) {\n if (entry.enabled && !entry.settings.src && !entry.settings.inline) {\n ctx.addIssue({\n code: "custom",\n path: at("src"),\n message: entry.kind === "custom" ? "A custom script needs a script address (settings.src) or code (settings.inline)." : `A \u201C${entry.kind}\u201D script is written from its own settings.src (the script\'s address) or settings.inline (its code); give it one of them.`,\n });\n }\n if (entry.settings.attributes !== undefined) {\n const attributes = entry.settings.attributes;\n\n if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes) || Object.values(attributes).some((value) => typeof value !== "string" && typeof value !== "boolean")) {\n ctx.addIssue({ code: "custom", path: at("attributes"), message: "settings.attributes is a list of attribute names and their text (or true for a bare attribute)." });\n } else if (Object.keys(attributes).some((name) => !/^[a-z][a-z0-9-]*$/i.test(name) || /^on/i.test(name) || name.toLowerCase() === "src" || name.toLowerCase() === "type")) {\n ctx.addIssue({ code: "custom", path: at("attributes"), message: "settings.attributes can\'t set src, type or on\u2026 handlers; use settings.src and settings.inline." });\n }\n }\n}\n\nconst scriptsShape = z.object({\n scripts: z.array(scriptEntrySchema),\n consent: consentSettingsSchema.optional(),\n});\n\n/** The scripts setup: src/data/scripts.json. */\nexport const scriptsSchema = scriptsShape.superRefine(checkScripts);\n\n/**\n * A zod error as plain lines: \u201Cscripts[0].settings.containerId: \u2026 \u201D.\n *\n * @param {z.ZodError} error\n * @returns {string[]}\n */\nexport function describeIssues(error) {\n return error.issues.map((issue) => {\n const path = issue.path.map((part, index) => (typeof part === "number" ? `[${part}]` : `${index === 0 ? "" : "."}${String(part)}`)).join("");\n\n return path ? `${path}: ${issue.message}` : issue.message;\n });\n}\n', "components/Form.astro": '---\n// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// <Form id="contact" /> renders src/content/forms/contact.json (the `forms`\n// collection); <Form definition={\u2026} /> renders a definition given directly.\n// The whole form is server-rendered; one small script per page (bundled by\n// Astro) runs every form on it. See docs/forms.md.\n//\n// Props: id, definition, collection, endpoint, class, submitClass,\n// backClass, headingLevel, unstyled. Slots: before, after, submit, success.\nimport { getEntry } from "astro:content";\nimport type { FormDefinition } from "../kit";\nimport { renderForm } from "../forms/render.js";\nimport { describeIssues, formSchema } from "../schema.js";\nimport { options } from "../runtime/site-config.js";\nimport css from "../forms/forms.css?raw";\n\ninterface Props {\n /** The form\'s id: its file name in the forms collection. */\n id?: string;\n /** A definition to render instead of looking one up. */\n definition?: FormDefinition;\n /** The collection to look in. Default: the integration\'s `forms.collection` ("forms"). */\n collection?: string;\n /** Capture address for "galley" destinations, instead of the site-wide one. */\n endpoint?: string;\n /** Extra classes on the <form>. */\n class?: string;\n /** Extra classes on the submit (and next) button, e.g. the site\'s own "button". */\n submitClass?: string;\n /** Extra classes on a multi-step form\'s back button, e.g. "button button--secondary". */\n backClass?: string;\n /** Level of `heading` fields (2\u20136). Default 3. */\n headingLevel?: number;\n /** Emit no CSS at all; style every part yourself. */\n unstyled?: boolean;\n}\n\nconst { id, definition, collection = options.collection, endpoint, class: className, submitClass, backClass, headingLevel, unstyled = false } = Astro.props;\nlet form: FormDefinition;\nlet formId = id;\n\nif (definition) {\n const parsed = formSchema.safeParse(definition);\n if (!parsed.success) throw new Error(`The form ${id ? `\u201C${id}\u201D` : "given to <Form>"} has problems:\\n${describeIssues(parsed.error).map((line) => ` - ${line}`).join("\\n")}`);\n form = parsed.data as FormDefinition;\n formId ??= form.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "form";\n} else {\n if (!id) throw new Error("<Form> needs an id (a file in the forms collection) or a definition.");\n const entry = await getEntry(collection as any, id).catch(() => undefined);\n if (!entry) throw new Error(`No form called \u201C${id}\u201D in the \u201C${collection}\u201D collection. Add src/content/forms/${id}.json, or check the collection in src/content.config.ts.`);\n form = (entry as any).data as FormDefinition;\n}\n\n// Ids stay unique when one form appears twice on a page; the CSS is written once.\nconst locals = Astro.locals as Record<string, any>;\nconst seen: Record<string, number> = (locals.__galleyForms ??= {});\nconst count = (seen[formId!] = (seen[formId!] ?? 0) + 1);\nconst writeCss = !unstyled && !locals.__galleyFormCss;\nif (writeCss) locals.__galleyFormCss = true;\nconst pageUrl = new URL(Astro.url.pathname, Astro.site ?? Astro.url).href;\nconst parts = renderForm(form, formId!, {\n endpoint: endpoint ?? options.endpoint,\n pageUrl,\n messages: options.messages,\n instance: count > 1 ? String(count) : undefined,\n className,\n submitClass,\n backClass,\n headingLevel,\n allowFormScripts: options.allowFormScripts,\n unstyled,\n freeEmailDomains: options.freeEmailDomains,\n base: import.meta.env.BASE_URL,\n});\n// Each note once per build (or dev server): "no capture address" is one note\n// for the whole site however many forms it applies to.\nconst warned: Set<string> = ((globalThis as any).__galleyFormWarnings ??= new Set());\nfor (const notice of parts.notices) {\n if (!warned.has(notice.key)) {\n warned.add(notice.key);\n console.warn(`[galley] ${notice.text}`);\n }\n}\nconst styles = writeCss ? css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, "").replace(/\\s+/g, " ").replace(/\\s*([{};,>])\\s*/g, "$1").trim() : "";\n---\n\n{styles && <style is:inline set:html={styles} data-galley-form-css />}\n<Fragment set:html={parts.start} />\n<slot name="before" />\n<Fragment set:html={parts.middle + parts.actionsStart} />\n{Astro.slots.has("submit") ? <slot name="submit" /> : <Fragment set:html={parts.submit} />}\n<Fragment set:html={parts.actionsEnd} />\n<slot name="after" />\n<Fragment set:html={parts.formEnd + parts.successStart} />\n{Astro.slots.has("success") ? <slot name="success" /> : <Fragment set:html={parts.successDefault} />}\n<Fragment set:html={parts.end} />\n\n<script>\n import { initForms } from "../client/forms.js";\n\n initForms();\n</script>\n', "components/Scripts.astro": `---
|
|
162555
|
+
// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162228
162556
|
// The managed scripts of src/data/scripts.json, placed by hand. The
|
|
162229
162557
|
// integration already puts them into every page, so most sites never use
|
|
162230
162558
|
// this; it is for layouts that want to decide the spot \u2014 and for the one
|
|
@@ -162253,7 +162581,7 @@ const html = renderPlacement(plan, placement, { consent: scripts?.consent, base
|
|
|
162253
162581
|
---
|
|
162254
162582
|
|
|
162255
162583
|
<Fragment set:html={html} />
|
|
162256
|
-
`, "components/ConsentBanner.astro": '---\n// Vendored from @galley/astro 0.1.
|
|
162584
|
+
`, "components/ConsentBanner.astro": '---\n// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// The consent banner, where the layout wants it (by default the integration\n// adds it before </body>). Rendered only when scripts.json uses\n// `consent.mode: "banner"` and some script \u2014 or a form\'s UTM memory \u2014 needs consent.\nimport { renderBanner } from "../scripts/banner.js";\nimport { planPage, resolveEntries } from "../scripts/plan.js";\nimport { scripts, utm } from "../runtime/site-config.js";\n\nconst consent = scripts?.consent;\nconst base = (import.meta.env.BASE_URL || "/").replace(/\\/+$/, "");\nconst path = base && Astro.url.pathname.startsWith(base) ? Astro.url.pathname.slice(base.length) || "/" : Astro.url.pathname;\nconst plan = planPage(scripts, { path, utm, resolved: scripts ? resolveEntries(scripts) : [] });\nconst html = consent && plan.banner ? renderBanner(consent, plan.categories, { base }) : "";\n---\n\n<Fragment set:html={html} />\n', "components/index.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// `@galley/astro/components`\nexport { default as Form } from "./Form.astro";\nexport { default as Scripts } from "./Scripts.astro";\nexport { default as ConsentBanner } from "./ConsentBanner.astro";\n', "forms/forms.css": `/* Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update. */
|
|
162257
162585
|
/*
|
|
162258
162586
|
* Galley forms \u2014 structural CSS. It sets layout and states only; colours,
|
|
162259
162587
|
* radii and spacing come from these custom properties, so a site themes every
|
|
@@ -162642,7 +162970,7 @@ textarea.galley-form__control {
|
|
|
162642
162970
|
transition: none;
|
|
162643
162971
|
}
|
|
162644
162972
|
}
|
|
162645
|
-
`, "forms/free-email-domains.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Free mailbox providers, for `validation.businessEmailOnly`: an address at\n// one of these domains is refused as "not a work address". The list is kept\n// short on purpose \u2014 the providers with the most personal mailboxes\n// worldwide, and their best-known country variants \u2014 so it stays a few\n// hundred bytes in the page. It is a courtesy check in the browser, not a\n// guarantee: anyone determined can type another address. Sites that need\n// more add domains with `forms.freeEmailDomains` in the integration options.\nexport const FREE_EMAIL_DOMAINS = [\n "gmail.com",\n "googlemail.com",\n "outlook.com",\n "hotmail.com",\n "hotmail.co.uk",\n "hotmail.fr",\n "live.com",\n "msn.com",\n "yahoo.com",\n "yahoo.co.uk",\n "yahoo.co.jp",\n "yahoo.fr",\n "ymail.com",\n "rocketmail.com",\n "aol.com",\n "icloud.com",\n "me.com",\n "mac.com",\n "proton.me",\n "protonmail.com",\n "pm.me",\n "gmx.com",\n "gmx.de",\n "gmx.net",\n "web.de",\n "mail.com",\n "zoho.com",\n "yandex.com",\n "yandex.ru",\n "mail.ru",\n "qq.com",\n "163.com",\n "126.com",\n "naver.com",\n "hanmail.net",\n "libero.it",\n "orange.fr",\n "free.fr",\n "laposte.net",\n "t-online.de",\n "btinternet.com",\n "comcast.net",\n "verizon.net",\n "att.net",\n "fastmail.com",\n "hey.com",\n "tutanota.com",\n "tuta.io",\n "rediffmail.com",\n "uol.com.br",\n "bol.com.br",\n];\n', "forms/logic.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The rules of a form that don\'t need a page: which fields are showing,\n// whether an answer is acceptable, which destinations get the submission and\n// what each one is sent. Shared by the browser runtime and the tests.\n\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n/** @typedef {{ [fieldId: string]: string | string[] }} Values */\n/** @typedef {{ field: FormField; name: string; value: string | string[] }} PayloadItem */\n\nexport const LAYOUT = new Set(["heading", "paragraph"]);\n/** How a ticked box reads in conditions \u2014 "yes", as the capture server stores it and the app\'s builder writes rules. */\nexport const TICKED = "yes";\n\n/**\n * An answer as conditions see it. A box the browser holds as "true" is "yes"\n * (and an unticked one is no answer), so `showWhen` / `when` rules behave in\n * the page exactly as on the server.\n *\n * @param {FormField | undefined} field\n * @param {string | string[] | undefined} value\n */\nexport function conditionValue(field, value) {\n if (field && (field.type === "checkbox" || field.type === "consent")) return value === "true" || value === TICKED ? TICKED : "";\n return value;\n}\n\n/**\n * Destinations the Galley server forwards to after capture (`settings.serverSide: true`):\n * never sent from the page, and never written into it.\n *\n * @param {FormDestination} destination\n */\nexport const isServerSide = (destination) => destination.provider !== "galley" && destination.settings?.serverSide === true;\n\n/** @param {string | string[] | undefined} value */\nconst asList = (value) => (Array.isArray(value) ? value : value === undefined || value === "" ? [] : [value]);\n\n/**\n * Whether one condition holds for the current answers.\n *\n * @param {{ equals?: string; notEquals?: string; in?: string[] }} rule\n * @param {string | string[] | undefined} value\n */\nexport function holds(rule, value) {\n const list = Array.isArray(value) ? value : [value ?? ""];\n\n if (rule.equals === undefined && rule.notEquals === undefined && rule.in === undefined) return asList(value).length > 0;\n if (rule.equals !== undefined && !list.includes(rule.equals)) return false;\n if (rule.notEquals !== undefined && list.includes(rule.notEquals)) return false;\n if (rule.in !== undefined && !list.some((item) => rule.in?.includes(item))) return false;\n return true;\n}\n\n/**\n * The ids of the fields that are showing. A field whose condition depends on\n * a hidden field is hidden too (a hidden field has no answer).\n *\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {Set<string>}\n */\nexport function shownFields(fields, values) {\n const byId = new Map(fields.map((field) => [field.id, field]));\n /** @type {Map<string, boolean>} */\n const memo = new Map();\n /** @param {string} id @param {Set<string>} seen @returns {boolean} */\n const shown = (id, seen) => {\n const known = memo.get(id);\n\n if (known !== undefined) return known;\n const field = byId.get(id);\n let result = Boolean(field);\n\n if (field?.showWhen) {\n const controller = field.showWhen.field;\n\n result = !seen.has(controller) && shown(controller, new Set([...seen, id])) && holds(field.showWhen, conditionValue(byId.get(controller), values[controller]));\n }\n memo.set(id, result);\n return result;\n };\n\n return new Set(fields.filter((field) => shown(field.id, new Set())).map((field) => field.id));\n}\n\n/**\n * Whether the page sends to this destination: not server-side, and its\n * `when` holds.\n *\n * @param {FormDestination} destination\n * @param {Values} values\n * @param {FormField[]} [fields]\n */\nexport function applies(destination, values, fields = []) {\n if (isServerSide(destination)) return false;\n const when = destination.when;\n\n return !when || holds({ equals: when.equals }, conditionValue(fields.find((field) => field.id === when.field), values[when.field]));\n}\n\n/**\n * What one destination is sent: every showing, non-layout field under its\n * mapped name (else `name`, else `id`), then the destination\'s constants.\n *\n * @param {FormDestination} destination\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {{ values: { [name: string]: string | string[] }; items: PayloadItem[] }}\n */\nexport function payloadFor(destination, fields, values) {\n const shown = shownFields(fields, values);\n /** @type {PayloadItem[]} */\n const items = [];\n /** @type {{ [name: string]: string | string[] }} */\n const out = {};\n\n for (const field of fields) {\n if (LAYOUT.has(field.type) || !shown.has(field.id)) continue;\n let value = values[field.id] ?? "";\n\n if ((field.type === "checkbox" || field.type === "consent") && value === "") value = "false";\n const name = destination.mapping?.[field.id] ?? field.name ?? field.id;\n\n items.push({ field, name, value });\n out[name] = value;\n }\n for (const [name, value] of Object.entries(destination.constants ?? {})) out[name] = value;\n return { values: out, items };\n}\n\n/**\n * The visitor\'s answers with hidden fields left out \u2014 what the form submits.\n *\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {Values}\n */\nexport function submittedValues(fields, values) {\n const shown = shownFields(fields, values);\n /** @type {Values} */\n const out = {};\n\n for (const field of fields) if (!LAYOUT.has(field.type) && shown.has(field.id)) out[field.id] = values[field.id] ?? "";\n return out;\n}\n\n/** @param {string} template @param {Record<string, string | number>} values */\nconst fill = (template, values) => template.replace(/\\{(\\w+)\\}/g, (whole, key) => (key in values ? String(values[key]) : whole));\n\n/**\n * Why an answer is refused, in the form\'s words \u2014 or "" when it is fine.\n *\n * @param {FormField} field\n * @param {string | string[]} value\n * @param {Record<string, string>} messages\n * @param {string[]} [freeDomains]\n * @returns {string}\n */\nexport function problem(field, value, messages, freeDomains = []) {\n const rules = field.validation ?? {};\n const say = (/** @type {string} */ key, /** @type {Record<string, string | number>} */ vars = {}) => rules.message || fill(messages[key] ?? key, { label: field.label ?? field.id, ...vars });\n const list = asList(value);\n const text = Array.isArray(value) ? value.join(",") : value;\n\n if (LAYOUT.has(field.type) || field.type === "hidden") return "";\n if (list.length === 0 || ((field.type === "checkbox" || field.type === "consent") && text !== "true")) {\n if (!field.required) return "";\n if (field.type === "checkbox" || field.type === "consent") return say("requiredCheck");\n return say(field.type === "select" || field.type === "radio" || field.type === "checkboxes" ? "requiredChoice" : "required");\n }\n switch (field.type) {\n case "email": {\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(text)) return say("email");\n const domain = text.split("@").pop()?.toLowerCase() ?? "";\n\n if (rules.businessEmailOnly && freeDomains.includes(domain)) return say("businessEmail", { domain });\n break;\n }\n case "url":\n try {\n if (!/^https?:$/.test(new URL(text).protocol)) return say("url");\n } catch {\n return say("url");\n }\n break;\n case "tel":\n if (!/^[+()\\d\\s./-]+$/.test(text) || text.replace(/\\D/g, "").length < 5) return say("tel");\n break;\n case "number": {\n const number = Number(text);\n\n if (!Number.isFinite(number) || text.trim() === "") return say("number");\n if (rules.min !== undefined && number < rules.min) return say("min", { min: rules.min });\n if (rules.max !== undefined && number > rules.max) return say("max", { max: rules.max });\n break;\n }\n case "date":\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(text) || Number.isNaN(Date.parse(text))) return say("date");\n break;\n case "select":\n case "radio":\n case "checkboxes":\n if (field.options && !list.every((item) => field.options?.some((option) => option.value === item))) return say("requiredChoice");\n break;\n }\n if (field.type !== "checkboxes" && field.type !== "number") {\n if (rules.minLength !== undefined && text.length < rules.minLength) return say("minLength", { min: rules.minLength });\n if (rules.maxLength !== undefined && text.length > rules.maxLength) return say("maxLength", { max: rules.maxLength });\n }\n if (rules.pattern) {\n try {\n if (!new RegExp(`^(?:${rules.pattern})$`, "u").test(text)) return say("pattern");\n } catch {\n return "";\n }\n }\n return "";\n}\n', "forms/messages.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162973
|
+
`, "forms/free-email-domains.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Free mailbox providers, for `validation.businessEmailOnly`: an address at\n// one of these domains is refused as "not a work address". The list is kept\n// short on purpose \u2014 the providers with the most personal mailboxes\n// worldwide, and their best-known country variants \u2014 so it stays a few\n// hundred bytes in the page. It is a courtesy check in the browser, not a\n// guarantee: anyone determined can type another address. Sites that need\n// more add domains with `forms.freeEmailDomains` in the integration options.\nexport const FREE_EMAIL_DOMAINS = [\n "gmail.com",\n "googlemail.com",\n "outlook.com",\n "hotmail.com",\n "hotmail.co.uk",\n "hotmail.fr",\n "live.com",\n "msn.com",\n "yahoo.com",\n "yahoo.co.uk",\n "yahoo.co.jp",\n "yahoo.fr",\n "ymail.com",\n "rocketmail.com",\n "aol.com",\n "icloud.com",\n "me.com",\n "mac.com",\n "proton.me",\n "protonmail.com",\n "pm.me",\n "gmx.com",\n "gmx.de",\n "gmx.net",\n "web.de",\n "mail.com",\n "zoho.com",\n "yandex.com",\n "yandex.ru",\n "mail.ru",\n "qq.com",\n "163.com",\n "126.com",\n "naver.com",\n "hanmail.net",\n "libero.it",\n "orange.fr",\n "free.fr",\n "laposte.net",\n "t-online.de",\n "btinternet.com",\n "comcast.net",\n "verizon.net",\n "att.net",\n "fastmail.com",\n "hey.com",\n "tutanota.com",\n "tuta.io",\n "rediffmail.com",\n "uol.com.br",\n "bol.com.br",\n];\n', "forms/logic.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The rules of a form that don\'t need a page: which fields are showing,\n// whether an answer is acceptable, which destinations get the submission and\n// what each one is sent. Shared by the browser runtime and the tests.\n\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n/** @typedef {{ [fieldId: string]: string | string[] }} Values */\n/** @typedef {{ field: FormField; name: string; value: string | string[] }} PayloadItem */\n\nexport const LAYOUT = new Set(["heading", "paragraph"]);\n/** How a ticked box reads in conditions \u2014 "yes", as the capture server stores it and the app\'s builder writes rules. */\nexport const TICKED = "yes";\n\n/**\n * An answer as conditions see it. A box the browser holds as "true" is "yes"\n * (and an unticked one is no answer), so `showWhen` / `when` rules behave in\n * the page exactly as on the server.\n *\n * @param {FormField | undefined} field\n * @param {string | string[] | undefined} value\n */\nexport function conditionValue(field, value) {\n if (field && (field.type === "checkbox" || field.type === "consent")) return value === "true" || value === TICKED ? TICKED : "";\n return value;\n}\n\n/**\n * Destinations the Galley server forwards to after capture (`settings.serverSide: true`):\n * never sent from the page, and never written into it.\n *\n * @param {FormDestination} destination\n */\nexport const isServerSide = (destination) => destination.provider !== "galley" && destination.settings?.serverSide === true;\n\n/** @param {string | string[] | undefined} value */\nconst asList = (value) => (Array.isArray(value) ? value : value === undefined || value === "" ? [] : [value]);\n\n/**\n * Whether one condition holds for the current answers.\n *\n * @param {{ equals?: string; notEquals?: string; in?: string[] }} rule\n * @param {string | string[] | undefined} value\n */\nexport function holds(rule, value) {\n const list = Array.isArray(value) ? value : [value ?? ""];\n\n if (rule.equals === undefined && rule.notEquals === undefined && rule.in === undefined) return asList(value).length > 0;\n if (rule.equals !== undefined && !list.includes(rule.equals)) return false;\n if (rule.notEquals !== undefined && list.includes(rule.notEquals)) return false;\n if (rule.in !== undefined && !list.some((item) => rule.in?.includes(item))) return false;\n return true;\n}\n\n/**\n * The ids of the fields that are showing. A field whose condition depends on\n * a hidden field is hidden too (a hidden field has no answer).\n *\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {Set<string>}\n */\nexport function shownFields(fields, values) {\n const byId = new Map(fields.map((field) => [field.id, field]));\n /** @type {Map<string, boolean>} */\n const memo = new Map();\n /** @param {string} id @param {Set<string>} seen @returns {boolean} */\n const shown = (id, seen) => {\n const known = memo.get(id);\n\n if (known !== undefined) return known;\n const field = byId.get(id);\n let result = Boolean(field);\n\n if (field?.showWhen) {\n const controller = field.showWhen.field;\n\n result = !seen.has(controller) && shown(controller, new Set([...seen, id])) && holds(field.showWhen, conditionValue(byId.get(controller), values[controller]));\n }\n memo.set(id, result);\n return result;\n };\n\n return new Set(fields.filter((field) => shown(field.id, new Set())).map((field) => field.id));\n}\n\n/**\n * Whether the page sends to this destination: not server-side, and its\n * `when` holds.\n *\n * @param {FormDestination} destination\n * @param {Values} values\n * @param {FormField[]} [fields]\n */\nexport function applies(destination, values, fields = []) {\n if (isServerSide(destination)) return false;\n const when = destination.when;\n\n return !when || holds({ equals: when.equals }, conditionValue(fields.find((field) => field.id === when.field), values[when.field]));\n}\n\n/**\n * What one destination is sent: every showing, non-layout field under its\n * mapped name (else `name`, else `id`), then the destination\'s constants.\n *\n * @param {FormDestination} destination\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {{ values: { [name: string]: string | string[] }; items: PayloadItem[] }}\n */\nexport function payloadFor(destination, fields, values) {\n const shown = shownFields(fields, values);\n /** @type {PayloadItem[]} */\n const items = [];\n /** @type {{ [name: string]: string | string[] }} */\n const out = {};\n\n for (const field of fields) {\n if (LAYOUT.has(field.type) || !shown.has(field.id)) continue;\n let value = values[field.id] ?? "";\n\n if ((field.type === "checkbox" || field.type === "consent") && value === "") value = "false";\n const name = destination.mapping?.[field.id] ?? field.name ?? field.id;\n\n items.push({ field, name, value });\n out[name] = value;\n }\n for (const [name, value] of Object.entries(destination.constants ?? {})) out[name] = value;\n return { values: out, items };\n}\n\n/**\n * The visitor\'s answers with hidden fields left out \u2014 what the form submits.\n *\n * @param {FormField[]} fields\n * @param {Values} values\n * @returns {Values}\n */\nexport function submittedValues(fields, values) {\n const shown = shownFields(fields, values);\n /** @type {Values} */\n const out = {};\n\n for (const field of fields) if (!LAYOUT.has(field.type) && shown.has(field.id)) out[field.id] = values[field.id] ?? "";\n return out;\n}\n\n/** @param {string} template @param {Record<string, string | number>} values */\nconst fill = (template, values) => template.replace(/\\{(\\w+)\\}/g, (whole, key) => (key in values ? String(values[key]) : whole));\n\n/**\n * Why an answer is refused, in the form\'s words \u2014 or "" when it is fine.\n *\n * @param {FormField} field\n * @param {string | string[]} value\n * @param {Record<string, string>} messages\n * @param {string[]} [freeDomains]\n * @returns {string}\n */\nexport function problem(field, value, messages, freeDomains = []) {\n const rules = field.validation ?? {};\n const say = (/** @type {string} */ key, /** @type {Record<string, string | number>} */ vars = {}) => rules.message || fill(messages[key] ?? key, { label: field.label ?? field.id, ...vars });\n const list = asList(value);\n const text = Array.isArray(value) ? value.join(",") : value;\n\n if (LAYOUT.has(field.type) || field.type === "hidden") return "";\n if (list.length === 0 || ((field.type === "checkbox" || field.type === "consent") && text !== "true")) {\n if (!field.required) return "";\n if (field.type === "checkbox" || field.type === "consent") return say("requiredCheck");\n return say(field.type === "select" || field.type === "radio" || field.type === "checkboxes" ? "requiredChoice" : "required");\n }\n switch (field.type) {\n case "email": {\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(text)) return say("email");\n const domain = text.split("@").pop()?.toLowerCase() ?? "";\n\n if (rules.businessEmailOnly && freeDomains.includes(domain)) return say("businessEmail", { domain });\n break;\n }\n case "url":\n try {\n if (!/^https?:$/.test(new URL(text).protocol)) return say("url");\n } catch {\n return say("url");\n }\n break;\n case "tel":\n if (!/^[+()\\d\\s./-]+$/.test(text) || text.replace(/\\D/g, "").length < 5) return say("tel");\n break;\n case "number": {\n const number = Number(text);\n\n if (!Number.isFinite(number) || text.trim() === "") return say("number");\n if (rules.min !== undefined && number < rules.min) return say("min", { min: rules.min });\n if (rules.max !== undefined && number > rules.max) return say("max", { max: rules.max });\n break;\n }\n case "date":\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(text) || Number.isNaN(Date.parse(text))) return say("date");\n break;\n case "select":\n case "radio":\n case "checkboxes":\n if (field.options && !list.every((item) => field.options?.some((option) => option.value === item))) return say("requiredChoice");\n break;\n }\n if (field.type !== "checkboxes" && field.type !== "number") {\n if (rules.minLength !== undefined && text.length < rules.minLength) return say("minLength", { min: rules.minLength });\n if (rules.maxLength !== undefined && text.length > rules.maxLength) return say("maxLength", { max: rules.maxLength });\n }\n if (rules.pattern) {\n try {\n if (!new RegExp(`^(?:${rules.pattern})$`, "u").test(text)) return say("pattern");\n } catch {\n return "";\n }\n }\n return "";\n}\n', "forms/messages.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162646
162974
|
// @ts-check
|
|
162647
162975
|
// Every word the form runtime says on its own, written to brand/voice.md:
|
|
162648
162976
|
// what happened, then what to do; no exclamation marks, no "we".
|
|
@@ -162724,17 +163052,17 @@ export function resolveMessages(...layers) {
|
|
|
162724
163052
|
export function fill(template, values = {}) {
|
|
162725
163053
|
return template.replace(/\\{(\\w+)\\}/g, (whole, key) => (key in values ? String(values[key]) : whole));
|
|
162726
163054
|
}
|
|
162727
|
-
`, "forms/render.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A form definition \u2192 its complete HTML, on the server. Everything a visitor\n// needs is in the page before any JavaScript runs: labels, inputs with native\n// validation attributes, help, options, every step, consent text, and \u2014 when\n// the first suitable destination accepts a plain form post \u2014 a working\n// `action`. The browser runtime (client/forms.js) then takes over: inline\n// validation, steps, conditions, sending without leaving the page.\n//\n// Pure string building, so it can be tested without Astro and reused by any\n// renderer. Every text from the file is escaped; Markdown is the small\n// inline subset in shared/markdown.js.\n\nimport { escapeHtml as esc, inlineMarkdown as inlineMd, markdownParagraphs as paragraphsMd, withBase } from "../shared/markdown.js";\nimport { isServerSide, LAYOUT } from "./logic.js";\nimport { FREE_EMAIL_DOMAINS } from "./free-email-domains.js";\nimport { fill, resolveMessages } from "./messages.js";\n\n/** @typedef {import("../kit").FormDefinition} FormDefinition */\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n\n/**\n * @typedef {object} RenderOptions\n * @property {string} [endpoint] The site-wide capture endpoint for "galley" destinations.\n * @property {string} [pageUrl] This page\'s absolute address (no-JS returns, `page-url` autofill).\n * @property {Record<string, string>} [messages] Site-wide wording (see messages.js).\n * @property {string} [instance] Suffix that keeps ids unique when one form appears twice on a page.\n * @property {string} [className] Extra classes for the <form>.\n * @property {string} [submitClass] Extra classes for the submit and next buttons (e.g. the site\'s "button").\n * @property {string} [backClass] Extra classes for a multi-step form\'s back button.\n * @property {number} [headingLevel] Level of `heading` fields. Default 3.\n * @property {boolean} [allowFormScripts] Keep `script` actions (see docs/forms.md).\n * @property {boolean} [unstyled]\n * @property {string[]} [freeEmailDomains] Extra free-mailbox domains.\n * @property {string} [base] The site\'s base path ("/docs"): links written from the site root get it.\n */\n\n/**\n * What a build should say about a form, once: `key` is the same for every\n * form the note applies to, so a site with several such forms hears it once\n * per build ("no-endpoint"), or once per form ("script-actions:<id>").\n *\n * @typedef {{ key: string; text: string }} RenderNotice\n */\n\n/** Browser autofill hints, by the field\'s id or name. */\nconst AUTOCOMPLETE = /** @type {Record<string, string>} */ ({\n name: "name",\n full_name: "name",\n fullname: "name",\n "full-name": "name",\n first_name: "given-name",\n firstname: "given-name",\n "first-name": "given-name",\n given_name: "given-name",\n last_name: "family-name",\n lastname: "family-name",\n "last-name": "family-name",\n surname: "family-name",\n family_name: "family-name",\n email: "email",\n work_email: "email",\n "work-email": "email",\n company: "organization",\n organization: "organization",\n organisation: "organization",\n company_name: "organization",\n "company-name": "organization",\n job_title: "organization-title",\n "job-title": "organization-title",\n jobtitle: "organization-title",\n title: "organization-title",\n phone: "tel",\n telephone: "tel",\n mobile: "tel",\n tel: "tel",\n country: "country-name",\n postal_code: "postal-code",\n "postal-code": "postal-code",\n postcode: "postal-code",\n zip: "postal-code",\n city: "address-level2",\n address: "street-address",\n website: "url",\n});\nconst TEXTLIKE = new Set(["text", "email", "tel", "url", "number", "date", "textarea"]);\n\n/**\n * The destination a browser without JavaScript can post to: the first one,\n * in order and without a `when` condition, whose provider accepts a plain\n * form post. HubSpot (JSON API) and Marketo (its own library) do not.\n *\n * @param {FormDestination[]} destinations\n * @param {string} endpoint\n * @returns {{ index: number; action: string; enctype?: string; hidden: Record<string, string> } | null}\n */\nexport function nativeTarget(destinations, endpoint, pageUrl = "", formId = "") {\n for (const [index, destination] of destinations.entries()) {\n if (destination.when || isServerSide(destination)) continue;\n const s = destination.settings;\n const str = (/** @type {string} */ key) => (typeof s[key] === "string" ? /** @type {string} */ (s[key]) : "");\n const sent = pageUrl ? `${pageUrl.split("#")[0]}#galley-sent-${formId}` : "";\n\n switch (destination.provider) {\n case "galley": {\n const url = str("endpoint") || endpoint;\n\n if (url) return { index, action: url, hidden: { _galley_form: formId, ...(sent ? { _galley_return: sent } : {}) } };\n break;\n }\n case "webhook":\n if (str("format") === "form" && str("url")) return { index, action: str("url"), hidden: {} };\n break;\n case "salesforce":\n if (str("orgId")) {\n return {\n index,\n action: "https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",\n hidden: { oid: str("orgId"), ...(str("returnUrl") || sent ? { retURL: str("returnUrl") || sent } : {}) },\n };\n }\n break;\n case "pardot":\n if (str("handlerUrl")) return { index, action: str("handlerUrl"), hidden: {} };\n break;\n case "mailto":\n if (str("to")) {\n const subject = str("subject");\n\n return { index, action: `mailto:${str("to")}${subject ? `?subject=${encodeURIComponent(subject)}` : ""}`, enctype: "text/plain", hidden: {} };\n }\n break;\n }\n }\n return null;\n}\n\n/** @param {Record<string, string | number | boolean | undefined | null>} attrs */\nfunction attributes(attrs) {\n let out = "";\n\n for (const [name, value] of Object.entries(attrs)) {\n if (value === undefined || value === null || value === false) continue;\n out += value === true ? ` ${name}` : ` ${name}="${esc(String(value))}"`;\n }\n return out;\n}\n\n/**\n * @param {FormDefinition} definition\n * @param {string} formId The form\'s id (its file name).\n * @param {RenderOptions} [options]\n */\nexport function renderForm(definition, formId, options = {}) {\n const messages = resolveMessages(options.messages, definition.messages);\n const base = options.base ?? "";\n /** @param {string} text */\n const inlineMarkdown = (text) => inlineMd(text, { base });\n /** @param {string} text */\n const markdownParagraphs = (text) => paragraphsMd(text, { base });\n const uid = `galley-${formId}${options.instance ? `-${options.instance}` : ""}`;\n const steps = Math.max(1, definition.steps?.length ?? 1);\n const appearance = definition.appearance ?? {};\n const labels = appearance.labels ?? "above";\n const endpoint = options.endpoint ?? "";\n const native = nativeTarget(definition.destinations, endpoint, options.pageUrl, formId);\n const nativeDestination = native ? definition.destinations[native.index] : undefined;\n /** @type {RenderNotice[]} */\n const notices = [];\n const headingTag = `h${Math.min(6, Math.max(2, options.headingLevel ?? 3))}`;\n const nameFor = (/** @type {FormField} */ field) => nativeDestination?.mapping?.[field.id] ?? field.name ?? field.id;\n const primary = definition.destinations[0];\n\n if (primary?.provider === "galley" && !(typeof primary.settings.endpoint === "string" && primary.settings.endpoint) && !endpoint) {\n notices.push({\n key: "no-endpoint",\n text: `The form \u201C${formId}\u201D sends to the Galley inbox, but no capture address is set: put the inbox address in forms.endpoint (src/galley/settings.json for a vendored kit, or the integration\'s options), or in the destination\'s settings.endpoint. Galley\'s preview supplies its own address; on the live site the form will say it isn\'t connected yet.`,\n });\n }\n const scriptActions = definition.afterSubmit.filter((action) => action.type === "script");\n\n if (scriptActions.length > 0 && !options.allowFormScripts) {\n notices.push({\n key: `script-actions:${formId}`,\n text: `The form \u201C${formId}\u201D has ${scriptActions.length === 1 ? "a script action" : `${scriptActions.length} script actions`}, which only run when forms.allowFormScripts is true (src/galley/settings.json for a vendored kit, or the integration\'s options). Leaving ${scriptActions.length === 1 ? "it" : "them"} out.`,\n });\n }\n\n /** Initial answers, for working out which conditional fields start hidden. */\n /** @type {Record<string, string>} */\n const initial = {};\n\n for (const field of definition.fields) initial[field.id] = field.defaultValue ?? "";\n\n const describedBy = (/** @type {FormField} */ field, /** @type {string} */ id) => [field.help ? `${id}-help` : "", `${id}-error`].filter(Boolean).join(" ");\n const requiredMark = (/** @type {FormField} */ field) =>\n field.required ? `<span class="galley-form__required" aria-hidden="true">${esc(messages.requiredMark)}</span>` : messages.optional ? ` <span class="galley-form__optional">${esc(messages.optional)}</span>` : "";\n const helpAndError = (/** @type {FormField} */ field, /** @type {string} */ id) =>\n `${field.help ? `<p class="galley-form__help" id="${id}-help">${inlineMarkdown(field.help)}</p>` : ""}<p class="galley-form__error" id="${id}-error" data-galley-error hidden></p>`;\n\n /** @param {FormField} field */\n function control(field) {\n const id = `${uid}-${field.id}`;\n const label = field.label ?? field.id;\n const hiddenLabel = labels === "hidden";\n const floating = labels === "floating" && TEXTLIKE.has(field.type) && field.type !== "date";\n const rules = field.validation ?? {};\n const conditional = Boolean(field.showWhen);\n const common = {\n id,\n name: nameFor(field),\n class: "galley-form__control",\n // A conditional field is only required while it shows; the runtime checks it.\n required: Boolean(field.required) && !conditional,\n "aria-describedby": describedBy(field, id),\n };\n const labelHtml = `<label class="galley-form__label${hiddenLabel ? " galley-visually-hidden" : ""}" for="${id}">${esc(label)}${requiredMark(field)}</label>`;\n\n switch (field.type) {\n case "textarea":\n return {\n id,\n html: `${floating ? "" : labelHtml}<textarea${attributes({\n ...common,\n rows: 5,\n placeholder: floating ? " " : field.placeholder ?? (hiddenLabel ? label : undefined),\n minlength: rules.minLength,\n maxlength: rules.maxLength,\n })}>${esc(field.defaultValue ?? "")}</textarea>${floating ? labelHtml : ""}${helpAndError(field, id)}`,\n };\n case "select": {\n const options = (field.options ?? [])\n .map((option) => `<option${attributes({ value: option.value, selected: field.defaultValue === option.value })}>${esc(option.label)}</option>`)\n .join("");\n\n return {\n id,\n html: `${labelHtml}<select${attributes(common)}><option value=""${field.defaultValue ? "" : " selected"}>${esc(field.placeholder ?? messages.choose)}</option>${options}</select>${helpAndError(field, id)}`,\n };\n }\n case "radio":\n case "checkboxes": {\n const type = field.type === "radio" ? "radio" : "checkbox";\n const chosen = (field.defaultValue ?? "").split(",").map((part) => part.trim());\n const options = (field.options ?? [])\n .map(\n (option, index) =>\n `<div class="galley-form__option"><input${attributes({\n type,\n id: `${id}-${index}`,\n name: nameFor(field),\n value: option.value,\n class: "galley-form__choice",\n checked: chosen.includes(option.value),\n required: type === "radio" && Boolean(field.required) && !conditional,\n })}><label for="${id}-${index}">${esc(option.label)}</label></div>`,\n )\n .join("");\n\n return {\n id,\n group: true,\n html: `<legend class="galley-form__label${hiddenLabel ? " galley-visually-hidden" : ""}" id="${id}-label">${esc(label)}${requiredMark(field)}</legend><div class="galley-form__options">${options}</div>${helpAndError(field, id)}`,\n };\n }\n case "checkbox":\n case "consent": {\n const text = field.type === "consent" ? inlineMarkdown(field.text ?? label) : esc(label);\n\n return {\n id,\n check: true,\n html: `<input${attributes({ ...common, type: "checkbox", value: "true", class: "galley-form__choice", checked: field.defaultValue === "true" })}><label class="galley-form__label" for="${id}">${text}${requiredMark(field)}</label>${helpAndError(field, id)}`,\n };\n }\n default: {\n const type = field.type === "text" ? "text" : field.type;\n const key = (field.name ?? field.id).toLowerCase();\n const autocomplete = AUTOCOMPLETE[key] ?? AUTOCOMPLETE[field.id] ?? (type === "email" ? "email" : type === "tel" ? "tel" : type === "url" ? "url" : undefined);\n const value = field.autofill?.from === "page-url" && options.pageUrl ? options.pageUrl : field.defaultValue;\n const input = `<input${attributes({\n ...common,\n type,\n value,\n autocomplete,\n inputmode: type === "number" ? "decimal" : undefined,\n placeholder: floating ? " " : field.placeholder ?? (hiddenLabel ? label : undefined),\n minlength: rules.minLength,\n maxlength: rules.maxLength,\n min: rules.min,\n max: rules.max,\n pattern: rules.pattern,\n })}>`;\n\n return { id, html: floating ? `${input}${labelHtml}${helpAndError(field, id)}` : `${labelHtml}${input}${helpAndError(field, id)}` };\n }\n }\n }\n\n /** @param {FormField} field */\n function fieldHtml(field) {\n const base = { "data-galley-field": field.id, "data-type": field.type, "data-width": field.width === "half" ? "half" : undefined };\n const hiddenAtStart = field.showWhen ? !conditionHolds(field, initial) : false;\n const when = { "data-galley-when": Boolean(field.showWhen), "data-galley-hidden": hiddenAtStart };\n\n if (field.type === "hidden") {\n const value = field.autofill?.from === "page-url" && options.pageUrl ? options.pageUrl : field.defaultValue ?? "";\n\n return `<input${attributes({ type: "hidden", id: `${uid}-${field.id}`, name: nameFor(field), value, "data-galley-field": field.id, "data-type": "hidden" })}>`;\n }\n if (field.type === "heading") {\n return `<div${attributes({ class: "galley-form__field galley-form__layout", ...base, ...when })}><${headingTag} class="galley-form__heading">${inlineMarkdown(field.text ?? field.label ?? "")}</${headingTag}></div>`;\n }\n if (field.type === "paragraph") {\n return `<div${attributes({ class: "galley-form__field galley-form__layout", ...base, ...when })}><div class="galley-form__text">${markdownParagraphs(field.text ?? field.label ?? "")}</div></div>`;\n }\n const built = control(field);\n\n if (built.group) {\n return `<fieldset${attributes({ class: "galley-form__field galley-form__group", ...base, ...when, "aria-describedby": describedBy(field, built.id) })}>${built.html}</fieldset>`;\n }\n return `<div${attributes({ class: `galley-form__field${built.check ? " galley-form__check" : ""}`, ...base, ...when, "data-floating": labels === "floating" && TEXTLIKE.has(field.type) && field.type !== "date" })}>${built.html}</div>`;\n }\n\n /** Whether a conditional field shows for the initial answers (one level is enough here). */\n function conditionHolds(/** @type {FormField} */ field, /** @type {Record<string, string>} */ values) {\n const rule = field.showWhen;\n\n if (!rule) return true;\n const value = values[rule.field] ?? "";\n\n if (rule.equals !== undefined) return value === rule.equals;\n if (rule.notEquals !== undefined) return value !== rule.notEquals;\n if (rule.in !== undefined) return rule.in.includes(value);\n return value !== "";\n }\n\n // \u2500\u2500 The form \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const stepOf = (/** @type {FormField} */ field) => Math.min(steps - 1, field.step ?? 0);\n let body = "";\n\n if (steps > 1) {\n body += `<p class="galley-form__progress" data-galley-progress hidden>${esc(fill(messages.step, { step: 1, total: steps }))}</p>`;\n for (let step = 0; step < steps; step += 1) {\n const title = definition.steps?.[step]?.title;\n const fields = definition.fields.filter((field) => stepOf(field) === step && field.type !== "hidden");\n\n body += `<fieldset class="galley-form__step" data-galley-step="${step}"${title ? "" : ` aria-label="${esc(fill(messages.step, { step: step + 1, total: steps }))}"`}>${\n title ? `<legend class="galley-form__step-title" tabindex="-1">${esc(title)}</legend>` : ""\n }<div class="galley-form__fields">${fields.map(fieldHtml).join("")}</div></fieldset>`;\n }\n } else {\n body += `<div class="galley-form__fields">${definition.fields.filter((field) => field.type !== "hidden").map(fieldHtml).join("")}</div>`;\n }\n\n const hiddenInputs =\n definition.fields\n .filter((field) => field.type === "hidden")\n .map(fieldHtml)\n .join("") +\n Object.entries({ ...(native?.hidden ?? {}), ...(nativeDestination?.constants ?? {}) })\n .map(([name, value]) => `<input type="hidden"${attributes({ name, value })}>`)\n .join("");\n const honeypot =\n definition.spam?.honeypot === false\n ? ""\n : `<div class="galley-form__hp" aria-hidden="true"><label for="${uid}-hp">${esc(messages.honeypotLabel)}</label><input type="text" id="${uid}-hp" name="_galley_hp" tabindex="-1" autocomplete="off" data-galley-hp></div>`;\n const turnstile = definition.spam?.turnstileSiteKey ? `<div class="cf-turnstile galley-form__turnstile"${attributes({ "data-sitekey": definition.spam.turnstileSiteKey })}></div>` : "";\n const nav =\n steps > 1\n ? `<button type="button" class="galley-form__back${options.backClass ? ` ${esc(options.backClass)}` : ""}" data-galley-back hidden>${esc(messages.back)}</button><button type="button" class="galley-form__next${options.submitClass ? ` ${esc(options.submitClass)}` : ""}" data-galley-next hidden>${esc(definition.steps?.[0]?.nextLabel ?? messages.next)}</button>`\n : "";\n const submit = `<button type="submit" class="galley-form__submit${options.submitClass ? ` ${esc(options.submitClass)}` : ""}" data-galley-submit>${esc(definition.submitLabel)}</button>`;\n const formAttrs = attributes({\n id: uid,\n class: `galley-form__form${options.className ? ` ${options.className}` : ""}`,\n action: native?.action,\n method: native ? "post" : undefined,\n enctype: native?.enctype,\n "accept-charset": native ? "UTF-8" : undefined,\n "aria-label": definition.name,\n "aria-describedby": definition.description ? `${uid}-description` : undefined,\n "data-galley-requires-js": !native,\n });\n\n const start =\n `<div${attributes({\n class: "galley-form",\n "data-galley-form": formId,\n "data-layout": appearance.layout ?? "stacked",\n "data-size": appearance.size ?? "regular",\n "data-labels": labels,\n "data-steps": steps > 1 ? steps : undefined,\n "data-state": "idle",\n "data-galley-unstyled": Boolean(options.unstyled),\n })}>` +\n `<form${formAttrs}>` +\n (definition.description ? `<p class="galley-form__description" id="${uid}-description">${inlineMarkdown(definition.description)}</p>` : "") +\n `<div class="galley-form__summary" id="${uid}-summary" tabindex="-1" role="group" aria-labelledby="${uid}-summary-title" hidden><p class="galley-form__summary-title" id="${uid}-summary-title"></p><ul class="galley-form__summary-list"></ul></div>`;\n const middle = hiddenInputs + honeypot + body + turnstile;\n const actionsStart = `<div class="galley-form__actions">${nav}`;\n const actionsEnd =\n `</div><p class="galley-form__status" id="${uid}-status" role="status" data-galley-status></p>` +\n (native ? "" : `<noscript><p class="galley-form__noscript">${esc(messages.noScript)}</p></noscript>`);\n const formEnd = "</form>";\n\n // \u2500\u2500 After a successful submission \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const message = /** @type {{ type: "message"; title?: string; text: string } | undefined} */ (definition.afterSubmit.find((action) => action.type === "message"));\n const downloads = definition.afterSubmit.filter((action) => action.type === "download");\n const mailtoPrimary = primary?.provider === "mailto";\n const successDefault =\n (message\n ? `${message.title ? `<p class="galley-form__success-title">${inlineMarkdown(message.title)}</p>` : ""}<div class="galley-form__success-text">${markdownParagraphs(message.text)}</div>`\n : `<p class="galley-form__success-title">${esc(messages.thanksTitle)}</p><div class="galley-form__success-text"><p>${esc(mailtoPrimary ? messages.mailtoText : messages.thanksText)}</p></div>`) +\n downloads\n .map((action) => (action.type === "download" ? `<p class="galley-form__download"><a href="${esc(withBase(action.url, base))}" download>${esc(action.label ?? messages.download)}</a></p>` : ""))\n .join("");\n const successStart = `<div class="galley-form__success" id="galley-sent-${formId}${options.instance ? `-${options.instance}` : ""}" tabindex="-1" data-galley-success hidden>`;\n const successEnd = "</div>";\n\n // \u2500\u2500 What the runtime needs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const config = {\n id: formId,\n uid,\n endpoint,\n fields: definition.fields\n .filter((field) => !LAYOUT.has(field.type) || field.showWhen)\n .map((field) => {\n /** @type {Record<string, unknown>} */\n const out = { id: field.id, type: field.type };\n\n // A consent field\'s text travels too: providers that record consent (HubSpot) send it.\n if (field.type === "consent") out.text = field.text ?? field.label ?? "";\n for (const key of /** @type {const} */ (["label", "name", "required", "validation", "showWhen", "autofill", "step", "options"])) {\n const value = field[key];\n\n if (value === undefined) continue;\n out[key] = key === "options" ? field.options?.map((option) => ({ value: option.value, label: option.label })) : value;\n }\n return out;\n }),\n steps,\n nextLabels: definition.steps?.map((step) => step.nextLabel ?? messages.next),\n // Server-side destinations are the capture server\'s to forward: their addresses stay out of the page.\n destinations: definition.destinations.filter((destination) => !isServerSide(destination)),\n // A redirect written from the site root ("/thanks/") goes to the page under the base path.\n afterSubmit: definition.afterSubmit.filter((action) => action.type !== "script" || options.allowFormScripts).map((action) => (action.type === "redirect" ? { ...action, url: withBase(action.url, base) } : action)),\n spam: { honeypot: definition.spam?.honeypot !== false, minSeconds: definition.spam?.minSeconds ?? 0, turnstile: Boolean(definition.spam?.turnstileSiteKey) },\n native: native?.index ?? -1,\n messages: {\n ...pick(messages, ["required", "requiredChoice", "requiredCheck", "email", "businessEmail", "url", "tel", "number", "date", "min", "max", "minLength", "maxLength", "pattern"]),\n ...pick(messages, ["summaryOne", "summaryMany", "sending", "sent", "rateLimited", "rateLimitedFor", "rateLimitedForOne", "tooFast", "notConnected", "step"]),\n error: definition.errorMessage ?? messages.error,\n },\n // The free-mailbox list travels only with forms that refuse personal addresses.\n freeEmailDomains: definition.fields.some((field) => field.validation?.businessEmailOnly) ? [...FREE_EMAIL_DOMAINS, ...(options.freeEmailDomains ?? [])] : [],\n name: definition.name,\n };\n const configHtml = `<script type="application/json" data-galley-form-config>${JSON.stringify(config).replace(/</g, "\\\\u003c")}</script>`;\n const end = `${successEnd}${configHtml}</div>`;\n\n return { start, middle, actionsStart, submit, actionsEnd, formEnd, successStart, successDefault, end, warnings: notices.map((notice) => notice.text), notices, config, uid };\n}\n\n/**\n * @template {Record<string, string>} T\n * @param {T} source\n * @param {(keyof T)[]} keys\n */\nfunction pick(source, keys) {\n /** @type {Partial<T>} */\n const out = {};\n\n for (const key of keys) out[key] = source[key];\n return out;\n}\n\n/**\n * The whole form as one string (no slots) \u2014 for tests and non-Astro use.\n *\n * @param {FormDefinition} definition\n * @param {string} formId\n * @param {RenderOptions} [options]\n */\nexport function renderFormHtml(definition, formId, options) {\n const parts = renderForm(definition, formId, options);\n\n return parts.start + parts.middle + parts.actionsStart + parts.submit + parts.actionsEnd + parts.formEnd + parts.successStart + parts.successDefault + parts.end;\n}\n', "mailto/config.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Settings, wording and styles of the email-link dialog (docs/mailto.md).\nimport { MAILTO_RUNTIME } from "./runtime.gen.js";\n\n/** The actions, in their default order. "outlook-live" (Outlook.com\'s own address) is available but not offered by default. */\nexport const MAILTO_OPTIONS = /** @type {const} */ (["gmail", "outlook", "app", "copy"]);\nexport const MAILTO_KNOWN = new Set([...MAILTO_OPTIONS, "outlook-live"]);\n\n/** Every word the dialog says, per brand/voice.md. `{address}` is the link\'s address. */\nexport const MAILTO_STRINGS = Object.freeze({\n label: "Email {address}",\n labelNoAddress: "Write an email",\n gmail: "Send with Gmail",\n outlook: "Send with Outlook",\n "outlook-live": "Send with Outlook.com",\n app: "Open my mail app",\n copy: "Copy address",\n copied: "Copied",\n copyFailed: "Couldn\'t copy. Select the address above instead.",\n close: "Close",\n});\n\n/*\n * Custom properties (with system fallbacks):\n * --galley-mailto-bg --galley-mailto-text --galley-mailto-border\n * --galley-mailto-radius --galley-mailto-shadow --galley-mailto-hover\n * --galley-field-focus (focus ring)\n * No animation, so nothing moves for anyone (reduced motion included).\n */\nexport const MAILTO_CSS =\n ".galley-mailto{position:fixed;z-index:2147483001;box-sizing:border-box;min-width:14rem;max-width:22rem;padding:.5rem;border:1px solid var(--galley-mailto-border,#8886);border-radius:var(--galley-mailto-radius,.5rem);background:var(--galley-mailto-bg,Canvas);color:var(--galley-mailto-text,CanvasText);box-shadow:var(--galley-mailto-shadow,0 8px 28px #0003);font:inherit;font-size:.9375rem;line-height:1.4}" +\n ".galley-mailto[data-sheet]{inset:auto 0 0;max-width:none;padding:1rem}" +\n ".galley-mailto p{margin:.25rem 2.25rem .5rem .5rem}.galley-mailto__address{font-weight:600;user-select:all;overflow-wrap:anywhere}" +\n ".galley-mailto ul{margin:0;padding:0;list-style:none}" +\n ".galley-mailto__option{display:block;box-sizing:border-box;width:100%;padding:.5rem;border:0;border-radius:.25rem;background:none;color:inherit;font:inherit;text-align:start;text-decoration:none;cursor:pointer}" +\n ".galley-mailto__option:hover,.galley-mailto__option:focus-visible{background:var(--galley-mailto-hover,#8882)}" +\n ".galley-mailto :focus-visible{outline:2px solid var(--galley-field-focus,Highlight)}" +\n ".galley-mailto__status:empty{display:none}" +\n ".galley-mailto__close{position:absolute;top:.25rem;right:.25rem;width:2rem;height:2rem;border:0;background:none;color:inherit;font:inherit;font-size:1.25rem;cursor:pointer}";\n\n/**\n * @typedef {object} MailtoOptions\n * @property {string[]} [options] Which actions, in which order: "gmail", "outlook", "outlook-live", "app", "copy".\n * @property {Record<string, string>} [strings] Wording, by key (MAILTO_STRINGS).\n */\n\n/**\n * The dialog\'s settings with defaults, or null when it is off.\n *\n * @param {MailtoOptions | boolean | undefined} given\n * @returns {{ options: string[]; strings: Record<string, string> } | null}\n */\nexport function resolveMailto(given) {\n if (given === false) return null;\n const settings = typeof given === "object" && given ? given : {};\n const options = (settings.options ?? [...MAILTO_OPTIONS]).filter((option) => MAILTO_KNOWN.has(/** @type {any} */ (option)));\n\n if (settings.options && options.length !== settings.options.length) {\n throw new Error(`mailto.options can only list ${[...MAILTO_KNOWN].map((option) => `"${option}"`).join(", ")}.`);\n }\n return { options, strings: { ...MAILTO_STRINGS, ...(settings.strings ?? {}) } };\n}\n\n/** The inline script\'s text \u2014 the same on every page of a site (one CSP hash). */\nexport function mailtoScript(/** @type {{ options: string[]; strings: Record<string, string> }} */ config) {\n return `(${MAILTO_RUNTIME})(${JSON.stringify({ ...config, css: MAILTO_CSS }).replace(/</g, "\\\\u003c")})`;\n}\n\n/** The <script> element, with the marker that keeps it from being added twice. */\nexport function mailtoTag(/** @type {{ options: string[]; strings: Record<string, string> }} */ config) {\n return `<script data-galley-mailto-script>${mailtoScript(config)}</script>`;\n}\n\n/** Whether a page has an email link worth enhancing. */\nexport const HAS_MAILTO = /<a\\b[^>]*\\bhref\\s*=\\s*["\']?mailto:/i;\n', "mailto/runtime.gen.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163055
|
+
`, "forms/render.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A form definition \u2192 its complete HTML, on the server. Everything a visitor\n// needs is in the page before any JavaScript runs: labels, inputs with native\n// validation attributes, help, options, every step, consent text, and \u2014 when\n// the first suitable destination accepts a plain form post \u2014 a working\n// `action`. The browser runtime (client/forms.js) then takes over: inline\n// validation, steps, conditions, sending without leaving the page.\n//\n// Pure string building, so it can be tested without Astro and reused by any\n// renderer. Every text from the file is escaped; Markdown is the small\n// inline subset in shared/markdown.js.\n\nimport { escapeHtml as esc, inlineMarkdown as inlineMd, markdownParagraphs as paragraphsMd, withBase } from "../shared/markdown.js";\nimport { isServerSide, LAYOUT } from "./logic.js";\nimport { FREE_EMAIL_DOMAINS } from "./free-email-domains.js";\nimport { fill, resolveMessages } from "./messages.js";\n\n/** @typedef {import("../kit").FormDefinition} FormDefinition */\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n\n/**\n * @typedef {object} RenderOptions\n * @property {string} [endpoint] The site-wide capture endpoint for "galley" destinations.\n * @property {string} [pageUrl] This page\'s absolute address (no-JS returns, `page-url` autofill).\n * @property {Record<string, string>} [messages] Site-wide wording (see messages.js).\n * @property {string} [instance] Suffix that keeps ids unique when one form appears twice on a page.\n * @property {string} [className] Extra classes for the <form>.\n * @property {string} [submitClass] Extra classes for the submit and next buttons (e.g. the site\'s "button").\n * @property {string} [backClass] Extra classes for a multi-step form\'s back button.\n * @property {number} [headingLevel] Level of `heading` fields. Default 3.\n * @property {boolean} [allowFormScripts] Keep `script` actions (see docs/forms.md).\n * @property {boolean} [unstyled]\n * @property {string[]} [freeEmailDomains] Extra free-mailbox domains.\n * @property {string} [base] The site\'s base path ("/docs"): links written from the site root get it.\n */\n\n/**\n * What a build should say about a form, once: `key` is the same for every\n * form the note applies to, so a site with several such forms hears it once\n * per build ("no-endpoint"), or once per form ("script-actions:<id>").\n *\n * @typedef {{ key: string; text: string }} RenderNotice\n */\n\n/** Browser autofill hints, by the field\'s id or name. */\nconst AUTOCOMPLETE = /** @type {Record<string, string>} */ ({\n name: "name",\n full_name: "name",\n fullname: "name",\n "full-name": "name",\n first_name: "given-name",\n firstname: "given-name",\n "first-name": "given-name",\n given_name: "given-name",\n last_name: "family-name",\n lastname: "family-name",\n "last-name": "family-name",\n surname: "family-name",\n family_name: "family-name",\n email: "email",\n work_email: "email",\n "work-email": "email",\n company: "organization",\n organization: "organization",\n organisation: "organization",\n company_name: "organization",\n "company-name": "organization",\n job_title: "organization-title",\n "job-title": "organization-title",\n jobtitle: "organization-title",\n title: "organization-title",\n phone: "tel",\n telephone: "tel",\n mobile: "tel",\n tel: "tel",\n country: "country-name",\n postal_code: "postal-code",\n "postal-code": "postal-code",\n postcode: "postal-code",\n zip: "postal-code",\n city: "address-level2",\n address: "street-address",\n website: "url",\n});\nconst TEXTLIKE = new Set(["text", "email", "tel", "url", "number", "date", "textarea"]);\n\n/**\n * The destination a browser without JavaScript can post to: the first one,\n * in order and without a `when` condition, whose provider accepts a plain\n * form post. HubSpot (JSON API) and Marketo (its own library) do not.\n *\n * @param {FormDestination[]} destinations\n * @param {string} endpoint\n * @returns {{ index: number; action: string; enctype?: string; hidden: Record<string, string> } | null}\n */\nexport function nativeTarget(destinations, endpoint, pageUrl = "", formId = "") {\n for (const [index, destination] of destinations.entries()) {\n if (destination.when || isServerSide(destination)) continue;\n const s = destination.settings;\n const str = (/** @type {string} */ key) => (typeof s[key] === "string" ? /** @type {string} */ (s[key]) : "");\n const sent = pageUrl ? `${pageUrl.split("#")[0]}#galley-sent-${formId}` : "";\n\n switch (destination.provider) {\n case "galley": {\n const url = str("endpoint") || endpoint;\n\n if (url) return { index, action: url, hidden: { _galley_form: formId, ...(sent ? { _galley_return: sent } : {}) } };\n break;\n }\n case "webhook":\n if (str("format") === "form" && str("url")) return { index, action: str("url"), hidden: {} };\n break;\n case "salesforce":\n if (str("orgId")) {\n return {\n index,\n action: "https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",\n hidden: { oid: str("orgId"), ...(str("returnUrl") || sent ? { retURL: str("returnUrl") || sent } : {}) },\n };\n }\n break;\n case "pardot":\n if (str("handlerUrl")) return { index, action: str("handlerUrl"), hidden: {} };\n break;\n case "mailto":\n if (str("to")) {\n const subject = str("subject");\n\n return { index, action: `mailto:${str("to")}${subject ? `?subject=${encodeURIComponent(subject)}` : ""}`, enctype: "text/plain", hidden: {} };\n }\n break;\n }\n }\n return null;\n}\n\n/** @param {Record<string, string | number | boolean | undefined | null>} attrs */\nfunction attributes(attrs) {\n let out = "";\n\n for (const [name, value] of Object.entries(attrs)) {\n if (value === undefined || value === null || value === false) continue;\n out += value === true ? ` ${name}` : ` ${name}="${esc(String(value))}"`;\n }\n return out;\n}\n\n/**\n * @param {FormDefinition} definition\n * @param {string} formId The form\'s id (its file name).\n * @param {RenderOptions} [options]\n */\nexport function renderForm(definition, formId, options = {}) {\n const messages = resolveMessages(options.messages, definition.messages);\n const base = options.base ?? "";\n /** @param {string} text */\n const inlineMarkdown = (text) => inlineMd(text, { base });\n /** @param {string} text */\n const markdownParagraphs = (text) => paragraphsMd(text, { base });\n const uid = `galley-${formId}${options.instance ? `-${options.instance}` : ""}`;\n const steps = Math.max(1, definition.steps?.length ?? 1);\n const appearance = definition.appearance ?? {};\n const labels = appearance.labels ?? "above";\n const endpoint = options.endpoint ?? "";\n const native = nativeTarget(definition.destinations, endpoint, options.pageUrl, formId);\n const nativeDestination = native ? definition.destinations[native.index] : undefined;\n /** @type {RenderNotice[]} */\n const notices = [];\n const headingTag = `h${Math.min(6, Math.max(2, options.headingLevel ?? 3))}`;\n const nameFor = (/** @type {FormField} */ field) => nativeDestination?.mapping?.[field.id] ?? field.name ?? field.id;\n const primary = definition.destinations[0];\n\n if (primary?.provider === "galley" && !(typeof primary.settings.endpoint === "string" && primary.settings.endpoint) && !endpoint) {\n notices.push({\n key: "no-endpoint",\n text: `The form \u201C${formId}\u201D sends to the Galley inbox, but no capture address is set: put the inbox address in forms.endpoint (src/galley/settings.json for a vendored kit, or the integration\'s options), or in the destination\'s settings.endpoint. Galley\'s preview supplies its own address; on the live site the form will say it isn\'t connected yet.`,\n });\n }\n const scriptActions = definition.afterSubmit.filter((action) => action.type === "script");\n\n if (scriptActions.length > 0 && !options.allowFormScripts) {\n notices.push({\n key: `script-actions:${formId}`,\n text: `The form \u201C${formId}\u201D has ${scriptActions.length === 1 ? "a script action" : `${scriptActions.length} script actions`}, which only run when forms.allowFormScripts is true (src/galley/settings.json for a vendored kit, or the integration\'s options). Leaving ${scriptActions.length === 1 ? "it" : "them"} out.`,\n });\n }\n\n /** Initial answers, for working out which conditional fields start hidden. */\n /** @type {Record<string, string>} */\n const initial = {};\n\n for (const field of definition.fields) initial[field.id] = field.defaultValue ?? "";\n\n const describedBy = (/** @type {FormField} */ field, /** @type {string} */ id) => [field.help ? `${id}-help` : "", `${id}-error`].filter(Boolean).join(" ");\n const requiredMark = (/** @type {FormField} */ field) =>\n field.required ? `<span class="galley-form__required" aria-hidden="true">${esc(messages.requiredMark)}</span>` : messages.optional ? ` <span class="galley-form__optional">${esc(messages.optional)}</span>` : "";\n const helpAndError = (/** @type {FormField} */ field, /** @type {string} */ id) =>\n `${field.help ? `<p class="galley-form__help" id="${id}-help">${inlineMarkdown(field.help)}</p>` : ""}<p class="galley-form__error" id="${id}-error" data-galley-error hidden></p>`;\n\n /** @param {FormField} field */\n function control(field) {\n const id = `${uid}-${field.id}`;\n const label = field.label ?? field.id;\n const hiddenLabel = labels === "hidden";\n const floating = labels === "floating" && TEXTLIKE.has(field.type) && field.type !== "date";\n const rules = field.validation ?? {};\n const conditional = Boolean(field.showWhen);\n const common = {\n id,\n name: nameFor(field),\n class: "galley-form__control",\n // A conditional field is only required while it shows; the runtime checks it.\n required: Boolean(field.required) && !conditional,\n "aria-describedby": describedBy(field, id),\n };\n const labelHtml = `<label class="galley-form__label${hiddenLabel ? " galley-visually-hidden" : ""}" for="${id}">${esc(label)}${requiredMark(field)}</label>`;\n\n switch (field.type) {\n case "textarea":\n return {\n id,\n html: `${floating ? "" : labelHtml}<textarea${attributes({\n ...common,\n rows: 5,\n placeholder: floating ? " " : field.placeholder ?? (hiddenLabel ? label : undefined),\n minlength: rules.minLength,\n maxlength: rules.maxLength,\n })}>${esc(field.defaultValue ?? "")}</textarea>${floating ? labelHtml : ""}${helpAndError(field, id)}`,\n };\n case "select": {\n const options = (field.options ?? [])\n .map((option) => `<option${attributes({ value: option.value, selected: field.defaultValue === option.value })}>${esc(option.label)}</option>`)\n .join("");\n\n return {\n id,\n html: `${labelHtml}<select${attributes(common)}><option value=""${field.defaultValue ? "" : " selected"}>${esc(field.placeholder ?? messages.choose)}</option>${options}</select>${helpAndError(field, id)}`,\n };\n }\n case "radio":\n case "checkboxes": {\n const type = field.type === "radio" ? "radio" : "checkbox";\n const chosen = (field.defaultValue ?? "").split(",").map((part) => part.trim());\n const options = (field.options ?? [])\n .map(\n (option, index) =>\n `<div class="galley-form__option"><input${attributes({\n type,\n id: `${id}-${index}`,\n name: nameFor(field),\n value: option.value,\n class: "galley-form__choice",\n checked: chosen.includes(option.value),\n required: type === "radio" && Boolean(field.required) && !conditional,\n })}><label for="${id}-${index}">${esc(option.label)}</label></div>`,\n )\n .join("");\n\n return {\n id,\n group: true,\n html: `<legend class="galley-form__label${hiddenLabel ? " galley-visually-hidden" : ""}" id="${id}-label">${esc(label)}${requiredMark(field)}</legend><div class="galley-form__options">${options}</div>${helpAndError(field, id)}`,\n };\n }\n case "checkbox":\n case "consent": {\n const text = field.type === "consent" ? inlineMarkdown(field.text ?? label) : esc(label);\n\n return {\n id,\n check: true,\n html: `<input${attributes({ ...common, type: "checkbox", value: "true", class: "galley-form__choice", checked: field.defaultValue === "true" })}><label class="galley-form__label" for="${id}">${text}${requiredMark(field)}</label>${helpAndError(field, id)}`,\n };\n }\n default: {\n const type = field.type === "text" ? "text" : field.type;\n const key = (field.name ?? field.id).toLowerCase();\n const autocomplete = AUTOCOMPLETE[key] ?? AUTOCOMPLETE[field.id] ?? (type === "email" ? "email" : type === "tel" ? "tel" : type === "url" ? "url" : undefined);\n const value = field.autofill?.from === "page-url" && options.pageUrl ? options.pageUrl : field.defaultValue;\n const input = `<input${attributes({\n ...common,\n type,\n value,\n autocomplete,\n inputmode: type === "number" ? "decimal" : undefined,\n placeholder: floating ? " " : field.placeholder ?? (hiddenLabel ? label : undefined),\n minlength: rules.minLength,\n maxlength: rules.maxLength,\n min: rules.min,\n max: rules.max,\n pattern: rules.pattern,\n })}>`;\n\n return { id, html: floating ? `${input}${labelHtml}${helpAndError(field, id)}` : `${labelHtml}${input}${helpAndError(field, id)}` };\n }\n }\n }\n\n /** @param {FormField} field */\n function fieldHtml(field) {\n const base = { "data-galley-field": field.id, "data-type": field.type, "data-width": field.width === "half" ? "half" : undefined };\n const hiddenAtStart = field.showWhen ? !conditionHolds(field, initial) : false;\n const when = { "data-galley-when": Boolean(field.showWhen), "data-galley-hidden": hiddenAtStart };\n\n if (field.type === "hidden") {\n const value = field.autofill?.from === "page-url" && options.pageUrl ? options.pageUrl : field.defaultValue ?? "";\n\n return `<input${attributes({ type: "hidden", id: `${uid}-${field.id}`, name: nameFor(field), value, "data-galley-field": field.id, "data-type": "hidden" })}>`;\n }\n if (field.type === "heading") {\n return `<div${attributes({ class: "galley-form__field galley-form__layout", ...base, ...when })}><${headingTag} class="galley-form__heading">${inlineMarkdown(field.text ?? field.label ?? "")}</${headingTag}></div>`;\n }\n if (field.type === "paragraph") {\n return `<div${attributes({ class: "galley-form__field galley-form__layout", ...base, ...when })}><div class="galley-form__text">${markdownParagraphs(field.text ?? field.label ?? "")}</div></div>`;\n }\n const built = control(field);\n\n if (built.group) {\n return `<fieldset${attributes({ class: "galley-form__field galley-form__group", ...base, ...when, "aria-describedby": describedBy(field, built.id) })}>${built.html}</fieldset>`;\n }\n return `<div${attributes({ class: `galley-form__field${built.check ? " galley-form__check" : ""}`, ...base, ...when, "data-floating": labels === "floating" && TEXTLIKE.has(field.type) && field.type !== "date" })}>${built.html}</div>`;\n }\n\n /** Whether a conditional field shows for the initial answers (one level is enough here). */\n function conditionHolds(/** @type {FormField} */ field, /** @type {Record<string, string>} */ values) {\n const rule = field.showWhen;\n\n if (!rule) return true;\n const value = values[rule.field] ?? "";\n\n if (rule.equals !== undefined) return value === rule.equals;\n if (rule.notEquals !== undefined) return value !== rule.notEquals;\n if (rule.in !== undefined) return rule.in.includes(value);\n return value !== "";\n }\n\n // \u2500\u2500 The form \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const stepOf = (/** @type {FormField} */ field) => Math.min(steps - 1, field.step ?? 0);\n let body = "";\n\n if (steps > 1) {\n body += `<p class="galley-form__progress" data-galley-progress hidden>${esc(fill(messages.step, { step: 1, total: steps }))}</p>`;\n for (let step = 0; step < steps; step += 1) {\n const title = definition.steps?.[step]?.title;\n const fields = definition.fields.filter((field) => stepOf(field) === step && field.type !== "hidden");\n\n body += `<fieldset class="galley-form__step" data-galley-step="${step}"${title ? "" : ` aria-label="${esc(fill(messages.step, { step: step + 1, total: steps }))}"`}>${\n title ? `<legend class="galley-form__step-title" tabindex="-1">${esc(title)}</legend>` : ""\n }<div class="galley-form__fields">${fields.map(fieldHtml).join("")}</div></fieldset>`;\n }\n } else {\n body += `<div class="galley-form__fields">${definition.fields.filter((field) => field.type !== "hidden").map(fieldHtml).join("")}</div>`;\n }\n\n const hiddenInputs =\n definition.fields\n .filter((field) => field.type === "hidden")\n .map(fieldHtml)\n .join("") +\n Object.entries({ ...(native?.hidden ?? {}), ...(nativeDestination?.constants ?? {}) })\n .map(([name, value]) => `<input type="hidden"${attributes({ name, value })}>`)\n .join("");\n const honeypot =\n definition.spam?.honeypot === false\n ? ""\n : `<div class="galley-form__hp" aria-hidden="true"><label for="${uid}-hp">${esc(messages.honeypotLabel)}</label><input type="text" id="${uid}-hp" name="_galley_hp" tabindex="-1" autocomplete="off" data-galley-hp></div>`;\n const turnstile = definition.spam?.turnstileSiteKey ? `<div class="cf-turnstile galley-form__turnstile"${attributes({ "data-sitekey": definition.spam.turnstileSiteKey })}></div>` : "";\n const nav =\n steps > 1\n ? `<button type="button" class="galley-form__back${options.backClass ? ` ${esc(options.backClass)}` : ""}" data-galley-back hidden>${esc(messages.back)}</button><button type="button" class="galley-form__next${options.submitClass ? ` ${esc(options.submitClass)}` : ""}" data-galley-next hidden>${esc(definition.steps?.[0]?.nextLabel ?? messages.next)}</button>`\n : "";\n const submit = `<button type="submit" class="galley-form__submit${options.submitClass ? ` ${esc(options.submitClass)}` : ""}" data-galley-submit>${esc(definition.submitLabel)}</button>`;\n const formAttrs = attributes({\n id: uid,\n class: `galley-form__form${options.className ? ` ${options.className}` : ""}`,\n action: native?.action,\n method: native ? "post" : undefined,\n enctype: native?.enctype,\n "accept-charset": native ? "UTF-8" : undefined,\n "aria-label": definition.name,\n "aria-describedby": definition.description ? `${uid}-description` : undefined,\n "data-galley-requires-js": !native,\n });\n\n const start =\n `<div${attributes({\n class: "galley-form",\n "data-galley-form": formId,\n "data-layout": appearance.layout ?? "stacked",\n "data-size": appearance.size ?? "regular",\n "data-labels": labels,\n "data-steps": steps > 1 ? steps : undefined,\n "data-state": "idle",\n "data-galley-unstyled": Boolean(options.unstyled),\n })}>` +\n `<form${formAttrs}>` +\n (definition.description ? `<p class="galley-form__description" id="${uid}-description">${inlineMarkdown(definition.description)}</p>` : "") +\n `<div class="galley-form__summary" id="${uid}-summary" tabindex="-1" role="group" aria-labelledby="${uid}-summary-title" hidden><p class="galley-form__summary-title" id="${uid}-summary-title"></p><ul class="galley-form__summary-list"></ul></div>`;\n const middle = hiddenInputs + honeypot + body + turnstile;\n const actionsStart = `<div class="galley-form__actions">${nav}`;\n const actionsEnd =\n `</div><p class="galley-form__status" id="${uid}-status" role="status" data-galley-status></p>` +\n (native ? "" : `<noscript><p class="galley-form__noscript">${esc(messages.noScript)}</p></noscript>`);\n const formEnd = "</form>";\n\n // \u2500\u2500 After a successful submission \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const message = /** @type {{ type: "message"; title?: string; text: string } | undefined} */ (definition.afterSubmit.find((action) => action.type === "message"));\n const downloads = definition.afterSubmit.filter((action) => action.type === "download");\n const mailtoPrimary = primary?.provider === "mailto";\n const successDefault =\n (message\n ? `${message.title ? `<p class="galley-form__success-title">${inlineMarkdown(message.title)}</p>` : ""}<div class="galley-form__success-text">${markdownParagraphs(message.text)}</div>`\n : `<p class="galley-form__success-title">${esc(messages.thanksTitle)}</p><div class="galley-form__success-text"><p>${esc(mailtoPrimary ? messages.mailtoText : messages.thanksText)}</p></div>`) +\n downloads\n .map((action) => (action.type === "download" ? `<p class="galley-form__download"><a href="${esc(withBase(action.url, base))}" download>${esc(action.label ?? messages.download)}</a></p>` : ""))\n .join("");\n const successStart = `<div class="galley-form__success" id="galley-sent-${formId}${options.instance ? `-${options.instance}` : ""}" tabindex="-1" data-galley-success hidden>`;\n const successEnd = "</div>";\n\n // \u2500\u2500 What the runtime needs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const config = {\n id: formId,\n uid,\n endpoint,\n fields: definition.fields\n .filter((field) => !LAYOUT.has(field.type) || field.showWhen)\n .map((field) => {\n /** @type {Record<string, unknown>} */\n const out = { id: field.id, type: field.type };\n\n // A consent field\'s text travels too: providers that record consent (HubSpot) send it.\n if (field.type === "consent") out.text = field.text ?? field.label ?? "";\n for (const key of /** @type {const} */ (["label", "name", "required", "validation", "showWhen", "autofill", "step", "options"])) {\n const value = field[key];\n\n if (value === undefined) continue;\n out[key] = key === "options" ? field.options?.map((option) => ({ value: option.value, label: option.label })) : value;\n }\n return out;\n }),\n steps,\n nextLabels: definition.steps?.map((step) => step.nextLabel ?? messages.next),\n // Server-side destinations are the capture server\'s to forward: their addresses stay out of the page.\n destinations: definition.destinations.filter((destination) => !isServerSide(destination)),\n // A redirect written from the site root ("/thanks/") goes to the page under the base path.\n afterSubmit: definition.afterSubmit.filter((action) => action.type !== "script" || options.allowFormScripts).map((action) => (action.type === "redirect" ? { ...action, url: withBase(action.url, base) } : action)),\n spam: { honeypot: definition.spam?.honeypot !== false, minSeconds: definition.spam?.minSeconds ?? 0, turnstile: Boolean(definition.spam?.turnstileSiteKey) },\n native: native?.index ?? -1,\n messages: {\n ...pick(messages, ["required", "requiredChoice", "requiredCheck", "email", "businessEmail", "url", "tel", "number", "date", "min", "max", "minLength", "maxLength", "pattern"]),\n ...pick(messages, ["summaryOne", "summaryMany", "sending", "sent", "rateLimited", "rateLimitedFor", "rateLimitedForOne", "tooFast", "notConnected", "step"]),\n error: definition.errorMessage ?? messages.error,\n },\n // The free-mailbox list travels only with forms that refuse personal addresses.\n freeEmailDomains: definition.fields.some((field) => field.validation?.businessEmailOnly) ? [...FREE_EMAIL_DOMAINS, ...(options.freeEmailDomains ?? [])] : [],\n name: definition.name,\n };\n const configHtml = `<script type="application/json" data-galley-form-config>${JSON.stringify(config).replace(/</g, "\\\\u003c")}</script>`;\n const end = `${successEnd}${configHtml}</div>`;\n\n return { start, middle, actionsStart, submit, actionsEnd, formEnd, successStart, successDefault, end, warnings: notices.map((notice) => notice.text), notices, config, uid };\n}\n\n/**\n * @template {Record<string, string>} T\n * @param {T} source\n * @param {(keyof T)[]} keys\n */\nfunction pick(source, keys) {\n /** @type {Partial<T>} */\n const out = {};\n\n for (const key of keys) out[key] = source[key];\n return out;\n}\n\n/**\n * The whole form as one string (no slots) \u2014 for tests and non-Astro use.\n *\n * @param {FormDefinition} definition\n * @param {string} formId\n * @param {RenderOptions} [options]\n */\nexport function renderFormHtml(definition, formId, options) {\n const parts = renderForm(definition, formId, options);\n\n return parts.start + parts.middle + parts.actionsStart + parts.submit + parts.actionsEnd + parts.formEnd + parts.successStart + parts.successDefault + parts.end;\n}\n', "mailto/config.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Settings, wording and styles of the email-link dialog (docs/mailto.md).\nimport { MAILTO_RUNTIME } from "./runtime.gen.js";\n\n/** The actions, in their default order. "outlook-live" (Outlook.com\'s own address) is available but not offered by default. */\nexport const MAILTO_OPTIONS = /** @type {const} */ (["gmail", "outlook", "app", "copy"]);\nexport const MAILTO_KNOWN = new Set([...MAILTO_OPTIONS, "outlook-live"]);\n\n/** Every word the dialog says, per brand/voice.md. `{address}` is the link\'s address. */\nexport const MAILTO_STRINGS = Object.freeze({\n label: "Email {address}",\n labelNoAddress: "Write an email",\n gmail: "Send with Gmail",\n outlook: "Send with Outlook",\n "outlook-live": "Send with Outlook.com",\n app: "Open my mail app",\n copy: "Copy address",\n copied: "Copied",\n copyFailed: "Couldn\'t copy. Select the address above instead.",\n close: "Close",\n});\n\n/*\n * Custom properties (with system fallbacks):\n * --galley-mailto-bg --galley-mailto-text --galley-mailto-border\n * --galley-mailto-radius --galley-mailto-shadow --galley-mailto-hover\n * --galley-field-focus (focus ring)\n * No animation, so nothing moves for anyone (reduced motion included).\n */\nexport const MAILTO_CSS =\n ".galley-mailto{position:fixed;z-index:2147483001;box-sizing:border-box;min-width:14rem;max-width:22rem;padding:.5rem;border:1px solid var(--galley-mailto-border,#8886);border-radius:var(--galley-mailto-radius,.5rem);background:var(--galley-mailto-bg,Canvas);color:var(--galley-mailto-text,CanvasText);box-shadow:var(--galley-mailto-shadow,0 8px 28px #0003);font:inherit;font-size:.9375rem;line-height:1.4}" +\n ".galley-mailto[data-sheet]{inset:auto 0 0;max-width:none;padding:1rem}" +\n ".galley-mailto p{margin:.25rem 2.25rem .5rem .5rem}.galley-mailto__address{font-weight:600;user-select:all;overflow-wrap:anywhere}" +\n ".galley-mailto ul{margin:0;padding:0;list-style:none}" +\n ".galley-mailto__option{display:block;box-sizing:border-box;width:100%;padding:.5rem;border:0;border-radius:.25rem;background:none;color:inherit;font:inherit;text-align:start;text-decoration:none;cursor:pointer}" +\n ".galley-mailto__option:hover,.galley-mailto__option:focus-visible{background:var(--galley-mailto-hover,#8882)}" +\n ".galley-mailto :focus-visible{outline:2px solid var(--galley-field-focus,Highlight)}" +\n ".galley-mailto__status:empty{display:none}" +\n ".galley-mailto__close{position:absolute;top:.25rem;right:.25rem;width:2rem;height:2rem;border:0;background:none;color:inherit;font:inherit;font-size:1.25rem;cursor:pointer}";\n\n/**\n * @typedef {object} MailtoOptions\n * @property {string[]} [options] Which actions, in which order: "gmail", "outlook", "outlook-live", "app", "copy".\n * @property {Record<string, string>} [strings] Wording, by key (MAILTO_STRINGS).\n */\n\n/**\n * The dialog\'s settings with defaults, or null when it is off.\n *\n * @param {MailtoOptions | boolean | undefined} given\n * @returns {{ options: string[]; strings: Record<string, string> } | null}\n */\nexport function resolveMailto(given) {\n if (given === false) return null;\n const settings = typeof given === "object" && given ? given : {};\n const options = (settings.options ?? [...MAILTO_OPTIONS]).filter((option) => MAILTO_KNOWN.has(/** @type {any} */ (option)));\n\n if (settings.options && options.length !== settings.options.length) {\n throw new Error(`mailto.options can only list ${[...MAILTO_KNOWN].map((option) => `"${option}"`).join(", ")}.`);\n }\n return { options, strings: { ...MAILTO_STRINGS, ...(settings.strings ?? {}) } };\n}\n\n/** The inline script\'s text \u2014 the same on every page of a site (one CSP hash). */\nexport function mailtoScript(/** @type {{ options: string[]; strings: Record<string, string> }} */ config) {\n return `(${MAILTO_RUNTIME})(${JSON.stringify({ ...config, css: MAILTO_CSS }).replace(/</g, "\\\\u003c")})`;\n}\n\n/** The <script> element, with the marker that keeps it from being added twice. */\nexport function mailtoTag(/** @type {{ options: string[]; strings: Record<string, string> }} */ config) {\n return `<script data-galley-mailto-script>${mailtoScript(config)}</script>`;\n}\n\n/** Whether a page has an email link worth enhancing. */\nexport const HAS_MAILTO = /<a\\b[^>]*\\bhref\\s*=\\s*["\']?mailto:/i;\n', "mailto/runtime.gen.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162728
163056
|
// Generated by scripts/build-inline.mjs from runtime.js \u2014 do not edit.
|
|
162729
163057
|
// @ts-check
|
|
162730
163058
|
/** The email-link dialog as one minified function expression, inlined before </body>. */
|
|
162731
163059
|
export const MAILTO_RUNTIME = "function(E){let c=document,m=window,g=E.strings,l=null,d=null,k=!1;function w(t){try{return decodeURIComponent(t)}catch(e){return t.replace(/(%[0-9a-f]{2})+/gi,i=>{try{return decodeURIComponent(i)}catch(o){return i.replace(/%([0-7][0-9a-f])/gi,(a,r)=>String.fromCharCode(parseInt(r,16)))}})}}function x(t){return t.split(\\",\\").map(e=>w(e).trim()).filter(Boolean)}function C(t){let e=t.replace(/^mailto:/i,\\"\\"),i=e.indexOf(\\"?\\"),o={to:x(i<0?e:e.slice(0,i)),cc:[],bcc:[],subject:\\"\\",body:\\"\\"};return(i<0?\\"\\":e.slice(i+1)).split(\\"&\\").forEach(a=>{let r=a.indexOf(\\"=\\"),s=w(r<0?a:a.slice(0,r)).toLowerCase(),b=r<0?\\"\\":a.slice(r+1);s===\\"to\\"||s===\\"cc\\"||s===\\"bcc\\"?o[s]=o[s].concat(x(b)):(s===\\"subject\\"||s===\\"body\\")&&!o[s]&&(o[s]=w(b).replace(/\\\\r\\\\n?/g,\`\\n\`))}),o}function A(t){return t.filter(e=>e[1]).map(e=>e[0]+\\"=\\"+encodeURIComponent(e[1])).join(\\"&\\")}function _(t){let e=C(t),i=e.to.join(\\",\\"),o=e.cc.join(\\",\\"),a=e.bcc.join(\\",\\"),r=A([[\\"to\\",i],[\\"cc\\",o],[\\"bcc\\",a],[\\"subject\\",e.subject],[\\"body\\",e.body]]);return{message:e,gmail:\\"https://mail.google.com/mail/?view=cm&fs=1&\\"+A([[\\"to\\",i],[\\"cc\\",o],[\\"bcc\\",a],[\\"su\\",e.subject],[\\"body\\",e.body]]),outlook:\\"https://outlook.office.com/mail/deeplink/compose?\\"+r,\\"outlook-live\\":\\"https://outlook.live.com/mail/0/deeplink/compose?\\"+r,app:t}}m.galleyMailto={parse:C,links:_};function f(t,e,i){let o=c.createElement(t);return e&&(o.className=e),i&&(o.textContent=i),o}function L(){return l?Array.prototype.slice.call(l.querySelectorAll(\\".galley-mailto__option\\")):[]}function y(t){l&&(l.remove(),l=null,c.removeEventListener(\\"pointerdown\\",j,!0),c.removeEventListener(\\"focusin\\",K,!0),m.removeEventListener(\\"resize\\",v),m.removeEventListener(\\"scroll\\",v,!0),t&&d&&d.focus(),d=null)}function j(t){l&&!l.contains(t.target)&&t.target!==d&&y(!t.target.closest||!t.target.closest(\\"a,button,input,select,textarea,[tabindex]\\"))}function K(t){l&&!l.contains(t.target)&&y(!1)}function v(t){(!t||!l||!l.contains(t.target))&&M()}function M(){if(!l||!d)return;if(m.matchMedia&&m.matchMedia(\\"(max-width: 32rem)\\").matches){l.setAttribute(\\"data-sheet\\",\\"\\"),l.style.top=l.style.left=\\"\\";return}l.removeAttribute(\\"data-sheet\\");let t=d.getClientRects()[0]||d.getBoundingClientRect(),e=l.getBoundingClientRect(),i=c.documentElement.clientWidth,o=c.documentElement.clientHeight,a=6,r=t.bottom+a;r+e.height>o-8&&t.top-a-e.height>8&&(r=t.top-a-e.height),l.style.top=Math.max(8,r)+\\"px\\",l.style.left=Math.max(8,Math.min(t.left,i-e.width-8))+\\"px\\"}function D(t){y(!1);let e=t.getAttribute(\\"href\\"),i=_(e),o=i.message.to.join(\\", \\");if(!k){k=!0;let n=f(\\"style\\");n.textContent=E.css,c.head.appendChild(n)}d=t,l=f(\\"div\\",\\"galley-mailto\\"),l.setAttribute(\\"role\\",\\"dialog\\"),l.setAttribute(\\"aria-label\\",(o?g.label:g.labelNoAddress).replace(\\"{address}\\",o)),l.setAttribute(\\"data-galley-mailto\\",\\"off\\"),o&&l.appendChild(f(\\"p\\",\\"galley-mailto__address\\",o));let a=f(\\"ul\\",\\"galley-mailto__options\\"),r=f(\\"p\\",\\"galley-mailto__status\\");r.setAttribute(\\"role\\",\\"status\\"),E.options.forEach(n=>{if(n===\\"copy\\"&&!o)return;let p=f(\\"li\\"),u;if(n===\\"copy\\")u=f(\\"button\\",\\"galley-mailto__option\\",g.copy),u.type=\\"button\\",u.addEventListener(\\"click\\",()=>{let h=I=>{r.textContent=I?g.copied:g.copyFailed,setTimeout(()=>{r.textContent=\\"\\"},2500)};navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(i.message.to.join(\\", \\")).then(()=>{h(!0)},()=>{h(!1)}):h(!1)});else if(i[n])u=f(\\"a\\",\\"galley-mailto__option\\",g[n]||n),u.href=i[n],n!==\\"app\\"&&(u.target=\\"_blank\\",u.rel=\\"noopener noreferrer\\"),u.addEventListener(\\"click\\",()=>{setTimeout(()=>{y(!1)},0)});else return;u.setAttribute(\\"data-option\\",n),p.appendChild(u),a.appendChild(p)});let s=f(\\"button\\",\\"galley-mailto__close\\",\\"\\\\xD7\\");s.type=\\"button\\",s.setAttribute(\\"aria-label\\",g.close),s.addEventListener(\\"click\\",()=>{y(!0)}),l.appendChild(a),l.appendChild(r),l.appendChild(s),l.addEventListener(\\"keydown\\",n=>{let p=L(),u=p.indexOf(c.activeElement);if(n.key===\\"Escape\\")n.preventDefault(),y(!0);else if(n.key===\\"ArrowDown\\"||n.key===\\"ArrowUp\\"||n.key===\\"Home\\"||n.key===\\"End\\"){n.preventDefault();let h=n.key===\\"Home\\"?0:n.key===\\"End\\"?p.length-1:(u+(n.key===\\"ArrowDown\\"?1:-1)+p.length)%p.length;p[h].focus()}}),c.body.appendChild(l),M(),c.addEventListener(\\"pointerdown\\",j,!0),c.addEventListener(\\"focusin\\",K,!0),m.addEventListener(\\"resize\\",v),m.addEventListener(\\"scroll\\",v,!0);let b=L()[0];b&&b.focus()}function R(t){let e=t.target&&t.target.closest?t.target.closest(\\"a[href]\\"):null;return!e||!/^mailto:/i.test(e.getAttribute(\\"href\\"))||e.hasAttribute(\\"download\\")||e.closest('[data-galley-mailto=\\"off\\"]')?null:e}c.addEventListener(\\"click\\",t=>{if(t.defaultPrevented||t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=R(t);e&&(t.preventDefault(),l&&d===e?y(!0):D(e))}),c.addEventListener(\\"keydown\\",t=>{if(t.key!==\\" \\"||t.defaultPrevented||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=R(t);e&&(t.preventDefault(),D(e))})}";
|
|
162732
|
-
`, "shared/glob.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Page-path globs for a script\'s `include` / `exclude`, matched at build time\n// against each page\'s path (without the site\'s base):\n//\n// "/" the home page only\n// "/pricing/" that page (with or without the trailing slash)\n// "/blog/*" pages one level under /blog/\n// "/blog/**" /blog/ and everything under it\n// "*/thanks/" `*` never crosses a "/"; `?` is one character\n\n/** @type {Map<string, RegExp>} */\nconst cache = new Map();\n\n/** @param {string} glob */\nfunction compile(glob) {\n const known = cache.get(glob);\n\n if (known) return known;\n let source = "";\n let pattern = glob.trim();\n\n if (!pattern.startsWith("/")) pattern = `/${pattern}`;\n pattern = pattern.replace(/\\/+$/, "");\n for (let index = 0; index < pattern.length; index += 1) {\n const char = pattern[index];\n\n if (char === "*" && pattern[index + 1] === "*") {\n // "/blog/**" also matches "/blog" itself.\n if (source.endsWith("/")) source = `${source.slice(0, -1)}(?:/.*)?`;\n else source += ".*";\n index += 1;\n } else if (char === "*") source += "[^/]*";\n else if (char === "?") source += "[^/]";\n else source += String(char).replace(/[.+^${}()|[\\]\\\\]/g, "\\\\$&");\n }\n const regex = new RegExp(`^${source}/?$`);\n\n cache.set(glob, regex);\n return regex;\n}\n\n/**\n * @param {string} path The page\'s path, e.g. "/pricing/".\n * @param {string} glob\n */\nexport function matchGlob(path, glob) {\n const clean = path.split(/[?#]/)[0] || "/";\n\n return compile(glob).test(clean === "/" ? "/" : clean.replace(/\\/+$/, "")) || (glob.trim().replace(/\\/+$/, "") === "" && clean === "/");\n}\n\n/**\n * Whether a page is in an entry\'s scope: in `include` (or `include` is empty)\n * and not in `exclude`.\n *\n * @param {string} path\n * @param {{ include?: string[]; exclude?: string[] }} entry\n */\nexport function inScope(path, entry) {\n const included = !entry.include || entry.include.length === 0 || entry.include.some((glob) => matchGlob(path, glob));\n\n return included && !(entry.exclude ?? []).some((glob) => matchGlob(path, glob));\n}\n', "shared/markdown.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The little Markdown a form\'s texts may use \u2014 **bold**, *italic*, `code`\n// and [links](https://\u2026) \u2014 rendered to escaped HTML. Nothing else is\n// interpreted: no raw HTML, no images, no headings.\n//\n// `{{field}}` placeholders become `<span data-galley-value="field"></span>`;\n// the browser fills them with the visitor\'s answer as plain text after a\n// submission. They are never filled inside a link address, so an answer can\n// never become a link.\n\nconst ESCAPES = /** @type {Record<string, string>} */ ({ "&": "&", "<": "<", ">": ">", \'"\': """, "\'": "'" });\n\n/** @param {string} text */\nexport function escapeHtml(text) {\n return String(text).replace(/[&<>"\']/g, (char) => ESCAPES[char] ?? char);\n}\n\nconst PLACEHOLDER = /\\{\\{\\s*([a-z][a-z0-9_-]*)\\s*\\}\\}/g;\n\n/** Escaped text with `{{field}}` placeholders turned into fill-in spans. */\nfunction text(/** @type {string} */ raw) {\n return escapeHtml(raw).replace(PLACEHOLDER, (_, id) => `<span data-galley-value="${id}"></span>`);\n}\n\n/**\n * Only addresses that go somewhere ordinary: http(s), mail, phone, or a path\n * or anchor on this site. Anything else (javascript:, data:) becomes "#".\n *\n * @param {string} url\n */\nexport function safeUrl(url) {\n const value = url.trim();\n\n if (/^(https?:|mailto:|tel:)/i.test(value) || /^[/#?.]/.test(value)) return value;\n if (!/^[a-z][a-z0-9+.-]*:/i.test(value)) return value;\n return "#";\n}\n\n/**\n * A site-root address ("/privacy/") under the site\'s base path ("/docs" \u2192\n * "/docs/privacy/"), so links written from the site root keep working in a\n * sub-path build. Full addresses, protocol-relative ones, anchors and\n * addresses already under the base are left as they are.\n *\n * @param {string} url\n * @param {string} [base] e.g. "/docs" or "/docs/"; "" or "/" for none.\n */\nexport function withBase(url, base = "") {\n const prefix = base.replace(/\\/+$/, "");\n\n if (!prefix || !url.startsWith("/") || url.startsWith("//") || url === prefix || url.startsWith(`${prefix}/`)) return url;\n return `${prefix}${url}`;\n}\n\n/** @typedef {{ base?: string }} MarkdownOptions */\n\nconst INLINE = /\\*\\*([^*]+?)\\*\\*|\\*([^*\\s][^*]*?)\\*|`([^`]+)`|\\[([^\\]]+)\\]\\(([^)\\s]+)\\)/g;\n\n/**\n * One line (or a few) of inline Markdown as HTML.\n *\n * @param {string} source\n * @param {MarkdownOptions} [options] `base`: the site\'s base path, for links written from the site root.\n * @returns {string}\n */\nexport function inlineMarkdown(source, options = {}) {\n let out = "";\n let last = 0;\n\n for (const match of String(source).matchAll(INLINE)) {\n out += text(source.slice(last, match.index));\n const [, bold, italic, code, label, href] = match;\n\n if (bold !== undefined) out += `<strong>${inlineMarkdown(bold, options)}</strong>`;\n else if (italic !== undefined) out += `<em>${inlineMarkdown(italic, options)}</em>`;\n else if (code !== undefined) out += `<code>${escapeHtml(code)}</code>`;\n else if (label !== undefined && href !== undefined) {\n const url = withBase(safeUrl(href.replace(PLACEHOLDER, "")), options.base);\n const external = /^https?:/i.test(url);\n\n out += `<a href="${escapeHtml(url)}"${external ? \' rel="noopener"\' : ""}>${inlineMarkdown(label, options)}</a>`;\n }\n last = (match.index ?? 0) + match[0].length;\n }\n return out + text(source.slice(last));\n}\n\n/**\n * Paragraphs of inline Markdown: blank lines separate paragraphs, single\n * line breaks are kept.\n *\n * @param {string} source\n * @param {MarkdownOptions} [options]\n * @returns {string}\n */\nexport function markdownParagraphs(source, options = {}) {\n return String(source)\n .trim()\n .split(/\\n\\s*\\n/)\n .filter((part) => part.trim())\n .map((part) => `<p>${part.trim().split(/\\n/).map((line) => inlineMarkdown(line, options)).join("<br>")}</p>`)\n .join("");\n}\n\n/**\n * The plain words of a Markdown text \u2014 for a consent text sent to a provider\n * that records what the visitor agreed to.\n *\n * @param {string} source\n */\nexport function plainText(source) {\n return String(source)\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, "$1")\n .replace(/\\*\\*([^*]+)\\*\\*/g, "$1")\n .replace(/\\*([^*]+)\\*/g, "$1")\n .replace(/`([^`]+)`/g, "$1")\n .replace(/\\s+/g, " ")\n .trim();\n}\n', "scripts/banner.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The built-in consent banner: a small, non-modal region at the foot of the\n// page with three equal choices \u2014 accept all, reject all, choose \u2014 and the\n// categories this site actually uses. Server-rendered and hidden; the scripts\n// runtime shows it when no choice is stored, and again whenever an element\n// with `data-galley-consent-open` is clicked (a footer link, say).\n//\n// Every word comes from scripts.json \u2192 consent.banner, falling back to the\n// defaults below (written to brand/voice.md). Styled only through custom\n// properties, so a site themes it like its forms.\n\nimport { escapeHtml as esc, inlineMarkdown, withBase } from "../shared/markdown.js";\n\n/** @typedef {import("../kit").ConsentSettings} ConsentSettings */\n/** @typedef {import("../kit").ConsentCategory} ConsentCategory */\n\nexport const BANNER_DEFAULTS = Object.freeze({\n title: "Cookies and tracking",\n text: "This site would like to measure visits and the success of its marketing. Choose what it may use. You can change this at any time from the link at the bottom of each page.",\n acceptLabel: "Accept all",\n rejectLabel: "Reject all",\n settingsLabel: "Choose\u2026",\n saveLabel: "Save choices",\n policyLabel: "Privacy policy",\n});\n\nexport const CATEGORY_DEFAULTS = Object.freeze({\n necessary: { label: "Necessary", description: "Needed for the site to work. Always on." },\n analytics: { label: "Analytics", description: "Counts visits and shows which pages are used." },\n marketing: { label: "Marketing", description: "Measures ads and remembers visits for campaigns." },\n preferences: { label: "Preferences", description: "Remembers choices such as chat conversations." },\n});\n\n/**\n * @param {ConsentSettings} consent\n * @param {ConsentCategory[]} categories The optional categories the site uses, in order.\n * @param {{ base?: string }} [options] `base`: the site\'s base path, for a policyUrl or text links written from the site root.\n */\nexport function renderBanner(consent, categories, options = {}) {\n const base = options.base ?? "";\n const text = { ...BANNER_DEFAULTS, ...Object.fromEntries(Object.entries(consent.banner ?? {}).filter(([, value]) => typeof value === "string" && value)) };\n /** @param {ConsentCategory} category */\n const category = (category) => ({ ...CATEGORY_DEFAULTS[category], ...(consent.banner?.categories?.[category] ?? {}) });\n const rows = /** @type {ConsentCategory[]} */ (["necessary", ...categories])\n .map((name) => {\n const info = category(name);\n const id = `galley-consent-${name}`;\n\n return `<div class="galley-consent__category"><input type="checkbox" id="${id}"${name === "necessary" ? " checked disabled" : ` data-category="${name}"`}><label for="${id}"><span class="galley-consent__category-name">${esc(info.label)}</span> <span class="galley-consent__category-text">${esc(info.description)}</span></label></div>`;\n })\n .join("");\n const policy = consent.banner?.policyUrl ? ` <a href="${esc(withBase(consent.banner.policyUrl, base))}">${esc(text.policyLabel)}</a>` : "";\n\n return (\n `<section class="galley-consent" data-galley-consent aria-labelledby="galley-consent-title" hidden>` +\n `<div class="galley-consent__inner">` +\n `<p class="galley-consent__title" id="galley-consent-title">${esc(text.title)}</p>` +\n `<p class="galley-consent__text">${inlineMarkdown(text.text, { base })}${policy}</p>` +\n `<fieldset class="galley-consent__choices" id="galley-consent-choices" data-galley-consent-choices hidden><legend class="galley-visually-hidden">${esc(text.settingsLabel.replace(/\u2026$/, ""))}</legend>${rows}</fieldset>` +\n `<div class="galley-consent__actions">` +\n `<button type="button" class="galley-consent__button" data-galley-consent-accept>${esc(text.acceptLabel)}</button>` +\n `<button type="button" class="galley-consent__button" data-galley-consent-reject>${esc(text.rejectLabel)}</button>` +\n `<button type="button" class="galley-consent__button galley-consent__button--quiet" data-galley-consent-settings aria-expanded="false" aria-controls="galley-consent-choices">${esc(text.settingsLabel)}</button>` +\n `<button type="button" class="galley-consent__button" data-galley-consent-save hidden>${esc(text.saveLabel)}</button>` +\n `</div></div></section>`\n );\n}\n\n/*\n * Custom properties (with fallbacks):\n * --galley-consent-bg Canvas --galley-consent-text CanvasText\n * --galley-consent-border currentColor 25% --galley-consent-radius 0.5rem\n * --galley-consent-shadow a soft shadow --galley-consent-width 44rem\n * --galley-button-bg / --galley-button-text / --galley-button-radius (shared with forms;\n * CanvasText on Canvas when unset \u2014 never currentColor, which on a button\n * is its own text colour)\n * --galley-field-focus focus ring\n */\nexport const BANNER_CSS = `.galley-consent [hidden]{display:none!important}.galley-consent{position:fixed;inset-inline:0;inset-block-end:0;z-index:2147483000;display:flex;justify-content:center;padding:0.75rem;pointer-events:none}.galley-consent[hidden]{display:none}.galley-consent__inner{box-sizing:border-box;display:grid;gap:0.75rem;width:min(100%,var(--galley-consent-width,44rem));max-height:calc(100vh - 1.5rem);overflow:auto;padding:1rem 1.25rem;border:1px solid var(--galley-consent-border,color-mix(in srgb,currentColor 25%,transparent));border-radius:var(--galley-consent-radius,0.5rem);background:var(--galley-consent-bg,Canvas);color:var(--galley-consent-text,CanvasText);box-shadow:var(--galley-consent-shadow,0 8px 30px rgb(0 0 0 / 0.18));font:inherit;pointer-events:auto}.galley-consent__title{margin:0;font-weight:700}.galley-consent__text{margin:0}.galley-consent__text a{color:inherit}.galley-consent__choices{display:grid;gap:0.5rem;margin:0;padding:0;border:0}.galley-consent__category{display:grid;grid-template-columns:auto 1fr;gap:0.6rem;align-items:start}.galley-consent__category input{width:1.1em;height:1.1em;margin:0.2em 0 0;accent-color:var(--galley-field-focus,Highlight)}.galley-consent__category-name{font-weight:600}.galley-consent__actions{display:flex;flex-wrap:wrap;gap:0.5rem}.galley-consent__button{min-height:2.5rem;padding:0.5em 1em;border:1px solid var(--galley-button-bg,CanvasText);border-radius:var(--galley-button-radius,0.375rem);background:var(--galley-button-bg,CanvasText);color:var(--galley-button-text,Canvas);font:inherit;font-weight:600;cursor:pointer}.galley-consent__button--quiet{background:transparent;color:inherit}.galley-consent__button:focus-visible,.galley-consent input:focus-visible,.galley-consent a:focus-visible{outline:2px solid var(--galley-field-focus,Highlight);outline-offset:2px}.galley-visually-hidden{position:absolute!important;width:1px!important;height:1px!important;overflow:hidden!important;clip-path:inset(50%)!important;white-space:nowrap!important}`;\n', "scripts/plan.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// scripts.json \u2192 what one page gets, and the HTML for each place it goes.\n// Used by the integration\'s middleware (no template changes), by <Scripts />\n// for sites that place things themselves, by the build summary and by the\n// dev-only manifest at /__galley/scripts.json.\n//\n// Every snippet goes into the page inert \u2014 <script type="text/plain"> \u2014 and\n// only the inline runtime (runtime.js) turns it into a running script, after\n// checking consent, the load moment and whether the page is in the editor\'s\n// preview. <noscript> fallbacks are written only for scripts that need no\n// consent, because a page without JavaScript can\'t ask for it.\n\nimport { SCRIPT_INTEGRATIONS } from "../catalog-data.js";\nimport { inScope } from "../shared/glob.js";\nimport { BANNER_CSS, renderBanner } from "./banner.js";\nimport { RUNTIME } from "./runtime.gen.js";\nimport { buildSnippet } from "./snippets.js";\n\n/** @typedef {import("../kit").ScriptsConfig} ScriptsConfig */\n/** @typedef {import("../kit").ScriptEntry} ScriptEntry */\n/** @typedef {import("../kit").ConsentCategory} ConsentCategory */\n/** @typedef {import("./snippets.js").ScriptPart} ScriptPart */\n/** @typedef {"head" | "body-start" | "body-end"} Placement */\n\n/**\n * @typedef {object} ResolvedEntry\n * @property {ScriptEntry} entry\n * @property {string} name\n * @property {ConsentCategory} consent\n * @property {Placement} placement\n * @property {"eager" | "idle" | "interaction"} load\n * @property {ScriptPart[]} parts\n */\n\n/**\n * @typedef {object} PagePlan\n * @property {ResolvedEntry[]} entries The entries this page carries.\n * @property {boolean} runtime Whether the page needs the inline runtime at all.\n * @property {boolean} banner\n * @property {ConsentCategory[]} categories Optional categories used anywhere on the site.\n * @property {Record<string, unknown>} config The runtime\'s configuration.\n * @property {(category: ConsentCategory) => boolean} grantedByDefault\n */\n\nexport const PLACEMENTS = /** @type {const} */ (["head", "body-start", "body-end"]);\nconst ORDER = /** @type {ConsentCategory[]} */ (["analytics", "marketing", "preferences"]);\n\n/**\n * Every enabled entry with its consent, placement, load moment and parts.\n * Throws (a ScriptSettingsError) on an id that doesn\'t fit its integration.\n *\n * @param {ScriptsConfig} config\n * @returns {ResolvedEntry[]}\n */\nexport function resolveEntries(config) {\n return config.scripts\n .filter((entry) => entry.enabled)\n .map((entry) => {\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n\n return {\n entry,\n name: entry.label ?? info?.name ?? entry.kind,\n consent: entry.consent ?? info?.defaultConsent ?? "marketing",\n placement: entry.placement ?? info?.defaultPlacement ?? "body-end",\n load: entry.load ?? "eager",\n parts: buildSnippet(entry),\n };\n });\n}\n\n/**\n * @param {ScriptsConfig | null | undefined} config\n * @param {{ path: string; dev?: boolean; host?: string; utm?: boolean; resolved?: ResolvedEntry[] }} page\n * @returns {PagePlan}\n */\nexport function planPage(config, page) {\n const consent = config?.consent ?? { mode: "none" };\n const all = config ? page.resolved ?? resolveEntries(config) : [];\n const entries = all.filter(({ entry }) => inScope(page.path, entry) && (!page.dev || entry.inPreview === true));\n // UTM memory for forms is marketing attribution: under a consent mode it is\n // stored only once "marketing" is granted, so a site whose forms use it\n // offers Marketing in the banner even when no script needs it (docs/scripts.md).\n const categories = ORDER.filter((category) => all.some((item) => item.consent === category) || (category === "marketing" && Boolean(page.utm)));\n const defaults = consent.defaults ?? [];\n const grantedByDefault = (/** @type {ConsentCategory} */ category) => category === "necessary" || consent.mode === "none" || defaults.includes(category);\n const banner = consent.mode === "banner" && categories.length > 0;\n const runtime = entries.length > 0 || banner || Boolean(page.utm) || (consent.mode !== "none" && Boolean(consent.googleConsentMode));\n\n return {\n entries,\n runtime,\n banner,\n categories,\n grantedByDefault,\n config: { mode: consent.mode, defaults, gcm: Boolean(consent.googleConsentMode), host: page.host ?? "", utm: Boolean(page.utm) },\n };\n}\n\n/** Script text that can sit inside <script>\u2026</script> without ending it early. */\nconst scriptText = (/** @type {string} */ code) => code.replace(/<\\/(script)/gi, "<\\\\/$1").replace(/<!--/g, "<\\\\!--");\n/** @param {string} value */\nconst attr = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");\n\n/** The constant text of the runtime\'s inline script for this configuration. */\nexport function runtimeScript(/** @type {PagePlan} */ plan) {\n return `(${RUNTIME})(${JSON.stringify(plan.config)})`;\n}\n\n/** @param {Placement} placement */\nexport const runCall = (placement) => `galleyScripts.run("${placement}")`;\n\n/**\n * The HTML for one placement of one page ("" when it has nothing).\n *\n * @param {PagePlan} plan\n * @param {Placement} placement\n * @param {{ consent?: import("../kit").ConsentSettings; base?: string }} [extra] `base`: the site\'s base path.\n */\nexport function renderPlacement(plan, placement, extra = {}) {\n if (!plan.runtime) return "";\n let html = "";\n\n if (placement === "head") {\n html += `<script data-galley-scripts="head">${runtimeScript(plan)}</script>`;\n if (plan.banner) html += `<style data-galley-consent-style>${BANNER_CSS}</style>`;\n }\n let blocks = 0;\n\n for (const item of plan.entries) {\n for (const [index, part] of item.parts.entries()) {\n const at = part.placement ?? item.placement;\n\n if (at !== placement) continue;\n if (part.type === "noscript") {\n if (plan.grantedByDefault(item.consent)) html += `<noscript data-galley-script="${attr(item.entry.id)}">${part.html ?? ""}</noscript>`;\n continue;\n }\n blocks += 1;\n html +=\n `<script type="text/plain" data-galley-script="${attr(item.entry.id)}" data-part="${index}" data-placement="${placement}" data-consent="${item.consent}" data-load="${item.load}"` +\n (item.entry.inPreview ? " data-preview" : "") +\n (part.src ? ` data-src="${attr(part.src)}"` : "") +\n (part.attrs && Object.keys(part.attrs).length > 0 ? ` data-attrs="${attr(JSON.stringify(part.attrs))}"` : "") +\n `>${part.src ? "" : scriptText(part.code ?? "")}</script>`;\n }\n }\n if (placement === "body-end" && plan.banner && extra.consent) html += renderBanner(extra.consent, plan.categories, { base: extra.base });\n if (blocks > 0 || placement === "body-end") html += `<script data-galley-scripts="${placement}">${runCall(placement)}</script>`;\n return html;\n}\n\n/**\n * Puts each placement\'s HTML into a finished page: the head part right after\n * <meta charset> (else right after <head>), body-start right after <body>,\n * body-end before </body>. A placement the page already carries (because the\n * layout uses <Scripts />) is left alone.\n *\n * @param {string} html\n * @param {PagePlan} plan\n * @param {{ consent?: import("../kit").ConsentSettings; base?: string }} [extra]\n */\nexport function injectPlan(html, plan, extra = {}) {\n if (!plan.runtime) return html;\n let out = html;\n const has = (/** @type {Placement} */ placement) => out.includes(`data-galley-scripts="${placement}"`);\n\n if (!has("head")) {\n const head = renderPlacement(plan, "head", extra);\n const charset = /<meta[^>]+charset[^>]*>/i.exec(out);\n const headOpen = /<head\\b[^>]*>/i.exec(out);\n const at = charset && headOpen && charset.index > headOpen.index ? charset.index + charset[0].length : headOpen ? headOpen.index + headOpen[0].length : -1;\n\n if (at >= 0) out = out.slice(0, at) + head + out.slice(at);\n }\n if (!has("body-start")) {\n const start = renderPlacement(plan, "body-start", extra);\n const body = /<body\\b[^>]*>/i.exec(out);\n\n if (start && body) out = out.slice(0, body.index + body[0].length) + start + out.slice(body.index + body[0].length);\n }\n if (!has("body-end")) {\n // A layout that renders <ConsentBanner /> itself keeps its own.\n const end = renderPlacement(plan, "body-end", /data-galley-consent[\\s>]/.test(out) ? { base: extra.base } : extra);\n const close = out.toLowerCase().lastIndexOf("</body>");\n\n if (end) out = close >= 0 ? out.slice(0, close) + end + out.slice(close) : out + end;\n }\n return out;\n}\n\n/**\n * What the build log says: which scripts load on the site and under which\n * consent, one line each.\n *\n * @param {ScriptsConfig} config\n * @returns {string[]}\n */\nexport function summarize(config) {\n const consent = config.consent ?? { mode: "none" };\n const resolved = resolveEntries(config);\n const mode = consent.mode === "banner" ? "the built-in consent banner" : consent.mode === "external" ? "another consent tool (galleyConsent.set / Consent Mode / Cookiebot)" : "no consent step";\n const lines = [`scripts: ${resolved.length} of ${config.scripts.length} enabled \xB7 ${mode}${consent.googleConsentMode ? " \xB7 Google Consent Mode v2" : ""}`];\n\n for (const item of resolved) {\n const id = Object.values(item.entry.settings).find((value) => typeof value === "string" && /^[A-Za-z0-9-]{4,}$/.test(value));\n const when = item.consent === "necessary" || consent.mode === "none" ? "always" : `after ${item.consent} consent`;\n const where = item.entry.include?.length ? `only ${item.entry.include.join(", ")}` : "every page";\n const except = item.entry.exclude?.length ? ` except ${item.entry.exclude.join(", ")}` : "";\n\n lines.push(` \u2713 ${item.entry.id} \xB7 ${item.name}${id ? ` ${id}` : ""} \xB7 ${item.placement}, ${item.load} \xB7 ${when} \xB7 ${where}${except}`);\n }\n for (const entry of config.scripts.filter((item) => !item.enabled)) lines.push(` \u2013 ${entry.id} \xB7 off`);\n return lines;\n}\n\n/**\n * The dev-only manifest: what a given page would load in production.\n *\n * @param {ScriptsConfig | null} config\n * @param {string} path\n * @param {string} file The scripts file, relative to the site.\n */\nexport function manifest(config, path, file) {\n if (!config) return { file, exists: false, path, consent: { mode: "none" }, scripts: [] };\n const resolved = resolveEntries(config);\n\n return {\n file,\n exists: true,\n path,\n consent: config.consent ?? { mode: "none" },\n scripts: config.scripts.map((entry) => {\n const item = resolved.find((candidate) => candidate.entry === entry);\n const onPage = Boolean(item) && inScope(path, entry);\n\n return {\n id: entry.id,\n kind: entry.kind,\n label: item?.name ?? entry.label ?? entry.kind,\n enabled: entry.enabled,\n consent: item?.consent ?? entry.consent ?? null,\n placement: item?.placement ?? entry.placement ?? null,\n load: item?.load ?? entry.load ?? "eager",\n inPreview: entry.inPreview === true,\n loadsOnPage: onPage,\n reason: !entry.enabled ? "turned off" : onPage ? (item?.consent === "necessary" || (config.consent?.mode ?? "none") === "none" ? "loads" : `loads after ${item?.consent} consent`) : "not on this page (include/exclude)",\n inDev: onPage && entry.inPreview === true,\n };\n }),\n };\n}\n', "scripts/runtime.gen.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163060
|
+
`, "shared/glob.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Page-path globs for a script\'s `include` / `exclude`, matched at build time\n// against each page\'s path (without the site\'s base):\n//\n// "/" the home page only\n// "/pricing/" that page (with or without the trailing slash)\n// "/blog/*" pages one level under /blog/\n// "/blog/**" /blog/ and everything under it\n// "*/thanks/" `*` never crosses a "/"; `?` is one character\n\n/** @type {Map<string, RegExp>} */\nconst cache = new Map();\n\n/** @param {string} glob */\nfunction compile(glob) {\n const known = cache.get(glob);\n\n if (known) return known;\n let source = "";\n let pattern = glob.trim();\n\n if (!pattern.startsWith("/")) pattern = `/${pattern}`;\n pattern = pattern.replace(/\\/+$/, "");\n for (let index = 0; index < pattern.length; index += 1) {\n const char = pattern[index];\n\n if (char === "*" && pattern[index + 1] === "*") {\n // "/blog/**" also matches "/blog" itself.\n if (source.endsWith("/")) source = `${source.slice(0, -1)}(?:/.*)?`;\n else source += ".*";\n index += 1;\n } else if (char === "*") source += "[^/]*";\n else if (char === "?") source += "[^/]";\n else source += String(char).replace(/[.+^${}()|[\\]\\\\]/g, "\\\\$&");\n }\n const regex = new RegExp(`^${source}/?$`);\n\n cache.set(glob, regex);\n return regex;\n}\n\n/**\n * @param {string} path The page\'s path, e.g. "/pricing/".\n * @param {string} glob\n */\nexport function matchGlob(path, glob) {\n const clean = path.split(/[?#]/)[0] || "/";\n\n return compile(glob).test(clean === "/" ? "/" : clean.replace(/\\/+$/, "")) || (glob.trim().replace(/\\/+$/, "") === "" && clean === "/");\n}\n\n/**\n * Whether a page is in an entry\'s scope: in `include` (or `include` is empty)\n * and not in `exclude`.\n *\n * @param {string} path\n * @param {{ include?: string[]; exclude?: string[] }} entry\n */\nexport function inScope(path, entry) {\n const included = !entry.include || entry.include.length === 0 || entry.include.some((glob) => matchGlob(path, glob));\n\n return included && !(entry.exclude ?? []).some((glob) => matchGlob(path, glob));\n}\n', "shared/markdown.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The little Markdown a form\'s texts may use \u2014 **bold**, *italic*, `code`\n// and [links](https://\u2026) \u2014 rendered to escaped HTML. Nothing else is\n// interpreted: no raw HTML, no images, no headings.\n//\n// `{{field}}` placeholders become `<span data-galley-value="field"></span>`;\n// the browser fills them with the visitor\'s answer as plain text after a\n// submission. They are never filled inside a link address, so an answer can\n// never become a link.\n\nconst ESCAPES = /** @type {Record<string, string>} */ ({ "&": "&", "<": "<", ">": ">", \'"\': """, "\'": "'" });\n\n/** @param {string} text */\nexport function escapeHtml(text) {\n return String(text).replace(/[&<>"\']/g, (char) => ESCAPES[char] ?? char);\n}\n\nconst PLACEHOLDER = /\\{\\{\\s*([a-z][a-z0-9_-]*)\\s*\\}\\}/g;\n\n/** Escaped text with `{{field}}` placeholders turned into fill-in spans. */\nfunction text(/** @type {string} */ raw) {\n return escapeHtml(raw).replace(PLACEHOLDER, (_, id) => `<span data-galley-value="${id}"></span>`);\n}\n\n/**\n * Only addresses that go somewhere ordinary: http(s), mail, phone, or a path\n * or anchor on this site. Anything else (javascript:, data:) becomes "#".\n *\n * @param {string} url\n */\nexport function safeUrl(url) {\n const value = url.trim();\n\n if (/^(https?:|mailto:|tel:)/i.test(value) || /^[/#?.]/.test(value)) return value;\n if (!/^[a-z][a-z0-9+.-]*:/i.test(value)) return value;\n return "#";\n}\n\n/**\n * A site-root address ("/privacy/") under the site\'s base path ("/docs" \u2192\n * "/docs/privacy/"), so links written from the site root keep working in a\n * sub-path build. Full addresses, protocol-relative ones, anchors and\n * addresses already under the base are left as they are.\n *\n * @param {string} url\n * @param {string} [base] e.g. "/docs" or "/docs/"; "" or "/" for none.\n */\nexport function withBase(url, base = "") {\n const prefix = base.replace(/\\/+$/, "");\n\n if (!prefix || !url.startsWith("/") || url.startsWith("//") || url === prefix || url.startsWith(`${prefix}/`)) return url;\n return `${prefix}${url}`;\n}\n\n/** @typedef {{ base?: string }} MarkdownOptions */\n\nconst INLINE = /\\*\\*([^*]+?)\\*\\*|\\*([^*\\s][^*]*?)\\*|`([^`]+)`|\\[([^\\]]+)\\]\\(([^)\\s]+)\\)/g;\n\n/**\n * One line (or a few) of inline Markdown as HTML.\n *\n * @param {string} source\n * @param {MarkdownOptions} [options] `base`: the site\'s base path, for links written from the site root.\n * @returns {string}\n */\nexport function inlineMarkdown(source, options = {}) {\n let out = "";\n let last = 0;\n\n for (const match of String(source).matchAll(INLINE)) {\n out += text(source.slice(last, match.index));\n const [, bold, italic, code, label, href] = match;\n\n if (bold !== undefined) out += `<strong>${inlineMarkdown(bold, options)}</strong>`;\n else if (italic !== undefined) out += `<em>${inlineMarkdown(italic, options)}</em>`;\n else if (code !== undefined) out += `<code>${escapeHtml(code)}</code>`;\n else if (label !== undefined && href !== undefined) {\n const url = withBase(safeUrl(href.replace(PLACEHOLDER, "")), options.base);\n const external = /^https?:/i.test(url);\n\n out += `<a href="${escapeHtml(url)}"${external ? \' rel="noopener"\' : ""}>${inlineMarkdown(label, options)}</a>`;\n }\n last = (match.index ?? 0) + match[0].length;\n }\n return out + text(source.slice(last));\n}\n\n/**\n * Paragraphs of inline Markdown: blank lines separate paragraphs, single\n * line breaks are kept.\n *\n * @param {string} source\n * @param {MarkdownOptions} [options]\n * @returns {string}\n */\nexport function markdownParagraphs(source, options = {}) {\n return String(source)\n .trim()\n .split(/\\n\\s*\\n/)\n .filter((part) => part.trim())\n .map((part) => `<p>${part.trim().split(/\\n/).map((line) => inlineMarkdown(line, options)).join("<br>")}</p>`)\n .join("");\n}\n\n/**\n * The plain words of a Markdown text \u2014 for a consent text sent to a provider\n * that records what the visitor agreed to.\n *\n * @param {string} source\n */\nexport function plainText(source) {\n return String(source)\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, "$1")\n .replace(/\\*\\*([^*]+)\\*\\*/g, "$1")\n .replace(/\\*([^*]+)\\*/g, "$1")\n .replace(/`([^`]+)`/g, "$1")\n .replace(/\\s+/g, " ")\n .trim();\n}\n', "scripts/banner.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The built-in consent banner: a small, non-modal region at the foot of the\n// page with three equal choices \u2014 accept all, reject all, choose \u2014 and the\n// categories this site actually uses. Server-rendered and hidden; the scripts\n// runtime shows it when no choice is stored, and again whenever an element\n// with `data-galley-consent-open` is clicked (a footer link, say).\n//\n// Every word comes from scripts.json \u2192 consent.banner, falling back to the\n// defaults below (written to brand/voice.md). Styled only through custom\n// properties, so a site themes it like its forms.\n\nimport { escapeHtml as esc, inlineMarkdown, withBase } from "../shared/markdown.js";\n\n/** @typedef {import("../kit").ConsentSettings} ConsentSettings */\n/** @typedef {import("../kit").ConsentCategory} ConsentCategory */\n\nexport const BANNER_DEFAULTS = Object.freeze({\n title: "Cookies and tracking",\n text: "This site would like to measure visits and the success of its marketing. Choose what it may use. You can change this at any time from the link at the bottom of each page.",\n acceptLabel: "Accept all",\n rejectLabel: "Reject all",\n settingsLabel: "Choose\u2026",\n saveLabel: "Save choices",\n policyLabel: "Privacy policy",\n});\n\nexport const CATEGORY_DEFAULTS = Object.freeze({\n necessary: { label: "Necessary", description: "Needed for the site to work. Always on." },\n analytics: { label: "Analytics", description: "Counts visits and shows which pages are used." },\n marketing: { label: "Marketing", description: "Measures ads and remembers visits for campaigns." },\n preferences: { label: "Preferences", description: "Remembers choices such as chat conversations." },\n});\n\n/**\n * @param {ConsentSettings} consent\n * @param {ConsentCategory[]} categories The optional categories the site uses, in order.\n * @param {{ base?: string }} [options] `base`: the site\'s base path, for a policyUrl or text links written from the site root.\n */\nexport function renderBanner(consent, categories, options = {}) {\n const base = options.base ?? "";\n const text = { ...BANNER_DEFAULTS, ...Object.fromEntries(Object.entries(consent.banner ?? {}).filter(([, value]) => typeof value === "string" && value)) };\n /** @param {ConsentCategory} category */\n const category = (category) => ({ ...CATEGORY_DEFAULTS[category], ...(consent.banner?.categories?.[category] ?? {}) });\n const rows = /** @type {ConsentCategory[]} */ (["necessary", ...categories])\n .map((name) => {\n const info = category(name);\n const id = `galley-consent-${name}`;\n\n return `<div class="galley-consent__category"><input type="checkbox" id="${id}"${name === "necessary" ? " checked disabled" : ` data-category="${name}"`}><label for="${id}"><span class="galley-consent__category-name">${esc(info.label)}</span> <span class="galley-consent__category-text">${esc(info.description)}</span></label></div>`;\n })\n .join("");\n const policy = consent.banner?.policyUrl ? ` <a href="${esc(withBase(consent.banner.policyUrl, base))}">${esc(text.policyLabel)}</a>` : "";\n\n return (\n `<section class="galley-consent" data-galley-consent aria-labelledby="galley-consent-title" hidden>` +\n `<div class="galley-consent__inner">` +\n `<p class="galley-consent__title" id="galley-consent-title">${esc(text.title)}</p>` +\n `<p class="galley-consent__text">${inlineMarkdown(text.text, { base })}${policy}</p>` +\n `<fieldset class="galley-consent__choices" id="galley-consent-choices" data-galley-consent-choices hidden><legend class="galley-visually-hidden">${esc(text.settingsLabel.replace(/\u2026$/, ""))}</legend>${rows}</fieldset>` +\n `<div class="galley-consent__actions">` +\n `<button type="button" class="galley-consent__button" data-galley-consent-accept>${esc(text.acceptLabel)}</button>` +\n `<button type="button" class="galley-consent__button" data-galley-consent-reject>${esc(text.rejectLabel)}</button>` +\n `<button type="button" class="galley-consent__button galley-consent__button--quiet" data-galley-consent-settings aria-expanded="false" aria-controls="galley-consent-choices">${esc(text.settingsLabel)}</button>` +\n `<button type="button" class="galley-consent__button" data-galley-consent-save hidden>${esc(text.saveLabel)}</button>` +\n `</div></div></section>`\n );\n}\n\n/*\n * Custom properties (with fallbacks):\n * --galley-consent-bg Canvas --galley-consent-text CanvasText\n * --galley-consent-border currentColor 25% --galley-consent-radius 0.5rem\n * --galley-consent-shadow a soft shadow --galley-consent-width 44rem\n * --galley-button-bg / --galley-button-text / --galley-button-radius (shared with forms;\n * CanvasText on Canvas when unset \u2014 never currentColor, which on a button\n * is its own text colour)\n * --galley-field-focus focus ring\n */\nexport const BANNER_CSS = `.galley-consent [hidden]{display:none!important}.galley-consent{position:fixed;inset-inline:0;inset-block-end:0;z-index:2147483000;display:flex;justify-content:center;padding:0.75rem;pointer-events:none}.galley-consent[hidden]{display:none}.galley-consent__inner{box-sizing:border-box;display:grid;gap:0.75rem;width:min(100%,var(--galley-consent-width,44rem));max-height:calc(100vh - 1.5rem);overflow:auto;padding:1rem 1.25rem;border:1px solid var(--galley-consent-border,color-mix(in srgb,currentColor 25%,transparent));border-radius:var(--galley-consent-radius,0.5rem);background:var(--galley-consent-bg,Canvas);color:var(--galley-consent-text,CanvasText);box-shadow:var(--galley-consent-shadow,0 8px 30px rgb(0 0 0 / 0.18));font:inherit;pointer-events:auto}.galley-consent__title{margin:0;font-weight:700}.galley-consent__text{margin:0}.galley-consent__text a{color:inherit}.galley-consent__choices{display:grid;gap:0.5rem;margin:0;padding:0;border:0}.galley-consent__category{display:grid;grid-template-columns:auto 1fr;gap:0.6rem;align-items:start}.galley-consent__category input{width:1.1em;height:1.1em;margin:0.2em 0 0;accent-color:var(--galley-field-focus,Highlight)}.galley-consent__category-name{font-weight:600}.galley-consent__actions{display:flex;flex-wrap:wrap;gap:0.5rem}.galley-consent__button{min-height:2.5rem;padding:0.5em 1em;border:1px solid var(--galley-button-bg,CanvasText);border-radius:var(--galley-button-radius,0.375rem);background:var(--galley-button-bg,CanvasText);color:var(--galley-button-text,Canvas);font:inherit;font-weight:600;cursor:pointer}.galley-consent__button--quiet{background:transparent;color:inherit}.galley-consent__button:focus-visible,.galley-consent input:focus-visible,.galley-consent a:focus-visible{outline:2px solid var(--galley-field-focus,Highlight);outline-offset:2px}.galley-visually-hidden{position:absolute!important;width:1px!important;height:1px!important;overflow:hidden!important;clip-path:inset(50%)!important;white-space:nowrap!important}`;\n', "scripts/plan.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// scripts.json \u2192 what one page gets, and the HTML for each place it goes.\n// Used by the integration\'s middleware (no template changes), by <Scripts />\n// for sites that place things themselves, by the build summary and by the\n// dev-only manifest at /__galley/scripts.json.\n//\n// Every snippet goes into the page inert \u2014 <script type="text/plain"> \u2014 and\n// only the inline runtime (runtime.js) turns it into a running script, after\n// checking consent, the load moment and whether the page is in the editor\'s\n// preview. <noscript> fallbacks are written only for scripts that need no\n// consent, because a page without JavaScript can\'t ask for it.\n\nimport { SCRIPT_INTEGRATIONS } from "../catalog-data.js";\nimport { inScope } from "../shared/glob.js";\nimport { BANNER_CSS, renderBanner } from "./banner.js";\nimport { RUNTIME } from "./runtime.gen.js";\nimport { buildSnippet } from "./snippets.js";\n\n/** @typedef {import("../kit").ScriptsConfig} ScriptsConfig */\n/** @typedef {import("../kit").ScriptEntry} ScriptEntry */\n/** @typedef {import("../kit").ConsentCategory} ConsentCategory */\n/** @typedef {import("./snippets.js").ScriptPart} ScriptPart */\n/** @typedef {"head" | "body-start" | "body-end"} Placement */\n\n/**\n * @typedef {object} ResolvedEntry\n * @property {ScriptEntry} entry\n * @property {string} name\n * @property {ConsentCategory} consent\n * @property {Placement} placement\n * @property {"eager" | "idle" | "interaction"} load\n * @property {ScriptPart[]} parts\n */\n\n/**\n * @typedef {object} PagePlan\n * @property {ResolvedEntry[]} entries The entries this page carries.\n * @property {boolean} runtime Whether the page needs the inline runtime at all.\n * @property {boolean} banner\n * @property {ConsentCategory[]} categories Optional categories used anywhere on the site.\n * @property {Record<string, unknown>} config The runtime\'s configuration.\n * @property {(category: ConsentCategory) => boolean} grantedByDefault\n */\n\nexport const PLACEMENTS = /** @type {const} */ (["head", "body-start", "body-end"]);\nconst ORDER = /** @type {ConsentCategory[]} */ (["analytics", "marketing", "preferences"]);\n\n/**\n * Every enabled entry with its consent, placement, load moment and parts.\n * Throws (a ScriptSettingsError) on an id that doesn\'t fit its integration.\n *\n * @param {ScriptsConfig} config\n * @returns {ResolvedEntry[]}\n */\nexport function resolveEntries(config) {\n return config.scripts\n .filter((entry) => entry.enabled)\n .map((entry) => {\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n\n return {\n entry,\n name: entry.label ?? info?.name ?? entry.kind,\n consent: entry.consent ?? info?.defaultConsent ?? "marketing",\n placement: entry.placement ?? info?.defaultPlacement ?? "body-end",\n load: entry.load ?? "eager",\n parts: buildSnippet(entry),\n };\n });\n}\n\n/**\n * @param {ScriptsConfig | null | undefined} config\n * @param {{ path: string; dev?: boolean; host?: string; utm?: boolean; resolved?: ResolvedEntry[] }} page\n * @returns {PagePlan}\n */\nexport function planPage(config, page) {\n const consent = config?.consent ?? { mode: "none" };\n const all = config ? page.resolved ?? resolveEntries(config) : [];\n const entries = all.filter(({ entry }) => inScope(page.path, entry) && (!page.dev || entry.inPreview === true));\n // UTM memory for forms is marketing attribution: under a consent mode it is\n // stored only once "marketing" is granted, so a site whose forms use it\n // offers Marketing in the banner even when no script needs it (docs/scripts.md).\n const categories = ORDER.filter((category) => all.some((item) => item.consent === category) || (category === "marketing" && Boolean(page.utm)));\n const defaults = consent.defaults ?? [];\n const grantedByDefault = (/** @type {ConsentCategory} */ category) => category === "necessary" || consent.mode === "none" || defaults.includes(category);\n const banner = consent.mode === "banner" && categories.length > 0;\n const runtime = entries.length > 0 || banner || Boolean(page.utm) || (consent.mode !== "none" && Boolean(consent.googleConsentMode));\n\n return {\n entries,\n runtime,\n banner,\n categories,\n grantedByDefault,\n config: { mode: consent.mode, defaults, gcm: Boolean(consent.googleConsentMode), host: page.host ?? "", utm: Boolean(page.utm) },\n };\n}\n\n/** Script text that can sit inside <script>\u2026</script> without ending it early. */\nconst scriptText = (/** @type {string} */ code) => code.replace(/<\\/(script)/gi, "<\\\\/$1").replace(/<!--/g, "<\\\\!--");\n/** @param {string} value */\nconst attr = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");\n\n/** The constant text of the runtime\'s inline script for this configuration. */\nexport function runtimeScript(/** @type {PagePlan} */ plan) {\n return `(${RUNTIME})(${JSON.stringify(plan.config)})`;\n}\n\n/** @param {Placement} placement */\nexport const runCall = (placement) => `galleyScripts.run("${placement}")`;\n\n/**\n * The HTML for one placement of one page ("" when it has nothing).\n *\n * @param {PagePlan} plan\n * @param {Placement} placement\n * @param {{ consent?: import("../kit").ConsentSettings; base?: string }} [extra] `base`: the site\'s base path.\n */\nexport function renderPlacement(plan, placement, extra = {}) {\n if (!plan.runtime) return "";\n let html = "";\n\n if (placement === "head") {\n html += `<script data-galley-scripts="head">${runtimeScript(plan)}</script>`;\n if (plan.banner) html += `<style data-galley-consent-style>${BANNER_CSS}</style>`;\n }\n let blocks = 0;\n\n for (const item of plan.entries) {\n for (const [index, part] of item.parts.entries()) {\n const at = part.placement ?? item.placement;\n\n if (at !== placement) continue;\n if (part.type === "noscript") {\n if (plan.grantedByDefault(item.consent)) html += `<noscript data-galley-script="${attr(item.entry.id)}">${part.html ?? ""}</noscript>`;\n continue;\n }\n blocks += 1;\n html +=\n `<script type="text/plain" data-galley-script="${attr(item.entry.id)}" data-part="${index}" data-placement="${placement}" data-consent="${item.consent}" data-load="${item.load}"` +\n (item.entry.inPreview ? " data-preview" : "") +\n (part.src ? ` data-src="${attr(part.src)}"` : "") +\n (part.attrs && Object.keys(part.attrs).length > 0 ? ` data-attrs="${attr(JSON.stringify(part.attrs))}"` : "") +\n `>${part.src ? "" : scriptText(part.code ?? "")}</script>`;\n }\n }\n if (placement === "body-end" && plan.banner && extra.consent) html += renderBanner(extra.consent, plan.categories, { base: extra.base });\n if (blocks > 0 || placement === "body-end") html += `<script data-galley-scripts="${placement}">${runCall(placement)}</script>`;\n return html;\n}\n\n/**\n * Puts each placement\'s HTML into a finished page: the head part right after\n * <meta charset> (else right after <head>), body-start right after <body>,\n * body-end before </body>. A placement the page already carries (because the\n * layout uses <Scripts />) is left alone.\n *\n * @param {string} html\n * @param {PagePlan} plan\n * @param {{ consent?: import("../kit").ConsentSettings; base?: string }} [extra]\n */\nexport function injectPlan(html, plan, extra = {}) {\n if (!plan.runtime) return html;\n let out = html;\n const has = (/** @type {Placement} */ placement) => out.includes(`data-galley-scripts="${placement}"`);\n\n if (!has("head")) {\n const head = renderPlacement(plan, "head", extra);\n const charset = /<meta[^>]+charset[^>]*>/i.exec(out);\n const headOpen = /<head\\b[^>]*>/i.exec(out);\n const at = charset && headOpen && charset.index > headOpen.index ? charset.index + charset[0].length : headOpen ? headOpen.index + headOpen[0].length : -1;\n\n if (at >= 0) out = out.slice(0, at) + head + out.slice(at);\n }\n if (!has("body-start")) {\n const start = renderPlacement(plan, "body-start", extra);\n const body = /<body\\b[^>]*>/i.exec(out);\n\n if (start && body) out = out.slice(0, body.index + body[0].length) + start + out.slice(body.index + body[0].length);\n }\n if (!has("body-end")) {\n // A layout that renders <ConsentBanner /> itself keeps its own.\n const end = renderPlacement(plan, "body-end", /data-galley-consent[\\s>]/.test(out) ? { base: extra.base } : extra);\n const close = out.toLowerCase().lastIndexOf("</body>");\n\n if (end) out = close >= 0 ? out.slice(0, close) + end + out.slice(close) : out + end;\n }\n return out;\n}\n\n/**\n * What the build log says: which scripts load on the site and under which\n * consent, one line each.\n *\n * @param {ScriptsConfig} config\n * @returns {string[]}\n */\nexport function summarize(config) {\n const consent = config.consent ?? { mode: "none" };\n const resolved = resolveEntries(config);\n const mode = consent.mode === "banner" ? "the built-in consent banner" : consent.mode === "external" ? "another consent tool (galleyConsent.set / Consent Mode / Cookiebot)" : "no consent step";\n const lines = [`scripts: ${resolved.length} of ${config.scripts.length} enabled \xB7 ${mode}${consent.googleConsentMode ? " \xB7 Google Consent Mode v2" : ""}`];\n\n for (const item of resolved) {\n const id = Object.values(item.entry.settings).find((value) => typeof value === "string" && /^[A-Za-z0-9-]{4,}$/.test(value));\n const when = item.consent === "necessary" || consent.mode === "none" ? "always" : `after ${item.consent} consent`;\n const where = item.entry.include?.length ? `only ${item.entry.include.join(", ")}` : "every page";\n const except = item.entry.exclude?.length ? ` except ${item.entry.exclude.join(", ")}` : "";\n\n lines.push(` \u2713 ${item.entry.id} \xB7 ${item.name}${id ? ` ${id}` : ""} \xB7 ${item.placement}, ${item.load} \xB7 ${when} \xB7 ${where}${except}`);\n }\n for (const entry of config.scripts.filter((item) => !item.enabled)) lines.push(` \u2013 ${entry.id} \xB7 off`);\n return lines;\n}\n\n/**\n * The dev-only manifest: what a given page would load in production.\n *\n * @param {ScriptsConfig | null} config\n * @param {string} path\n * @param {string} file The scripts file, relative to the site.\n */\nexport function manifest(config, path, file) {\n if (!config) return { file, exists: false, path, consent: { mode: "none" }, scripts: [] };\n const resolved = resolveEntries(config);\n\n return {\n file,\n exists: true,\n path,\n consent: config.consent ?? { mode: "none" },\n scripts: config.scripts.map((entry) => {\n const item = resolved.find((candidate) => candidate.entry === entry);\n const onPage = Boolean(item) && inScope(path, entry);\n\n return {\n id: entry.id,\n kind: entry.kind,\n label: item?.name ?? entry.label ?? entry.kind,\n enabled: entry.enabled,\n consent: item?.consent ?? entry.consent ?? null,\n placement: item?.placement ?? entry.placement ?? null,\n load: item?.load ?? entry.load ?? "eager",\n inPreview: entry.inPreview === true,\n loadsOnPage: onPage,\n reason: !entry.enabled ? "turned off" : onPage ? (item?.consent === "necessary" || (config.consent?.mode ?? "none") === "none" ? "loads" : `loads after ${item?.consent} consent`) : "not on this page (include/exclude)",\n inDev: onPage && entry.inPreview === true,\n };\n }),\n };\n}\n', "scripts/runtime.gen.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162733
163061
|
// Generated by scripts/build-inline.mjs from runtime.js \u2014 do not edit.
|
|
162734
163062
|
// @ts-check
|
|
162735
163063
|
/** The scripts runtime as one minified function expression, inlined into <head>. */
|
|
162736
163064
|
export const RUNTIME = "function(o){var r=window,f=document,q=\\"galley:consent\\",p=[\\"analytics\\",\\"marketing\\",\\"preferences\\"],n={necessary:!0},l=null,S=!1,I={},y=!1;try{S=r.top!==r}catch(e){S=!0}var E=/^galley-(preview|post-)/.test(r.name||\\"\\")||r.__galleyPreview===!0||f.documentElement.hasAttribute(\\"data-galley-preview\\")||S&&!!o.host&&location.hostname!==o.host;try{l=JSON.parse(localStorage.getItem(q)||\\"null\\")}catch(e){l=null}(!l||l.v!==1||o.mode!==\\"banner\\")&&(l=null),p.forEach(function(e){n[e]=o.mode===\\"none\\"||o.defaults.indexOf(e)>-1});var Y=JSON.parse(JSON.stringify(n));l&&p.forEach(function(e){n[e]=!!l.choice[e]});function A(e){var t=e.analytics?\\"granted\\":\\"denied\\",a=e.marketing?\\"granted\\":\\"denied\\",c=e.preferences?\\"granted\\":\\"denied\\";return{ad_storage:a,ad_user_data:a,ad_personalization:a,analytics_storage:t,functionality_storage:c,personalization_storage:c,security_storage:\\"granted\\"}}function k(){r.dataLayer.push(arguments)}if(o.gcm){r.dataLayer=r.dataLayer||[];var N=A(Y);o.mode===\\"external\\"&&(N.wait_for_update=500),y=!0,k(\\"consent\\",\\"default\\",N),l&&k(\\"consent\\",\\"update\\",A(n)),y=!1}function J(e){var t=e.getAttribute(\\"data-consent\\")||\\"marketing\\";return(t===\\"necessary\\"||n[t]===!0)&&(!E||e.hasAttribute(\\"data-preview\\"))}function D(e){if(!e.__galley){e.__galley=1;var t=f.createElement(\\"script\\"),a=JSON.parse(e.getAttribute(\\"data-attrs\\")||\\"{}\\");for(var c in a)t.setAttribute(c,a[c]===!0?\\"\\":a[c]);a.async===!0&&(t.async=!0);var s=e.getAttribute(\\"data-src\\");s?t.src=s:t.text=e.text,e.parentNode.insertBefore(t,e.nextSibling)}}var w=[],b=[],O=!1,L=!1;function z(e){e.splice(0).forEach(function(t){J(t)&&D(t)})}function F(){if(!O){O=!0;var e=function(){(r.requestIdleCallback||setTimeout)(function(){O=!1,z(w)})};f.readyState===\\"complete\\"?e():r.addEventListener(\\"load\\",e,{once:!0})}}function G(){if(!L){L=!0;var e=[\\"pointerdown\\",\\"keydown\\",\\"scroll\\",\\"touchstart\\"],t=function(){e.forEach(function(a){r.removeEventListener(a,t,!0)}),L=!1,z(b)};e.forEach(function(a){r.addEventListener(a,t,{capture:!0,passive:!0})})}}function j(e){if(!(e.__galley||!J(e))){var t=e.getAttribute(\\"data-load\\");t===\\"idle\\"?(w.indexOf(e)<0&&w.push(e),F()):t===\\"interaction\\"?(b.indexOf(e)<0&&b.push(e),G()):D(e)}}function P(e){return f.querySelectorAll('script[type=\\"text/plain\\"][data-galley-script]'+(e?'[data-placement=\\"'+e+'\\"]':\\"\\"))}function H(e){I[e]=1,Array.prototype.forEach.call(P(e),j),e===\\"body-end\\"&&h()}function Q(){Array.prototype.forEach.call(P(),function(e){I[e.getAttribute(\\"data-placement\\")]&&j(e)})}function R(){if(!(!o.utm||!(n.marketing||o.mode===\\"none\\")))try{var e=new URL(location.href),t={},a=!1;if([\\"utm_source\\",\\"utm_medium\\",\\"utm_campaign\\",\\"utm_term\\",\\"utm_content\\",\\"utm_id\\"].forEach(function(s){var u=e.searchParams.get(s);u&&(t[s]=u.slice(0,200),a=!0)}),!a)return;t.landing_page=e.origin+e.pathname,f.referrer&&(t.referrer=f.referrer.slice(0,500)),t.at=new Date().toISOString();var c=JSON.parse(localStorage.getItem(\\"galley:attribution\\")||\\"{}\\")||{};localStorage.setItem(\\"galley:attribution\\",JSON.stringify({first:c.first||t,last:t}))}catch(s){}}function d(e,t){if(p.forEach(function(a){a in e&&(n[a]=!!e[a])}),t){l={v:1,at:new Date().toISOString(),choice:{analytics:n.analytics,marketing:n.marketing,preferences:n.preferences}};try{localStorage.setItem(q,JSON.stringify(l))}catch(a){}}o.gcm&&(y=!0,k(\\"consent\\",\\"update\\",A(n)),y=!1),R();try{f.dispatchEvent(new CustomEvent(\\"galley:consent\\",{detail:B.get()}))}catch(a){}Q()}var i=null,v=null;function x(e){if(i){i.hidden=!1;var t=i.querySelectorAll(\\"input[data-category]\\");if(Array.prototype.forEach.call(t,function(c){c.checked=!!n[c.getAttribute(\\"data-category\\")]}),e){var a=i.querySelector(\\"button\\");a&&a.focus()}}}function m(){i&&(i.hidden=!0,v&&v.focus&&v.focus(),v=null)}function h(){if(!(i||o.mode!==\\"banner\\")&&(i=f.querySelector(\\"[data-galley-consent]\\"),!!i)){var e=i.querySelector(\\"[data-galley-consent-choices]\\"),t=i.querySelector(\\"[data-galley-consent-settings]\\"),a=i.querySelector(\\"[data-galley-consent-save]\\"),c=function(s){var u={};return p.forEach(function(g){u[g]=s}),u};i.addEventListener(\\"click\\",function(s){var u=s.target.closest?s.target.closest(\\"button\\"):null;if(u){if(u.hasAttribute(\\"data-galley-consent-accept\\"))d(c(!0),!0),m();else if(u.hasAttribute(\\"data-galley-consent-reject\\"))d(c(!1),!0),m();else if(u===t&&e){var g=e.hidden;if(e.hidden=!g,t.setAttribute(\\"aria-expanded\\",String(g)),a&&(a.hidden=!g),g){var K=e.querySelector(\\"input:not([disabled])\\");K&&K.focus()}}else if(u===a){var M={};Array.prototype.forEach.call(i.querySelectorAll(\\"input[data-category]\\"),function(U){M[U.getAttribute(\\"data-category\\")]=U.checked}),d(M,!0),m()}}}),i.addEventListener(\\"keydown\\",function(s){s.key===\\"Escape\\"&&l&&m()}),!l&&!E&&x(!1)}}if(f.addEventListener(\\"click\\",function(e){var t=e.target&&e.target.closest?e.target.closest(\\"[data-galley-consent-open]\\"):null;t&&(e.preventDefault(),h(),v=t,x(!0))}),o.mode===\\"external\\"){var V=function(){var e=r.Cookiebot&&r.Cookiebot.consent;e&&d({analytics:!!e.statistics,marketing:!!e.marketing,preferences:!!e.preferences},!1)};[\\"CookiebotOnConsentReady\\",\\"CookiebotOnAccept\\",\\"CookiebotOnDecline\\"].forEach(function(e){r.addEventListener(e,V)});var T=function(e){if(!(y||!e||e[0]!==\\"consent\\"||e[1]!==\\"update\\"||typeof e[2]!=\\"object\\")){var t=e[2],a={};\\"analytics_storage\\"in t&&(a.analytics=t.analytics_storage===\\"granted\\"),\\"ad_storage\\"in t&&(a.marketing=t.ad_storage===\\"granted\\"),(\\"functionality_storage\\"in t||\\"personalization_storage\\"in t)&&(a.preferences=(t.functionality_storage||t.personalization_storage)===\\"granted\\"),d(a,!1)}},_=r.dataLayer=r.dataLayer||[],W=_.push;Array.prototype.forEach.call(_,T),_.push=function(){var e=W.apply(_,arguments);return Array.prototype.forEach.call(arguments,T),e}}var B={mode:o.mode,preview:E,granted:function(e){return e===\\"necessary\\"||n[e]===!0},get:function(){return{necessary:!0,analytics:!!n.analytics,marketing:!!n.marketing,preferences:!!n.preferences}},set:function(e){d(e||{},o.mode===\\"banner\\")},open:function(){h(),x(!0)}};r.galleyConsent=B,r.galleyScripts={run:H},R(),f.addEventListener(\\"DOMContentLoaded\\",h)}";
|
|
162737
|
-
`, "scripts/snippets.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// One snippet builder per known integration, each written from the vendor\'s\n// current install code with only the ids from `settings` substituted (the\n// README lists the page each was checked against). A builder returns the\n// snippet as parts \u2014 scripts to load, inline code to run, <noscript>\n// fallbacks \u2014 and the runtime decides when each part may run (consent,\n// load strategy, preview). Ids are checked against the catalogue\'s patterns\n// first, so a wrong id is a build error with a plain message, never a broken\n// tag in the page.\n\nimport { SCRIPT_INTEGRATIONS } from "../catalog-data.js";\n\n/** @typedef {import("../kit").ScriptEntry} ScriptEntry */\n/**\n * @typedef {object} ScriptPart\n * @property {"script" | "noscript"} type\n * @property {string} [src] An external script.\n * @property {Record<string, string | true>} [attrs] Attributes for the <script> (async, defer, id, data-\u2026).\n * @property {string} [code] Inline code, run as written.\n * @property {string} [html] For "noscript": the fallback\'s inner HTML.\n * @property {"head" | "body-start" | "body-end"} [placement] When the part must sit somewhere else than its entry (GTM\'s frame).\n */\n\nexport class ScriptSettingsError extends Error {}\n\n/** @param {ScriptEntry} entry @param {string} key */\nfunction setting(entry, key) {\n const value = entry.settings[key];\n\n return value === undefined || value === null ? "" : String(value);\n}\n\n/**\n * Checks the entry\'s settings against its integration\'s patterns.\n *\n * @param {ScriptEntry} entry\n * @throws {ScriptSettingsError}\n */\nexport function checkSettings(entry) {\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n\n // A kind this kit has no builder for (one a plugin adds to the app\'s\n // catalogue) is written like "custom": from settings.src / settings.inline,\n // under the same consent and placement rules.\n if (!info) {\n if (!setting(entry, "src") && !setting(entry, "inline")) {\n throw new ScriptSettingsError(`\u201C${entry.id}\u201D is a \u201C${entry.kind}\u201D script, which this version of the kit can\'t write by itself. Give it settings.src (the script\'s address) or settings.inline (its code).`);\n }\n return;\n }\n for (const field of info.settings) {\n const value = setting(entry, field.key);\n\n if (!value) {\n if (field.required) throw new ScriptSettingsError(`\u201C${entry.id}\u201D (${info.name}) needs its ${field.label} in settings.${field.key}${field.placeholder ? `, like ${field.placeholder}` : ""}.`);\n continue;\n }\n if (field.pattern && !new RegExp(field.pattern).test(value)) {\n throw new ScriptSettingsError(`\u201C${entry.id}\u201D: \u201C${value}\u201D doesn\'t look like a ${info.name} ${field.label}${field.placeholder ? ` (it looks like ${field.placeholder})` : ""}.`);\n }\n }\n}\n\n/** @type {Record<string, (entry: ScriptEntry) => ScriptPart[]>} */\nexport const BUILDERS = {\n // support.google.com/tagmanager/answer/14847097 \u2014 the current one-part\n // snippet, plus (on request) the previous version\'s <noscript> frame.\n gtm(entry) {\n const id = setting(entry, "containerId");\n /** @type {ScriptPart[]} */\n const parts = [\n { type: "script", src: `https://www.googletagmanager.com/gtm.js?id=${id}`, attrs: { async: true } },\n { type: "script", code: "window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag(\'js\', new Date());" },\n ];\n\n if (setting(entry, "noscript") === "true") {\n parts.push({\n type: "noscript",\n placement: "body-start",\n html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${id}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,\n });\n }\n return parts;\n },\n\n // developers.google.com/tag-platform/gtagjs/install (+ /configure for the config command).\n ga4(entry) {\n const id = setting(entry, "measurementId");\n\n return [\n { type: "script", src: `https://www.googletagmanager.com/gtm.js?id=${id}`, attrs: { async: true } },\n { type: "script", code: `window.dataLayer = window.dataLayer || [];\\nfunction gtag(){dataLayer.push(arguments);}\\ngtag(\'js\', new Date());\\ngtag(\'config\', \'${id}\');` },\n ];\n },\n\n // developers.facebook.com/docs/meta-pixel/get-started \u2014 the base code.\n "meta-pixel"(entry) {\n const id = setting(entry, "pixelId");\n\n return [\n {\n type: "script",\n code: `!function(f,b,e,v,n,t,s)\\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version=\'2.0\';\\nn.queue=[];t=b.createElement(e);t.async=!0;\\nt.src=v;s=b.getElementsByTagName(e)[0];\\ns.parentNode.insertBefore(t,s)}(window, document,\'script\',\\n\'https://connect.facebook.net/en_US/fbevents.js\');\\nfbq(\'init\', \'${id}\');\\nfbq(\'track\', \'PageView\');`,\n },\n { type: "noscript", html: `<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=${id}&ev=PageView&noscript=1" alt="">` },\n ];\n },\n\n // The Insight Tag as Campaign Manager issues it (Signals manager \u203A Insight Tag).\n "linkedin-insight"(entry) {\n const id = setting(entry, "partnerId");\n\n return [\n { type: "script", code: `_linkedin_partner_id = "${id}";\\nwindow._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];\\nwindow._linkedin_data_partner_ids.push(_linkedin_partner_id);` },\n {\n type: "script",\n code: `(function(l) {\\nif (!l){window.lintrk = function(a,b){window.lintrk.q.push([a,b])};\\nwindow.lintrk.q=[]}\\nvar s = document.getElementsByTagName("script")[0];\\nvar b = document.createElement("script");\\nb.type = "text/javascript";b.async = true;\\nb.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";\\ns.parentNode.insertBefore(b, s);})(window.lintrk);`,\n },\n { type: "noscript", html: `<img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid=${id}&fmt=gif">` },\n ];\n },\n\n // The HubSpot embed code (Settings \u203A Tracking code), before </body>.\n hubspot(entry) {\n const id = setting(entry, "portalId");\n const region = setting(entry, "region");\n const host = region && region !== "na1" ? `js-${region}.hs-scripts.com` : "js.hs-scripts.com";\n\n return [{ type: "script", src: `//${host}/${id}.js`, attrs: { type: "text/javascript", id: "hs-script-loader", async: true, defer: true } }];\n },\n\n // experienceleague.adobe.com \u2026 /javascriptapi/leadtracking/lead-tracking \u2014 the asynchronous embed.\n "marketo-munchkin"(entry) {\n const id = setting(entry, "munchkinId");\n\n return [\n {\n type: "script",\n code: `(function() {\\n var didInit = false;\\n function initMunchkin() {\\n if(didInit === false) {\\n didInit = true;\\n Munchkin.init(\'${id}\');\\n }\\n }\\n var s = document.createElement(\'script\');\\n s.type = \'text/javascript\';\\n s.async = true;\\n s.src = \'//munchkin.marketo.net/munchkin.js\';\\n s.onreadystatechange = function() {\\n if (this.readyState == \'complete\' || this.readyState == \'loaded\') {\\n initMunchkin();\\n }\\n };\\n s.onload = initMunchkin;\\n document.getElementsByTagName(\'head\')[0].appendChild(s);\\n})();`,\n },\n ];\n },\n\n // plausible.io/docs/plausible-script \u2014 the per-site script (Oct 2025 on);\n // the older data-domain script for sites that give a domain instead.\n plausible(entry) {\n const host = (setting(entry, "host") || "https://plausible.io").replace(/\\/+$/, "");\n const scriptId = setting(entry, "scriptId");\n\n if (scriptId) {\n return [\n { type: "script", src: `${host}/js/${scriptId}.js`, attrs: { async: true } },\n { type: "script", code: "window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};\\nplausible.init()" },\n ];\n }\n return [{ type: "script", src: `${host}/js/script.js`, attrs: { defer: true, "data-domain": setting(entry, "domain") } }];\n },\n\n // twilio.com/docs/segment/connections/sources/catalog/libraries/website/javascript/quickstart \u2014 "Minified", snippet 5.2.1.\n segment(entry) {\n const key = setting(entry, "writeKey");\n\n return [\n {\n type: "script",\n code: `!function(){var i="analytics",analytics=window[i]=window[i]||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","screen","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware","register"];analytics.factory=function(e){return function(){if(window[i].initialized)return window[i][e].apply(window[i],arguments);var n=Array.prototype.slice.call(arguments);if(["track","screen","alias","group","page","identify"].indexOf(e)>-1){var c=document.querySelector("link[rel=\'canonical\']");n.push({__t:"bpc",c:c&&c.getAttribute("href")||void 0,p:location.pathname,u:location.href,s:location.search,t:document.title,r:document.referrer})}n.unshift(e);analytics.push(n);return analytics}};for(var n=0;n<analytics.methods.length;n++){var key=analytics.methods[n];analytics[key]=analytics.factory(key)}analytics.load=function(key,n){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.setAttribute("data-global-segment-analytics-key",i);t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(t,r);analytics._loadOptions=n};analytics._writeKey="${key}";;analytics.SNIPPET_VERSION="5.2.1";\\nanalytics.load("${key}");\\nanalytics.page();\\n}}();`,\n },\n ];\n },\n\n // The Hotjar Tracking Code (Sites & Organizations \u203A Tracking).\n hotjar(entry) {\n const id = setting(entry, "siteId");\n\n return [\n {\n type: "script",\n code: `(function(h,o,t,j,a,r){\\n h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};\\n h._hjSettings={hjid:${id},hjsv:6};\\n a=o.getElementsByTagName(\'head\')[0];\\n r=o.createElement(\'script\');r.async=1;\\n r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;\\n a.appendChild(r);\\n})(window,document,\'https://static.hotjar.com/c/hotjar-\',\'.js?sv=\');`,\n },\n ];\n },\n\n // The Clarity tracking code (Settings \u203A Setup \u203A Install manually).\n clarity(entry) {\n const id = setting(entry, "projectId");\n\n return [\n {\n type: "script",\n attrs: { type: "text/javascript" },\n code: `(function(c,l,a,r,i,t,y){\\n c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};\\n t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;\\n y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);\\n})(window, document, "clarity", "script", "${id}");`,\n },\n ];\n },\n\n // developers.intercom.com/installing-intercom/web/installation \u2014 for\n // visitors who aren\'t signed in (no user_id/email), with the regional API base.\n intercom(entry) {\n const id = setting(entry, "appId");\n const region = setting(entry, "region");\n const base = region === "eu" ? "https://api-iam.eu.intercom.io" : region === "au" ? "https://api-iam.au.intercom.io" : "https://api-iam.intercom.io";\n\n return [\n { type: "script", code: `window.intercomSettings = {\\n api_base: "${base}",\\n app_id: "${id}",\\n};` },\n {\n type: "script",\n code: `(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic(\'update\',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement(\'script\');s.type=\'text/javascript\';s.async=true;s.src=\'https://widget.intercom.io/widget/\' + "${id}";var x=d.getElementsByTagName(\'script\')[0];x.parentNode.insertBefore(s, x);};if(document.readyState===\'complete\'){l();}else if(w.attachEvent){w.attachEvent(\'onload\',l);}else{w.addEventListener(\'load\',l,false);}}})();`,\n },\n ];\n },\n\n custom(entry) {\n const src = setting(entry, "src");\n const code = setting(entry, "inline");\n const raw = entry.settings.attributes;\n /** @type {Record<string, string | true>} */\n const attrs = {};\n\n if (raw && typeof raw === "object" && !Array.isArray(raw)) {\n for (const [name, value] of Object.entries(raw)) if (value !== false && value !== null) attrs[name.toLowerCase()] = value === true ? true : String(value);\n }\n /** @type {ScriptPart[]} */\n const parts = [];\n\n if (src) parts.push({ type: "script", src, attrs });\n if (code) parts.push({ type: "script", code, ...(src ? {} : { attrs }) });\n return parts;\n },\n};\n\n/**\n * The snippet for one entry, after checking its settings.\n *\n * @param {ScriptEntry} entry\n * @returns {ScriptPart[]}\n */\nexport function buildSnippet(entry) {\n checkSettings(entry);\n const known = SCRIPT_INTEGRATIONS.some((item) => item.kind === entry.kind);\n const build = known ? BUILDERS[entry.kind] : BUILDERS.custom;\n\n if (!build) throw new ScriptSettingsError(`No snippet builder for \u201C${entry.kind}\u201D.`);\n return build(entry);\n}\n', "client/attribution.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163065
|
+
`, "scripts/snippets.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// One snippet builder per known integration, each written from the vendor\'s\n// current install code with only the ids from `settings` substituted (the\n// README lists the page each was checked against). A builder returns the\n// snippet as parts \u2014 scripts to load, inline code to run, <noscript>\n// fallbacks \u2014 and the runtime decides when each part may run (consent,\n// load strategy, preview). Ids are checked against the catalogue\'s patterns\n// first, so a wrong id is a build error with a plain message, never a broken\n// tag in the page.\n\nimport { SCRIPT_INTEGRATIONS } from "../catalog-data.js";\n\n/** @typedef {import("../kit").ScriptEntry} ScriptEntry */\n/**\n * @typedef {object} ScriptPart\n * @property {"script" | "noscript"} type\n * @property {string} [src] An external script.\n * @property {Record<string, string | true>} [attrs] Attributes for the <script> (async, defer, id, data-\u2026).\n * @property {string} [code] Inline code, run as written.\n * @property {string} [html] For "noscript": the fallback\'s inner HTML.\n * @property {"head" | "body-start" | "body-end"} [placement] When the part must sit somewhere else than its entry (GTM\'s frame).\n */\n\nexport class ScriptSettingsError extends Error {}\n\n/** @param {ScriptEntry} entry @param {string} key */\nfunction setting(entry, key) {\n const value = entry.settings[key];\n\n return value === undefined || value === null ? "" : String(value);\n}\n\n/**\n * Checks the entry\'s settings against its integration\'s patterns.\n *\n * @param {ScriptEntry} entry\n * @throws {ScriptSettingsError}\n */\nexport function checkSettings(entry) {\n const info = SCRIPT_INTEGRATIONS.find((item) => item.kind === entry.kind);\n\n // A kind this kit has no builder for (one a plugin adds to the app\'s\n // catalogue) is written like "custom": from settings.src / settings.inline,\n // under the same consent and placement rules.\n if (!info) {\n if (!setting(entry, "src") && !setting(entry, "inline")) {\n throw new ScriptSettingsError(`\u201C${entry.id}\u201D is a \u201C${entry.kind}\u201D script, which this version of the kit can\'t write by itself. Give it settings.src (the script\'s address) or settings.inline (its code).`);\n }\n return;\n }\n for (const field of info.settings) {\n const value = setting(entry, field.key);\n\n if (!value) {\n if (field.required) throw new ScriptSettingsError(`\u201C${entry.id}\u201D (${info.name}) needs its ${field.label} in settings.${field.key}${field.placeholder ? `, like ${field.placeholder}` : ""}.`);\n continue;\n }\n if (field.pattern && !new RegExp(field.pattern).test(value)) {\n throw new ScriptSettingsError(`\u201C${entry.id}\u201D: \u201C${value}\u201D doesn\'t look like a ${info.name} ${field.label}${field.placeholder ? ` (it looks like ${field.placeholder})` : ""}.`);\n }\n }\n}\n\n/** @type {Record<string, (entry: ScriptEntry) => ScriptPart[]>} */\nexport const BUILDERS = {\n // support.google.com/tagmanager/answer/14847097 \u2014 the current one-part\n // snippet, plus (on request) the previous version\'s <noscript> frame.\n gtm(entry) {\n const id = setting(entry, "containerId");\n /** @type {ScriptPart[]} */\n const parts = [\n { type: "script", src: `https://www.googletagmanager.com/gtm.js?id=${id}`, attrs: { async: true } },\n { type: "script", code: "window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag(\'js\', new Date());" },\n ];\n\n if (setting(entry, "noscript") === "true") {\n parts.push({\n type: "noscript",\n placement: "body-start",\n html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${id}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,\n });\n }\n return parts;\n },\n\n // developers.google.com/tag-platform/gtagjs/install (+ /configure for the config command).\n ga4(entry) {\n const id = setting(entry, "measurementId");\n\n return [\n { type: "script", src: `https://www.googletagmanager.com/gtm.js?id=${id}`, attrs: { async: true } },\n { type: "script", code: `window.dataLayer = window.dataLayer || [];\\nfunction gtag(){dataLayer.push(arguments);}\\ngtag(\'js\', new Date());\\ngtag(\'config\', \'${id}\');` },\n ];\n },\n\n // developers.facebook.com/docs/meta-pixel/get-started \u2014 the base code.\n "meta-pixel"(entry) {\n const id = setting(entry, "pixelId");\n\n return [\n {\n type: "script",\n code: `!function(f,b,e,v,n,t,s)\\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version=\'2.0\';\\nn.queue=[];t=b.createElement(e);t.async=!0;\\nt.src=v;s=b.getElementsByTagName(e)[0];\\ns.parentNode.insertBefore(t,s)}(window, document,\'script\',\\n\'https://connect.facebook.net/en_US/fbevents.js\');\\nfbq(\'init\', \'${id}\');\\nfbq(\'track\', \'PageView\');`,\n },\n { type: "noscript", html: `<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=${id}&ev=PageView&noscript=1" alt="">` },\n ];\n },\n\n // The Insight Tag as Campaign Manager issues it (Signals manager \u203A Insight Tag).\n "linkedin-insight"(entry) {\n const id = setting(entry, "partnerId");\n\n return [\n { type: "script", code: `_linkedin_partner_id = "${id}";\\nwindow._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];\\nwindow._linkedin_data_partner_ids.push(_linkedin_partner_id);` },\n {\n type: "script",\n code: `(function(l) {\\nif (!l){window.lintrk = function(a,b){window.lintrk.q.push([a,b])};\\nwindow.lintrk.q=[]}\\nvar s = document.getElementsByTagName("script")[0];\\nvar b = document.createElement("script");\\nb.type = "text/javascript";b.async = true;\\nb.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";\\ns.parentNode.insertBefore(b, s);})(window.lintrk);`,\n },\n { type: "noscript", html: `<img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid=${id}&fmt=gif">` },\n ];\n },\n\n // The HubSpot embed code (Settings \u203A Tracking code), before </body>.\n hubspot(entry) {\n const id = setting(entry, "portalId");\n const region = setting(entry, "region");\n const host = region && region !== "na1" ? `js-${region}.hs-scripts.com` : "js.hs-scripts.com";\n\n return [{ type: "script", src: `//${host}/${id}.js`, attrs: { type: "text/javascript", id: "hs-script-loader", async: true, defer: true } }];\n },\n\n // experienceleague.adobe.com \u2026 /javascriptapi/leadtracking/lead-tracking \u2014 the asynchronous embed.\n "marketo-munchkin"(entry) {\n const id = setting(entry, "munchkinId");\n\n return [\n {\n type: "script",\n code: `(function() {\\n var didInit = false;\\n function initMunchkin() {\\n if(didInit === false) {\\n didInit = true;\\n Munchkin.init(\'${id}\');\\n }\\n }\\n var s = document.createElement(\'script\');\\n s.type = \'text/javascript\';\\n s.async = true;\\n s.src = \'//munchkin.marketo.net/munchkin.js\';\\n s.onreadystatechange = function() {\\n if (this.readyState == \'complete\' || this.readyState == \'loaded\') {\\n initMunchkin();\\n }\\n };\\n s.onload = initMunchkin;\\n document.getElementsByTagName(\'head\')[0].appendChild(s);\\n})();`,\n },\n ];\n },\n\n // plausible.io/docs/plausible-script \u2014 the per-site script (Oct 2025 on);\n // the older data-domain script for sites that give a domain instead.\n plausible(entry) {\n const host = (setting(entry, "host") || "https://plausible.io").replace(/\\/+$/, "");\n const scriptId = setting(entry, "scriptId");\n\n if (scriptId) {\n return [\n { type: "script", src: `${host}/js/${scriptId}.js`, attrs: { async: true } },\n { type: "script", code: "window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};\\nplausible.init()" },\n ];\n }\n return [{ type: "script", src: `${host}/js/script.js`, attrs: { defer: true, "data-domain": setting(entry, "domain") } }];\n },\n\n // twilio.com/docs/segment/connections/sources/catalog/libraries/website/javascript/quickstart \u2014 "Minified", snippet 5.2.1.\n segment(entry) {\n const key = setting(entry, "writeKey");\n\n return [\n {\n type: "script",\n code: `!function(){var i="analytics",analytics=window[i]=window[i]||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","screen","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware","register"];analytics.factory=function(e){return function(){if(window[i].initialized)return window[i][e].apply(window[i],arguments);var n=Array.prototype.slice.call(arguments);if(["track","screen","alias","group","page","identify"].indexOf(e)>-1){var c=document.querySelector("link[rel=\'canonical\']");n.push({__t:"bpc",c:c&&c.getAttribute("href")||void 0,p:location.pathname,u:location.href,s:location.search,t:document.title,r:document.referrer})}n.unshift(e);analytics.push(n);return analytics}};for(var n=0;n<analytics.methods.length;n++){var key=analytics.methods[n];analytics[key]=analytics.factory(key)}analytics.load=function(key,n){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.setAttribute("data-global-segment-analytics-key",i);t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(t,r);analytics._loadOptions=n};analytics._writeKey="${key}";;analytics.SNIPPET_VERSION="5.2.1";\\nanalytics.load("${key}");\\nanalytics.page();\\n}}();`,\n },\n ];\n },\n\n // The Hotjar Tracking Code (Sites & Organizations \u203A Tracking).\n hotjar(entry) {\n const id = setting(entry, "siteId");\n\n return [\n {\n type: "script",\n code: `(function(h,o,t,j,a,r){\\n h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};\\n h._hjSettings={hjid:${id},hjsv:6};\\n a=o.getElementsByTagName(\'head\')[0];\\n r=o.createElement(\'script\');r.async=1;\\n r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;\\n a.appendChild(r);\\n})(window,document,\'https://static.hotjar.com/c/hotjar-\',\'.js?sv=\');`,\n },\n ];\n },\n\n // The Clarity tracking code (Settings \u203A Setup \u203A Install manually).\n clarity(entry) {\n const id = setting(entry, "projectId");\n\n return [\n {\n type: "script",\n attrs: { type: "text/javascript" },\n code: `(function(c,l,a,r,i,t,y){\\n c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};\\n t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;\\n y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);\\n})(window, document, "clarity", "script", "${id}");`,\n },\n ];\n },\n\n // developers.intercom.com/installing-intercom/web/installation \u2014 for\n // visitors who aren\'t signed in (no user_id/email), with the regional API base.\n intercom(entry) {\n const id = setting(entry, "appId");\n const region = setting(entry, "region");\n const base = region === "eu" ? "https://api-iam.eu.intercom.io" : region === "au" ? "https://api-iam.au.intercom.io" : "https://api-iam.intercom.io";\n\n return [\n { type: "script", code: `window.intercomSettings = {\\n api_base: "${base}",\\n app_id: "${id}",\\n};` },\n {\n type: "script",\n code: `(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic(\'update\',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement(\'script\');s.type=\'text/javascript\';s.async=true;s.src=\'https://widget.intercom.io/widget/\' + "${id}";var x=d.getElementsByTagName(\'script\')[0];x.parentNode.insertBefore(s, x);};if(document.readyState===\'complete\'){l();}else if(w.attachEvent){w.attachEvent(\'onload\',l);}else{w.addEventListener(\'load\',l,false);}}})();`,\n },\n ];\n },\n\n custom(entry) {\n const src = setting(entry, "src");\n const code = setting(entry, "inline");\n const raw = entry.settings.attributes;\n /** @type {Record<string, string | true>} */\n const attrs = {};\n\n if (raw && typeof raw === "object" && !Array.isArray(raw)) {\n for (const [name, value] of Object.entries(raw)) if (value !== false && value !== null) attrs[name.toLowerCase()] = value === true ? true : String(value);\n }\n /** @type {ScriptPart[]} */\n const parts = [];\n\n if (src) parts.push({ type: "script", src, attrs });\n if (code) parts.push({ type: "script", code, ...(src ? {} : { attrs }) });\n return parts;\n },\n};\n\n/**\n * The snippet for one entry, after checking its settings.\n *\n * @param {ScriptEntry} entry\n * @returns {ScriptPart[]}\n */\nexport function buildSnippet(entry) {\n checkSettings(entry);\n const known = SCRIPT_INTEGRATIONS.some((item) => item.kind === entry.kind);\n const build = known ? BUILDERS[entry.kind] : BUILDERS.custom;\n\n if (!build) throw new ScriptSettingsError(`No snippet builder for \u201C${entry.kind}\u201D.`);\n return build(entry);\n}\n', "client/attribution.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162738
163066
|
// @ts-check
|
|
162739
163067
|
// UTM memory for \`autofill: { from: "utm", touch }\`: the campaign parameters
|
|
162740
163068
|
// of the visitor's first landing and of their latest landing, kept in this
|
|
@@ -162813,7 +163141,7 @@ export function utmValue(key, touch = "last") {
|
|
|
162813
163141
|
if (remembered) return remembered;
|
|
162814
163142
|
return new URL(location.href).searchParams.get(key) ?? "";
|
|
162815
163143
|
}
|
|
162816
|
-
`, "client/forms.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The browser half of the forms: one module for every form on the page.\n// It finds each `.galley-form` the server rendered, then:\n// - validates inline and on submit, with an error summary that takes focus;\n// - shows and hides conditional fields (hidden ones are not sent);\n// - runs multi-step forms (per-step checks, progress, back/next keep answers);\n// - fills autofill fields (query, UTM first/last touch, referrer, page, cookie);\n// - sends to each destination through its provider, loaded only when a form\n// on the page uses it, and never clears what the visitor typed on failure;\n// - runs the after-submit actions and dispatches galley:form:* events.\n// Baseline: browsers with ES2020 modules, fetch, URL, CustomEvent and\n// `:focus-visible` \u2014 every evergreen browser since 2022.\n\nimport { applies, payloadFor, problem, shownFields, submittedValues } from "../forms/logic.js";\nimport { captureAttribution, utmValue } from "./attribution.js";\nimport { registerFormProvider, registeredProvider } from "./registry.js";\n\n/** @typedef {import("./types").ClientFormConfig} Config */\n/** @typedef {import("./types").SubmitResult} SubmitResult */\n/** @typedef {import("./types").Submitter} Submitter */\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n/** @typedef {{ [id: string]: string | string[] }} Values */\n\nexport const KIT_VERSION = "0.1.0";\n\n/** Built-in providers, each its own chunk. */\nconst BUILT_IN = /** @type {Record<string, () => Promise<{ submit: Submitter }>>} */ ({\n galley: () => import("./providers/galley.js"),\n hubspot: () => import("./providers/hubspot.js"),\n marketo: () => import("./providers/marketo.js"),\n salesforce: () => import("./providers/salesforce.js"),\n pardot: () => import("./providers/pardot.js"),\n webhook: () => import("./providers/webhook.js"),\n mailto: () => import("./providers/mailto.js"),\n});\n\n/** @param {string} id @returns {Promise<Submitter | undefined>} */\nasync function provider(id) {\n const own = registeredProvider(id);\n\n if (own) return own;\n const load = BUILT_IN[id];\n\n return load ? (await load()).submit : undefined;\n}\n\n/** @param {string} name @param {Element} target @param {object} detail @param {boolean} [cancelable] */\nfunction emit(name, target, detail, cancelable = false) {\n return target.dispatchEvent(new CustomEvent(name, { bubbles: true, cancelable, detail }));\n}\n\n/** @param {string} template @param {Record<string, string | number>} [values] */\nconst fill = (template, values = {}) => template.replace(/\\{(\\w+)\\}/g, (whole, key) => (key in values ? String(values[key]) : whole));\n\n/** @param {string} name */\nfunction cookie(name) {\n const match = document.cookie.split(/;\\s*/).find((part) => part.startsWith(`${name}=`));\n\n return match ? decodeURIComponent(match.slice(name.length + 1)) : "";\n}\n\n/** @param {FormField} field @returns {string} */\nfunction autofillValue(field) {\n const rule = field.autofill;\n\n if (!rule) return "";\n switch (rule.from) {\n case "query":\n return new URL(location.href).searchParams.get(rule.key ?? field.id) ?? "";\n case "utm":\n return utmValue(rule.key ?? field.id, rule.touch ?? "last");\n case "referrer":\n return document.referrer;\n case "page-url":\n return location.href;\n case "page-title":\n return document.title;\n case "cookie":\n return cookie(rule.key ?? field.id);\n }\n return "";\n}\n\nlet turnstileRequested = false;\n\nfunction loadTurnstile() {\n if (turnstileRequested) return;\n turnstileRequested = true;\n const script = document.createElement("script");\n\n script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";\n script.async = true;\n script.defer = true;\n document.head.append(script);\n}\n\n/** @param {HTMLElement} root */\nfunction setUp(root) {\n const configElement = root.querySelector("script[data-galley-form-config]");\n const found = root.querySelector("form");\n\n if (!configElement || !found) return;\n const form = found;\n /** @type {Config} */\n const config = JSON.parse(configElement.textContent || "{}");\n const messages = config.messages;\n const fields = config.fields;\n const byId = new Map(fields.map((field) => [field.id, field]));\n const startedAt = performance.now();\n const status = /** @type {HTMLElement} */ (root.querySelector("[data-galley-status]"));\n const summary = /** @type {HTMLElement} */ (root.querySelector(".galley-form__summary"));\n const success = /** @type {HTMLElement} */ (root.querySelector("[data-galley-success]"));\n const submitButton = /** @type {HTMLButtonElement | null} */ (form.querySelector(\'[type="submit"]\'));\n const nextButton = /** @type {HTMLButtonElement | null} */ (root.querySelector("[data-galley-next]"));\n const backButton = /** @type {HTMLButtonElement | null} */ (root.querySelector("[data-galley-back]"));\n const progress = /** @type {HTMLElement | null} */ (root.querySelector("[data-galley-progress]"));\n /** Fields the visitor has left at least once: they are checked as they type. */\n const touched = new Set();\n /** A destination\'s refusal stays on its field until the answer changes. */\n /** @type {Map<string, { message: string; value: string }>} */\n const refused = new Map();\n let step = 0;\n let sending = false;\n\n form.noValidate = true;\n root.setAttribute("data-galley-ready", "");\n\n /** @param {string} id */\n const wrapper = (id) => /** @type {HTMLElement | null} */ (form.querySelector(`[data-galley-field="${CSS.escape(id)}"]`));\n /** @param {string} id */\n const controls = (id) => {\n const at = wrapper(id);\n\n if (!at) return [];\n return /** @type {(HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement)[]} */ (at.matches("input") ? [at] : [...at.querySelectorAll("input, select, textarea")]);\n };\n\n /** @returns {Values} */\n function read() {\n /** @type {Values} */\n const values = {};\n\n for (const field of fields) {\n const list = controls(field.id);\n\n if (field.type === "checkboxes") values[field.id] = list.filter((input) => /** @type {HTMLInputElement} */ (input).checked).map((input) => input.value);\n else if (field.type === "radio") values[field.id] = list.find((input) => /** @type {HTMLInputElement} */ (input).checked)?.value ?? "";\n else if (field.type === "checkbox" || field.type === "consent") values[field.id] = /** @type {HTMLInputElement | undefined} */ (list[0])?.checked ? "true" : "";\n else if (list[0]) values[field.id] = list[0].value;\n }\n return values;\n }\n\n // \u2500\u2500 Autofill \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const field of fields) {\n if (!field.autofill) continue;\n const value = autofillValue(field);\n const control = controls(field.id)[0];\n\n if (value && control && (field.type === "hidden" || !control.value || field.autofill.from === "page-url")) control.value = value;\n }\n\n // \u2500\u2500 Conditions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n function applyConditions() {\n const shown = shownFields(fields, read());\n\n for (const at of /** @type {NodeListOf<HTMLElement>} */ (form.querySelectorAll("[data-galley-when]"))) {\n const id = at.getAttribute("data-galley-field") ?? "";\n const visible = shown.has(id);\n\n at.removeAttribute("data-galley-hidden");\n at.hidden = !visible;\n for (const control of at.querySelectorAll("input, select, textarea")) /** @type {HTMLInputElement} */ (control).disabled = !visible;\n }\n }\n\n // \u2500\u2500 Errors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {string} id @param {string} message */\n function showError(id, message) {\n const at = wrapper(id);\n const error = at?.querySelector("[data-galley-error]");\n\n if (!at || !error) return;\n error.textContent = message;\n /** @type {HTMLElement} */ (error).hidden = !message;\n at.toggleAttribute("data-invalid", Boolean(message));\n for (const control of controls(id)) {\n if (message) control.setAttribute("aria-invalid", "true");\n else control.removeAttribute("aria-invalid");\n }\n }\n\n /** @param {FormField} field @param {Values} values */\n const check = (field, values) => problem(field, values[field.id] ?? "", messages, config.freeEmailDomains);\n\n /** @param {string[]} ids @returns {{ id: string; message: string }[]} */\n function validate(ids) {\n const values = read();\n const shown = shownFields(fields, values);\n const found = [];\n\n for (const id of ids) {\n const field = byId.get(id);\n\n if (!field || !shown.has(id)) {\n showError(id, "");\n continue;\n }\n const value = JSON.stringify(values[id] ?? "");\n const kept = refused.get(id);\n const message = check(field, values) || (kept && kept.value === value ? kept.message : "");\n\n if (kept && kept.value !== value) refused.delete(id);\n showError(id, message);\n if (message) found.push({ id, message });\n }\n return found;\n }\n\n /** @param {{ id: string; message: string }[]} errors */\n function showSummary(errors) {\n const title = summary.querySelector(".galley-form__summary-title");\n const list = summary.querySelector(".galley-form__summary-list");\n\n if (!title || !list) return;\n if (errors.length === 0) {\n summary.hidden = true;\n return;\n }\n title.textContent = errors.length === 1 ? messages.summaryOne ?? "" : fill(messages.summaryMany ?? "", { count: errors.length });\n list.replaceChildren(\n ...errors.map(({ id, message }) => {\n const item = document.createElement("li");\n const link = document.createElement("a");\n const control = controls(id)[0];\n const label = byId.get(id)?.label;\n\n link.href = `#${control?.id ?? ""}`;\n link.textContent = label ? `${label}: ${message}` : message;\n link.addEventListener("click", (event) => {\n event.preventDefault();\n control?.focus();\n });\n item.append(link);\n return item;\n }),\n );\n summary.hidden = false;\n summary.focus();\n }\n\n /** @param {string} text @param {"error" | ""} [tone] */\n function say(text, tone = "") {\n status.textContent = text;\n if (tone) status.setAttribute("data-tone", tone);\n else status.removeAttribute("data-tone");\n }\n\n form.addEventListener("focusout", (event) => {\n const at = /** @type {HTMLElement} */ (event.target).closest?.("[data-galley-field]");\n const id = at?.getAttribute("data-galley-field");\n\n if (!id || at?.contains(/** @type {Node | null} */ (event.relatedTarget))) return;\n const values = read();\n const field = byId.get(id);\n\n if (field && (touched.has(id) || (values[id] ?? "") !== "")) {\n touched.add(id);\n validate([id]);\n }\n });\n form.addEventListener("input", (event) => {\n const id = /** @type {HTMLElement} */ (event.target).closest?.("[data-galley-field]")?.getAttribute("data-galley-field");\n\n applyConditions();\n if (id && wrapper(id)?.hasAttribute("data-invalid")) validate([id]);\n });\n form.addEventListener("change", applyConditions);\n\n // \u2500\u2500 Steps \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const stepElements = /** @type {HTMLElement[]} */ ([...form.querySelectorAll("[data-galley-step]")]);\n const stepOf = (/** @type {FormField} */ field) => Math.min(config.steps - 1, field.step ?? 0);\n\n /** @param {number} to @param {boolean} [focus] */\n function showStep(to, focus = true) {\n step = to;\n stepElements.forEach((element, index) => (element.hidden = index !== step));\n const last = step === config.steps - 1;\n\n if (progress) {\n progress.hidden = false;\n progress.textContent = fill(messages.step ?? "", { step: step + 1, total: config.steps });\n }\n if (backButton) backButton.hidden = step === 0;\n if (nextButton) {\n nextButton.hidden = last;\n nextButton.textContent = config.nextLabels?.[step] ?? nextButton.textContent;\n }\n if (submitButton) submitButton.hidden = !last;\n if (focus) {\n const current = stepElements[step];\n const target = /** @type {HTMLElement | null} */ (current?.querySelector(".galley-form__step-title") ?? current?.querySelector("input:not([type=hidden]), select, textarea"));\n\n target?.focus();\n }\n }\n\n function next() {\n const errors = validate(fields.filter((field) => stepOf(field) === step).map((field) => field.id));\n\n showSummary(errors);\n if (errors.length === 0) showStep(step + 1);\n }\n\n if (config.steps > 1) {\n showStep(0, false);\n nextButton?.addEventListener("click", next);\n backButton?.addEventListener("click", () => {\n showSummary([]);\n showStep(step - 1);\n });\n }\n\n applyConditions();\n if (config.spam.turnstile) loadTurnstile();\n // Warm the providers this form uses, so sending doesn\'t wait for them.\n const warm = () => config.destinations.forEach((destination) => provider(destination.provider).catch(() => undefined));\n\n if ("requestIdleCallback" in window) requestIdleCallback(warm, { timeout: 3000 });\n else setTimeout(warm, 1500);\n\n // \u2500\u2500 Sending \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {boolean} on */\n function busy(on) {\n sending = on;\n root.setAttribute("data-state", on ? "sending" : "idle");\n form.setAttribute("aria-busy", String(on));\n if (submitButton) submitButton.setAttribute("aria-disabled", String(on));\n }\n\n /** @param {FormDestination} destination @param {object} context */\n async function send(destination, context) {\n try {\n const submit = await provider(destination.provider);\n\n if (!submit) return { ok: false, detail: `No form provider called \u201C${destination.provider}\u201D is registered.` };\n const { values, items } = payloadFor(destination, fields, /** @type {Values} */ (/** @type {any} */ (context).answers));\n\n return /** @type {SubmitResult} */ (await submit(values, destination, { .../** @type {any} */ (context), items }));\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n }\n\n form.addEventListener("submit", async (event) => {\n event.preventDefault();\n if (sending) return;\n if (config.steps > 1 && step < config.steps - 1) {\n next();\n return;\n }\n say("");\n const all = validate(fields.map((field) => field.id));\n\n if (all.length > 0) {\n const firstStep = Math.min(...all.map(({ id }) => stepOf(/** @type {FormField} */ (byId.get(id)))));\n\n if (config.steps > 1 && firstStep !== step) showStep(firstStep, false);\n showSummary(all.filter(({ id }) => stepOf(/** @type {FormField} */ (byId.get(id))) === (config.steps > 1 ? firstStep : 0) || config.steps === 1));\n return;\n }\n showSummary([]);\n const honeypot = /** @type {HTMLInputElement | null} */ (form.querySelector("[data-galley-hp]"))?.value ?? "";\n const elapsedMs = Math.round(performance.now() - startedAt);\n const answers = submittedValues(fields, read());\n\n // A filled-in trap means a robot: it is shown the thank-you and nothing is sent.\n if (config.spam.honeypot && honeypot) {\n done(answers, []);\n return;\n }\n if (config.spam.minSeconds > 0 && elapsedMs < config.spam.minSeconds * 1000) {\n say(messages.tooFast ?? "", "error");\n status.focus();\n return;\n }\n const turnstileToken = /** @type {HTMLInputElement | null} */ (form.querySelector(\'[name="cf-turnstile-response"]\'))?.value || undefined;\n\n if (!emit("galley:form:submit", root, { form: config.id, values: answers }, true)) return;\n const targets = config.destinations.filter((destination) => applies(destination, answers, fields));\n\n if (targets.length === 0) {\n fail({ ok: false, notConnected: true, detail: "No destination applies to these answers." });\n return;\n }\n busy(true);\n say(messages.sending ?? "");\n const context = {\n formId: config.id,\n form,\n fields,\n answers,\n page: { url: location.href, title: document.title, referrer: document.referrer },\n meta: { elapsedMs, honeypot, turnstileToken, locale: navigator.language, kit: KIT_VERSION },\n messages,\n };\n const navigates = (/** @type {FormDestination} */ destination) => destination.settings.mode === "navigate" && (destination.provider === "salesforce" || destination.provider === "pardot");\n const inPage = targets.filter((destination) => !navigates(destination));\n const leaving = targets.filter(navigates);\n const pending = inPage.map((destination) => send(destination, context));\n const primary = targets[0];\n const primaryLeaves = primary ? navigates(primary) : false;\n const result = primaryLeaves ? { ok: true } : await /** @type {Promise<SubmitResult>} */ (pending[0]);\n\n // The others get a few seconds to finish before the page moves on.\n await Promise.race([Promise.allSettled(pending), new Promise((done) => setTimeout(done, 4000))]);\n if (!result.ok) {\n fail(result, primary);\n return;\n }\n const results = await Promise.all(pending.map((promise) => Promise.race([promise, Promise.resolve({ ok: false, detail: "still sending" })])));\n\n if (leaving.length > 0) {\n // A destination that takes the visitor away goes last; only actions that\n // don\'t need the page (events, webhooks) run first.\n runActions(answers, results, true);\n busy(false);\n for (const destination of leaving.slice(1)) void send(destination, context);\n await send(/** @type {FormDestination} */ (leaving[0]), context);\n return;\n }\n done(answers, results, result);\n });\n\n /** @param {SubmitResult} result @param {FormDestination} [destination] */\n function fail(result, destination) {\n busy(false);\n const errors = result.errors ?? {};\n const named = Object.entries(errors)\n .map(([name, message]) => {\n const field = fields.find((item) => item.id === name || destination?.mapping?.[item.id] === name || item.name === name);\n\n return field ? { id: field.id, message } : null;\n })\n .filter((item) => item !== null);\n\n const values = read();\n\n named.forEach(({ id, message }) => {\n refused.set(id, { message, value: JSON.stringify(values[id] ?? "") });\n showError(id, message);\n });\n const text = result.retry\n ? result.retryAfter\n ? result.retryAfter === 1\n ? messages.rateLimitedForOne\n : fill(messages.rateLimitedFor ?? "", { seconds: result.retryAfter })\n : messages.rateLimited\n : result.notConnected\n ? messages.notConnected\n : result.message || messages.error;\n\n say(text ?? "", "error");\n emit("galley:form:error", root, { form: config.id, detail: result.detail, errors });\n if (result.detail) console.warn(`[galley] The form \u201C${config.id}\u201D couldn\'t be sent: ${result.detail}`);\n if (named.length > 0) showSummary(named);\n else {\n status.tabIndex = -1;\n status.focus();\n }\n }\n\n /** @param {Values} answers @param {SubmitResult[]} results @param {SubmitResult} [primary] */\n function done(answers, results, primary) {\n busy(false);\n say("");\n const redirect = runActions(answers, results, false);\n const showsMessage = config.afterSubmit.some((action) => action.type === "message") || !redirect || (redirect.delaySeconds ?? 0) > 0;\n\n if (showsMessage) {\n for (const slot of success.querySelectorAll("[data-galley-value]")) {\n const value = answers[slot.getAttribute("data-galley-value") ?? ""];\n\n slot.textContent = Array.isArray(value) ? value.join(", ") : value ?? "";\n }\n form.hidden = true;\n success.hidden = false;\n success.setAttribute("role", "status");\n success.focus();\n root.setAttribute("data-state", "sent");\n }\n emit("galley:form:success", root, { form: config.id, values: answers, results, redirect: primary?.redirect });\n if (redirect) {\n const url = new URL(redirect.url, location.href);\n\n for (const id of redirect.passFields ?? []) {\n const value = answers[id];\n\n if (value !== undefined) url.searchParams.set(id, Array.isArray(value) ? value.join(",") : value);\n }\n if (!/^https?:$/.test(url.protocol)) return;\n setTimeout(() => location.assign(url.href), Math.max(150, (redirect.delaySeconds ?? 0) * 1000));\n }\n }\n\n /**\n * Runs the after-submit actions in order and returns the redirect (if any),\n * which the caller performs last so nothing after it is cut short.\n *\n * @param {Values} answers @param {SubmitResult[]} results @param {boolean} leaving\n */\n function runActions(answers, results, leaving) {\n /** @type {{ url: string; passFields?: string[]; delaySeconds?: number } | undefined} */\n let redirect;\n /** @param {string} text */\n const withAnswers = (text) =>\n text.replace(/\\{\\{\\s*([a-z][a-z0-9_-]*)\\s*\\}\\}/g, (_, id) => {\n const value = answers[id];\n\n return Array.isArray(value) ? value.join(", ") : value ?? "";\n });\n\n for (const action of config.afterSubmit) {\n try {\n switch (action.type) {\n case "redirect":\n if (!leaving) redirect = action;\n break;\n case "download":\n if (action.auto && !leaving) /** @type {HTMLAnchorElement | null} */ (success.querySelector(".galley-form__download a"))?.click();\n break;\n case "event": {\n /** @type {Record<string, string>} */\n const params = {};\n\n for (const [key, value] of Object.entries(action.params ?? {})) params[key] = withAnswers(value);\n const target = action.target ?? "dataLayer";\n\n if (target === "dataLayer") (window.dataLayer = window.dataLayer || []).push({ event: action.name, galley_form: config.id, ...params });\n else if (target === "gtag") window.gtag?.("event", action.name, params);\n else root.dispatchEvent(new CustomEvent(action.name, { bubbles: true, detail: { form: config.id, values: answers, params } }));\n break;\n }\n case "webhook": {\n const body = JSON.stringify({ form: config.id, values: answers, page: { url: location.href, title: document.title, referrer: document.referrer }, at: new Date().toISOString() });\n\n if (!navigator.sendBeacon?.(action.url, new Blob([body], { type: "text/plain;charset=UTF-8" }))) {\n void fetch(action.url, { method: "POST", body, keepalive: true, mode: "no-cors", headers: { "content-type": "text/plain;charset=UTF-8" } }).catch(() => undefined);\n }\n break;\n }\n case "script":\n // Present only when the site set forms.allowFormScripts (docs/forms.md).\n new Function("values", "form", "results", action.code)(structuredClone(answers), form, results);\n break;\n }\n } catch (error) {\n console.error(`[galley] An after-submit action of the form \u201C${config.id}\u201D failed:`, error);\n }\n }\n return redirect;\n }\n}\n\n/**\n * Starts every form under `root` that isn\'t running yet. Safe to call again\n * after new forms are added to the page.\n *\n * @param {ParentNode} [root]\n */\nexport function initForms(root = document) {\n captureAttribution();\n for (const element of /** @type {NodeListOf<HTMLElement>} */ (root.querySelectorAll(".galley-form:not([data-galley-ready])"))) setUp(element);\n}\n\nwindow.galleyForms = { registerProvider: registerFormProvider, init: initForms };\n\nexport { registerFormProvider };\n', "client/registry.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The one seam for adding a form destination: a submitter registered under a\n// provider id. Built-in providers load from ./providers/ on demand; a site or\n// plugin registers its own before (or after) the forms start:\n//\n// import { registerFormProvider } from "@galley/astro/client";\n// registerFormProvider("crm", async (values, destination, context) => {\n// const res = await fetch(String(destination.settings.url), { method: "POST", body: JSON.stringify(values) });\n// return res.ok ? { ok: true } : { ok: false, detail: `HTTP ${res.status}` };\n// });\n//\n// or, without a bundler: window.galleyForms.registerProvider("crm", fn).\n\n/** @typedef {import("./types").Submitter} Submitter */\n\n/** @type {Map<string, Submitter>} */\nconst registered = new Map();\n\n/**\n * @param {string} id The `provider` a destination names.\n * @param {Submitter} submitter\n */\nexport function registerFormProvider(id, submitter) {\n if (typeof submitter !== "function") throw new TypeError(`registerFormProvider("${id}") needs a function.`);\n registered.set(id, submitter);\n}\n\n/** @param {string} id */\nexport function registeredProvider(id) {\n return registered.get(id);\n}\n', "client/types.d.ts": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163144
|
+
`, "client/forms.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The browser half of the forms: one module for every form on the page.\n// It finds each `.galley-form` the server rendered, then:\n// - validates inline and on submit, with an error summary that takes focus;\n// - shows and hides conditional fields (hidden ones are not sent);\n// - runs multi-step forms (per-step checks, progress, back/next keep answers);\n// - fills autofill fields (query, UTM first/last touch, referrer, page, cookie);\n// - sends to each destination through its provider, loaded only when a form\n// on the page uses it, and never clears what the visitor typed on failure;\n// - runs the after-submit actions and dispatches galley:form:* events.\n// Baseline: browsers with ES2020 modules, fetch, URL, CustomEvent and\n// `:focus-visible` \u2014 every evergreen browser since 2022.\n\nimport { applies, payloadFor, problem, shownFields, submittedValues } from "../forms/logic.js";\nimport { captureAttribution, utmValue } from "./attribution.js";\nimport { registerFormProvider, registeredProvider } from "./registry.js";\n\n/** @typedef {import("./types").ClientFormConfig} Config */\n/** @typedef {import("./types").SubmitResult} SubmitResult */\n/** @typedef {import("./types").Submitter} Submitter */\n/** @typedef {import("../kit").FormField} FormField */\n/** @typedef {import("../kit").FormDestination} FormDestination */\n/** @typedef {{ [id: string]: string | string[] }} Values */\n\nexport const KIT_VERSION = "0.1.1";\n\n/** Built-in providers, each its own chunk. */\nconst BUILT_IN = /** @type {Record<string, () => Promise<{ submit: Submitter }>>} */ ({\n galley: () => import("./providers/galley.js"),\n hubspot: () => import("./providers/hubspot.js"),\n marketo: () => import("./providers/marketo.js"),\n salesforce: () => import("./providers/salesforce.js"),\n pardot: () => import("./providers/pardot.js"),\n webhook: () => import("./providers/webhook.js"),\n mailto: () => import("./providers/mailto.js"),\n});\n\n/** @param {string} id @returns {Promise<Submitter | undefined>} */\nasync function provider(id) {\n const own = registeredProvider(id);\n\n if (own) return own;\n const load = BUILT_IN[id];\n\n return load ? (await load()).submit : undefined;\n}\n\n/** @param {string} name @param {Element} target @param {object} detail @param {boolean} [cancelable] */\nfunction emit(name, target, detail, cancelable = false) {\n return target.dispatchEvent(new CustomEvent(name, { bubbles: true, cancelable, detail }));\n}\n\n/** @param {string} template @param {Record<string, string | number>} [values] */\nconst fill = (template, values = {}) => template.replace(/\\{(\\w+)\\}/g, (whole, key) => (key in values ? String(values[key]) : whole));\n\n/** @param {string} name */\nfunction cookie(name) {\n const match = document.cookie.split(/;\\s*/).find((part) => part.startsWith(`${name}=`));\n\n return match ? decodeURIComponent(match.slice(name.length + 1)) : "";\n}\n\n/** @param {FormField} field @returns {string} */\nfunction autofillValue(field) {\n const rule = field.autofill;\n\n if (!rule) return "";\n switch (rule.from) {\n case "query":\n return new URL(location.href).searchParams.get(rule.key ?? field.id) ?? "";\n case "utm":\n return utmValue(rule.key ?? field.id, rule.touch ?? "last");\n case "referrer":\n return document.referrer;\n case "page-url":\n return location.href;\n case "page-title":\n return document.title;\n case "cookie":\n return cookie(rule.key ?? field.id);\n }\n return "";\n}\n\nlet turnstileRequested = false;\n\nfunction loadTurnstile() {\n if (turnstileRequested) return;\n turnstileRequested = true;\n const script = document.createElement("script");\n\n script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";\n script.async = true;\n script.defer = true;\n document.head.append(script);\n}\n\n/** @param {HTMLElement} root */\nfunction setUp(root) {\n const configElement = root.querySelector("script[data-galley-form-config]");\n const found = root.querySelector("form");\n\n if (!configElement || !found) return;\n const form = found;\n /** @type {Config} */\n const config = JSON.parse(configElement.textContent || "{}");\n const messages = config.messages;\n const fields = config.fields;\n const byId = new Map(fields.map((field) => [field.id, field]));\n const startedAt = performance.now();\n const status = /** @type {HTMLElement} */ (root.querySelector("[data-galley-status]"));\n const summary = /** @type {HTMLElement} */ (root.querySelector(".galley-form__summary"));\n const success = /** @type {HTMLElement} */ (root.querySelector("[data-galley-success]"));\n const submitButton = /** @type {HTMLButtonElement | null} */ (form.querySelector(\'[type="submit"]\'));\n const nextButton = /** @type {HTMLButtonElement | null} */ (root.querySelector("[data-galley-next]"));\n const backButton = /** @type {HTMLButtonElement | null} */ (root.querySelector("[data-galley-back]"));\n const progress = /** @type {HTMLElement | null} */ (root.querySelector("[data-galley-progress]"));\n /** Fields the visitor has left at least once: they are checked as they type. */\n const touched = new Set();\n /** A destination\'s refusal stays on its field until the answer changes. */\n /** @type {Map<string, { message: string; value: string }>} */\n const refused = new Map();\n let step = 0;\n let sending = false;\n\n form.noValidate = true;\n root.setAttribute("data-galley-ready", "");\n\n /** @param {string} id */\n const wrapper = (id) => /** @type {HTMLElement | null} */ (form.querySelector(`[data-galley-field="${CSS.escape(id)}"]`));\n /** @param {string} id */\n const controls = (id) => {\n const at = wrapper(id);\n\n if (!at) return [];\n return /** @type {(HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement)[]} */ (at.matches("input") ? [at] : [...at.querySelectorAll("input, select, textarea")]);\n };\n\n /** @returns {Values} */\n function read() {\n /** @type {Values} */\n const values = {};\n\n for (const field of fields) {\n const list = controls(field.id);\n\n if (field.type === "checkboxes") values[field.id] = list.filter((input) => /** @type {HTMLInputElement} */ (input).checked).map((input) => input.value);\n else if (field.type === "radio") values[field.id] = list.find((input) => /** @type {HTMLInputElement} */ (input).checked)?.value ?? "";\n else if (field.type === "checkbox" || field.type === "consent") values[field.id] = /** @type {HTMLInputElement | undefined} */ (list[0])?.checked ? "true" : "";\n else if (list[0]) values[field.id] = list[0].value;\n }\n return values;\n }\n\n // \u2500\u2500 Autofill \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const field of fields) {\n if (!field.autofill) continue;\n const value = autofillValue(field);\n const control = controls(field.id)[0];\n\n if (value && control && (field.type === "hidden" || !control.value || field.autofill.from === "page-url")) control.value = value;\n }\n\n // \u2500\u2500 Conditions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n function applyConditions() {\n const shown = shownFields(fields, read());\n\n for (const at of /** @type {NodeListOf<HTMLElement>} */ (form.querySelectorAll("[data-galley-when]"))) {\n const id = at.getAttribute("data-galley-field") ?? "";\n const visible = shown.has(id);\n\n at.removeAttribute("data-galley-hidden");\n at.hidden = !visible;\n for (const control of at.querySelectorAll("input, select, textarea")) /** @type {HTMLInputElement} */ (control).disabled = !visible;\n }\n }\n\n // \u2500\u2500 Errors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {string} id @param {string} message */\n function showError(id, message) {\n const at = wrapper(id);\n const error = at?.querySelector("[data-galley-error]");\n\n if (!at || !error) return;\n error.textContent = message;\n /** @type {HTMLElement} */ (error).hidden = !message;\n at.toggleAttribute("data-invalid", Boolean(message));\n for (const control of controls(id)) {\n if (message) control.setAttribute("aria-invalid", "true");\n else control.removeAttribute("aria-invalid");\n }\n }\n\n /** @param {FormField} field @param {Values} values */\n const check = (field, values) => problem(field, values[field.id] ?? "", messages, config.freeEmailDomains);\n\n /** @param {string[]} ids @returns {{ id: string; message: string }[]} */\n function validate(ids) {\n const values = read();\n const shown = shownFields(fields, values);\n const found = [];\n\n for (const id of ids) {\n const field = byId.get(id);\n\n if (!field || !shown.has(id)) {\n showError(id, "");\n continue;\n }\n const value = JSON.stringify(values[id] ?? "");\n const kept = refused.get(id);\n const message = check(field, values) || (kept && kept.value === value ? kept.message : "");\n\n if (kept && kept.value !== value) refused.delete(id);\n showError(id, message);\n if (message) found.push({ id, message });\n }\n return found;\n }\n\n /** @param {{ id: string; message: string }[]} errors */\n function showSummary(errors) {\n const title = summary.querySelector(".galley-form__summary-title");\n const list = summary.querySelector(".galley-form__summary-list");\n\n if (!title || !list) return;\n if (errors.length === 0) {\n summary.hidden = true;\n return;\n }\n title.textContent = errors.length === 1 ? messages.summaryOne ?? "" : fill(messages.summaryMany ?? "", { count: errors.length });\n list.replaceChildren(\n ...errors.map(({ id, message }) => {\n const item = document.createElement("li");\n const link = document.createElement("a");\n const control = controls(id)[0];\n const label = byId.get(id)?.label;\n\n link.href = `#${control?.id ?? ""}`;\n link.textContent = label ? `${label}: ${message}` : message;\n link.addEventListener("click", (event) => {\n event.preventDefault();\n control?.focus();\n });\n item.append(link);\n return item;\n }),\n );\n summary.hidden = false;\n summary.focus();\n }\n\n /** @param {string} text @param {"error" | ""} [tone] */\n function say(text, tone = "") {\n status.textContent = text;\n if (tone) status.setAttribute("data-tone", tone);\n else status.removeAttribute("data-tone");\n }\n\n form.addEventListener("focusout", (event) => {\n const at = /** @type {HTMLElement} */ (event.target).closest?.("[data-galley-field]");\n const id = at?.getAttribute("data-galley-field");\n\n if (!id || at?.contains(/** @type {Node | null} */ (event.relatedTarget))) return;\n const values = read();\n const field = byId.get(id);\n\n if (field && (touched.has(id) || (values[id] ?? "") !== "")) {\n touched.add(id);\n validate([id]);\n }\n });\n form.addEventListener("input", (event) => {\n const id = /** @type {HTMLElement} */ (event.target).closest?.("[data-galley-field]")?.getAttribute("data-galley-field");\n\n applyConditions();\n if (id && wrapper(id)?.hasAttribute("data-invalid")) validate([id]);\n });\n form.addEventListener("change", applyConditions);\n\n // \u2500\u2500 Steps \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const stepElements = /** @type {HTMLElement[]} */ ([...form.querySelectorAll("[data-galley-step]")]);\n const stepOf = (/** @type {FormField} */ field) => Math.min(config.steps - 1, field.step ?? 0);\n\n /** @param {number} to @param {boolean} [focus] */\n function showStep(to, focus = true) {\n step = to;\n stepElements.forEach((element, index) => (element.hidden = index !== step));\n const last = step === config.steps - 1;\n\n if (progress) {\n progress.hidden = false;\n progress.textContent = fill(messages.step ?? "", { step: step + 1, total: config.steps });\n }\n if (backButton) backButton.hidden = step === 0;\n if (nextButton) {\n nextButton.hidden = last;\n nextButton.textContent = config.nextLabels?.[step] ?? nextButton.textContent;\n }\n if (submitButton) submitButton.hidden = !last;\n if (focus) {\n const current = stepElements[step];\n const target = /** @type {HTMLElement | null} */ (current?.querySelector(".galley-form__step-title") ?? current?.querySelector("input:not([type=hidden]), select, textarea"));\n\n target?.focus();\n }\n }\n\n function next() {\n const errors = validate(fields.filter((field) => stepOf(field) === step).map((field) => field.id));\n\n showSummary(errors);\n if (errors.length === 0) showStep(step + 1);\n }\n\n if (config.steps > 1) {\n showStep(0, false);\n nextButton?.addEventListener("click", next);\n backButton?.addEventListener("click", () => {\n showSummary([]);\n showStep(step - 1);\n });\n }\n\n applyConditions();\n if (config.spam.turnstile) loadTurnstile();\n // Warm the providers this form uses, so sending doesn\'t wait for them.\n const warm = () => config.destinations.forEach((destination) => provider(destination.provider).catch(() => undefined));\n\n if ("requestIdleCallback" in window) requestIdleCallback(warm, { timeout: 3000 });\n else setTimeout(warm, 1500);\n\n // \u2500\u2500 Sending \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {boolean} on */\n function busy(on) {\n sending = on;\n root.setAttribute("data-state", on ? "sending" : "idle");\n form.setAttribute("aria-busy", String(on));\n if (submitButton) submitButton.setAttribute("aria-disabled", String(on));\n }\n\n /** @param {FormDestination} destination @param {object} context */\n async function send(destination, context) {\n try {\n const submit = await provider(destination.provider);\n\n if (!submit) return { ok: false, detail: `No form provider called \u201C${destination.provider}\u201D is registered.` };\n const { values, items } = payloadFor(destination, fields, /** @type {Values} */ (/** @type {any} */ (context).answers));\n\n return /** @type {SubmitResult} */ (await submit(values, destination, { .../** @type {any} */ (context), items }));\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n }\n\n form.addEventListener("submit", async (event) => {\n event.preventDefault();\n if (sending) return;\n if (config.steps > 1 && step < config.steps - 1) {\n next();\n return;\n }\n say("");\n const all = validate(fields.map((field) => field.id));\n\n if (all.length > 0) {\n const firstStep = Math.min(...all.map(({ id }) => stepOf(/** @type {FormField} */ (byId.get(id)))));\n\n if (config.steps > 1 && firstStep !== step) showStep(firstStep, false);\n showSummary(all.filter(({ id }) => stepOf(/** @type {FormField} */ (byId.get(id))) === (config.steps > 1 ? firstStep : 0) || config.steps === 1));\n return;\n }\n showSummary([]);\n const honeypot = /** @type {HTMLInputElement | null} */ (form.querySelector("[data-galley-hp]"))?.value ?? "";\n const elapsedMs = Math.round(performance.now() - startedAt);\n const answers = submittedValues(fields, read());\n\n // A filled-in trap means a robot: it is shown the thank-you and nothing is sent.\n if (config.spam.honeypot && honeypot) {\n done(answers, []);\n return;\n }\n if (config.spam.minSeconds > 0 && elapsedMs < config.spam.minSeconds * 1000) {\n say(messages.tooFast ?? "", "error");\n status.focus();\n return;\n }\n const turnstileToken = /** @type {HTMLInputElement | null} */ (form.querySelector(\'[name="cf-turnstile-response"]\'))?.value || undefined;\n\n if (!emit("galley:form:submit", root, { form: config.id, values: answers }, true)) return;\n const targets = config.destinations.filter((destination) => applies(destination, answers, fields));\n\n if (targets.length === 0) {\n fail({ ok: false, notConnected: true, detail: "No destination applies to these answers." });\n return;\n }\n busy(true);\n say(messages.sending ?? "");\n const context = {\n formId: config.id,\n form,\n fields,\n answers,\n page: { url: location.href, title: document.title, referrer: document.referrer },\n meta: { elapsedMs, honeypot, turnstileToken, locale: navigator.language, kit: KIT_VERSION },\n messages,\n };\n const navigates = (/** @type {FormDestination} */ destination) => destination.settings.mode === "navigate" && (destination.provider === "salesforce" || destination.provider === "pardot");\n const inPage = targets.filter((destination) => !navigates(destination));\n const leaving = targets.filter(navigates);\n const pending = inPage.map((destination) => send(destination, context));\n const primary = targets[0];\n const primaryLeaves = primary ? navigates(primary) : false;\n const result = primaryLeaves ? { ok: true } : await /** @type {Promise<SubmitResult>} */ (pending[0]);\n\n // The others get a few seconds to finish before the page moves on.\n await Promise.race([Promise.allSettled(pending), new Promise((done) => setTimeout(done, 4000))]);\n if (!result.ok) {\n fail(result, primary);\n return;\n }\n const results = await Promise.all(pending.map((promise) => Promise.race([promise, Promise.resolve({ ok: false, detail: "still sending" })])));\n\n if (leaving.length > 0) {\n // A destination that takes the visitor away goes last; only actions that\n // don\'t need the page (events, webhooks) run first.\n runActions(answers, results, true);\n busy(false);\n for (const destination of leaving.slice(1)) void send(destination, context);\n await send(/** @type {FormDestination} */ (leaving[0]), context);\n return;\n }\n done(answers, results, result);\n });\n\n /** @param {SubmitResult} result @param {FormDestination} [destination] */\n function fail(result, destination) {\n busy(false);\n const errors = result.errors ?? {};\n const named = Object.entries(errors)\n .map(([name, message]) => {\n const field = fields.find((item) => item.id === name || destination?.mapping?.[item.id] === name || item.name === name);\n\n return field ? { id: field.id, message } : null;\n })\n .filter((item) => item !== null);\n\n const values = read();\n\n named.forEach(({ id, message }) => {\n refused.set(id, { message, value: JSON.stringify(values[id] ?? "") });\n showError(id, message);\n });\n const text = result.retry\n ? result.retryAfter\n ? result.retryAfter === 1\n ? messages.rateLimitedForOne\n : fill(messages.rateLimitedFor ?? "", { seconds: result.retryAfter })\n : messages.rateLimited\n : result.notConnected\n ? messages.notConnected\n : result.message || messages.error;\n\n say(text ?? "", "error");\n emit("galley:form:error", root, { form: config.id, detail: result.detail, errors });\n if (result.detail) console.warn(`[galley] The form \u201C${config.id}\u201D couldn\'t be sent: ${result.detail}`);\n if (named.length > 0) showSummary(named);\n else {\n status.tabIndex = -1;\n status.focus();\n }\n }\n\n /** @param {Values} answers @param {SubmitResult[]} results @param {SubmitResult} [primary] */\n function done(answers, results, primary) {\n busy(false);\n say("");\n const redirect = runActions(answers, results, false);\n const showsMessage = config.afterSubmit.some((action) => action.type === "message") || !redirect || (redirect.delaySeconds ?? 0) > 0;\n\n if (showsMessage) {\n for (const slot of success.querySelectorAll("[data-galley-value]")) {\n const value = answers[slot.getAttribute("data-galley-value") ?? ""];\n\n slot.textContent = Array.isArray(value) ? value.join(", ") : value ?? "";\n }\n form.hidden = true;\n success.hidden = false;\n success.setAttribute("role", "status");\n success.focus();\n root.setAttribute("data-state", "sent");\n }\n emit("galley:form:success", root, { form: config.id, values: answers, results, redirect: primary?.redirect });\n if (redirect) {\n const url = new URL(redirect.url, location.href);\n\n for (const id of redirect.passFields ?? []) {\n const value = answers[id];\n\n if (value !== undefined) url.searchParams.set(id, Array.isArray(value) ? value.join(",") : value);\n }\n if (!/^https?:$/.test(url.protocol)) return;\n setTimeout(() => location.assign(url.href), Math.max(150, (redirect.delaySeconds ?? 0) * 1000));\n }\n }\n\n /**\n * Runs the after-submit actions in order and returns the redirect (if any),\n * which the caller performs last so nothing after it is cut short.\n *\n * @param {Values} answers @param {SubmitResult[]} results @param {boolean} leaving\n */\n function runActions(answers, results, leaving) {\n /** @type {{ url: string; passFields?: string[]; delaySeconds?: number } | undefined} */\n let redirect;\n /** @param {string} text */\n const withAnswers = (text) =>\n text.replace(/\\{\\{\\s*([a-z][a-z0-9_-]*)\\s*\\}\\}/g, (_, id) => {\n const value = answers[id];\n\n return Array.isArray(value) ? value.join(", ") : value ?? "";\n });\n\n for (const action of config.afterSubmit) {\n try {\n switch (action.type) {\n case "redirect":\n if (!leaving) redirect = action;\n break;\n case "download":\n if (action.auto && !leaving) /** @type {HTMLAnchorElement | null} */ (success.querySelector(".galley-form__download a"))?.click();\n break;\n case "event": {\n /** @type {Record<string, string>} */\n const params = {};\n\n for (const [key, value] of Object.entries(action.params ?? {})) params[key] = withAnswers(value);\n const target = action.target ?? "dataLayer";\n\n if (target === "dataLayer") (window.dataLayer = window.dataLayer || []).push({ event: action.name, galley_form: config.id, ...params });\n else if (target === "gtag") window.gtag?.("event", action.name, params);\n else root.dispatchEvent(new CustomEvent(action.name, { bubbles: true, detail: { form: config.id, values: answers, params } }));\n break;\n }\n case "webhook": {\n const body = JSON.stringify({ form: config.id, values: answers, page: { url: location.href, title: document.title, referrer: document.referrer }, at: new Date().toISOString() });\n\n if (!navigator.sendBeacon?.(action.url, new Blob([body], { type: "text/plain;charset=UTF-8" }))) {\n void fetch(action.url, { method: "POST", body, keepalive: true, mode: "no-cors", headers: { "content-type": "text/plain;charset=UTF-8" } }).catch(() => undefined);\n }\n break;\n }\n case "script":\n // Present only when the site set forms.allowFormScripts (docs/forms.md).\n new Function("values", "form", "results", action.code)(structuredClone(answers), form, results);\n break;\n }\n } catch (error) {\n console.error(`[galley] An after-submit action of the form \u201C${config.id}\u201D failed:`, error);\n }\n }\n return redirect;\n }\n}\n\n/**\n * Starts every form under `root` that isn\'t running yet. Safe to call again\n * after new forms are added to the page.\n *\n * @param {ParentNode} [root]\n */\nexport function initForms(root = document) {\n captureAttribution();\n for (const element of /** @type {NodeListOf<HTMLElement>} */ (root.querySelectorAll(".galley-form:not([data-galley-ready])"))) setUp(element);\n}\n\nwindow.galleyForms = { registerProvider: registerFormProvider, init: initForms };\n\nexport { registerFormProvider };\n', "client/registry.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The one seam for adding a form destination: a submitter registered under a\n// provider id. Built-in providers load from ./providers/ on demand; a site or\n// plugin registers its own before (or after) the forms start:\n//\n// import { registerFormProvider } from "@galley/astro/client";\n// registerFormProvider("crm", async (values, destination, context) => {\n// const res = await fetch(String(destination.settings.url), { method: "POST", body: JSON.stringify(values) });\n// return res.ok ? { ok: true } : { ok: false, detail: `HTTP ${res.status}` };\n// });\n//\n// or, without a bundler: window.galleyForms.registerProvider("crm", fn).\n\n/** @typedef {import("./types").Submitter} Submitter */\n\n/** @type {Map<string, Submitter>} */\nconst registered = new Map();\n\n/**\n * @param {string} id The `provider` a destination names.\n * @param {Submitter} submitter\n */\nexport function registerFormProvider(id, submitter) {\n if (typeof submitter !== "function") throw new TypeError(`registerFormProvider("${id}") needs a function.`);\n registered.set(id, submitter);\n}\n\n/** @param {string} id */\nexport function registeredProvider(id) {\n return registered.get(id);\n}\n', "client/types.d.ts": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162817
163145
|
import type { FormAction, FormDestination, FormField } from "../kit";
|
|
162818
163146
|
|
|
162819
163147
|
/** What a submitter is given besides the values and the destination. */
|
|
@@ -162893,7 +163221,7 @@ declare global {
|
|
|
162893
163221
|
MktoForms2?: any;
|
|
162894
163222
|
}
|
|
162895
163223
|
}
|
|
162896
|
-
`, "visibility/config.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The visibility data file \u2014 src/data/visibility.json unless the\n// integration names another \u2014 read, checked and given its defaults. Every\n// part can be switched off; with no file at all a site gets the safe\n// defaults: markdown twins, llms.txt, llms-full.txt and the agent page on,\n// structured data where the page\'s own facts allow it, robots.txt and\n// sitemap.xml only when the site has none of its own, and no crawler\n// blocked.\n//\n// {\n// "site": { "name": "Ferrow", "summary": "One sentence about the site." },\n// "crawlers": { "GPTBot": "block", "OAI-SearchBot": "allow" },\n// "robots": { "disallow": ["/drafts/"] },\n// "sitemap": { "exclude": ["/thanks/"], "lastmod": "content" },\n// "structuredData": { "website": true, "organization": { "logo": "/images/logo.svg", "sameAs": [] },\n// "articles": ["blog"], "breadcrumbs": true },\n// "agentReadable": { "llmsTxt": true, "llmsFullTxt": true, "markdownTwins": true, "agentPage": true,\n// "optional": ["/privacy/"], "exclude": [], "contact": "hello@example.com" }\n// }\n\nimport { existsSync, readFileSync } from "node:fs";\nimport { join } from "node:path";\n\nexport const DEFAULT_FILE = "src/data/visibility.json";\n/** llms-full.txt stops before this many bytes. */\nexport const FULL_MAX_BYTES = 1_000_000;\n\n/**\n * @typedef {object} VisibilitySettings\n * @property {{ name: string; summary: string }} site\n * @property {Record<string, "allow" | "block">} crawlers\n * @property {{ enabled: boolean; disallow: string[]; allow: string[] }} robots\n * @property {{ enabled: boolean; exclude: string[]; lastmod: "content" | "none" }} sitemap\n * @property {{ website: boolean; organization: false | { name: string; logo: string; sameAs: string[]; email: string; telephone: string }; articles: "auto" | false | string[]; breadcrumbs: boolean }} structuredData\n * @property {{ llmsTxt: boolean; llmsFullTxt: boolean; markdownTwins: boolean; agentPage: boolean; optional: string[]; exclude: string[]; contact: string; fullMaxBytes: number }} agentReadable\n */\n\nexport class VisibilityFileError extends Error {}\n\n/** @returns {VisibilitySettings} */\nexport function defaultSettings() {\n return {\n site: { name: "", summary: "" },\n crawlers: {},\n robots: { enabled: true, disallow: [], allow: [] },\n sitemap: { enabled: true, exclude: [], lastmod: "content" },\n structuredData: { website: true, organization: { name: "", logo: "", sameAs: [], email: "", telephone: "" }, articles: "auto", breadcrumbs: true },\n agentReadable: { llmsTxt: true, llmsFullTxt: true, markdownTwins: true, agentPage: true, optional: [], exclude: [], contact: "", fullMaxBytes: FULL_MAX_BYTES },\n };\n}\n\n/** A robots.txt product token (RFC 9309: letters, "_" and "-"); digits are accepted as crawlers use them. */\nconst TOKEN = /^[A-Za-z0-9_-]+$/;\n\n/**\n * The file\'s contents with defaults applied. Throws a VisibilityFileError\n * listing every problem, in plain words, when something can\'t be used.\n *\n * @param {unknown} raw\n * @param {string} [file] For the messages.\n * @returns {VisibilitySettings}\n */\nexport function normalizeSettings(raw, file = DEFAULT_FILE) {\n const out = defaultSettings();\n /** @type {string[]} */\n const problems = [];\n\n if (raw === undefined || raw === null) return out;\n if (typeof raw !== "object" || Array.isArray(raw)) throw new VisibilityFileError(`${file} must hold an object, like { "crawlers": { "GPTBot": "block" } }.`);\n const data = /** @type {Record<string, unknown>} */ (raw);\n const known = new Set(["$schema", "site", "crawlers", "robots", "sitemap", "structuredData", "agentReadable"]);\n\n for (const key of Object.keys(data)) if (!known.has(key)) problems.push(`\u201C${key}\u201D isn\'t a setting this kit knows (it reads site, crawlers, robots, sitemap, structuredData and agentReadable).`);\n /** @param {unknown} value @param {string} at */\n const section = (value, at) => {\n if (value === undefined) return null;\n if (value === false) return false;\n if (value === true) return {};\n if (typeof value === "object" && value !== null && !Array.isArray(value)) return /** @type {Record<string, unknown>} */ (value);\n problems.push(`${at} should be an object of settings, or false to turn it off.`);\n return null;\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at @param {boolean} fallback */\n const bool = (from, key, at, fallback) => {\n const value = from[key];\n\n if (value === undefined) return fallback;\n if (typeof value === "boolean") return value;\n problems.push(`${at}.${key} should be true or false.`);\n return fallback;\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at */\n const text = (from, key, at) => {\n const value = from[key];\n\n if (value === undefined || value === null) return "";\n if (typeof value === "string") return value.trim();\n problems.push(`${at}.${key} should be text.`);\n return "";\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at @param {boolean} [paths] */\n const list = (from, key, at, paths = false) => {\n const value = from[key];\n\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {\n problems.push(`${at}.${key} should be a list of ${paths ? "addresses on the site, like \\"/thanks/\\"" : "texts"}.`);\n return [];\n }\n const items = /** @type {string[]} */ (value).map((item) => item.trim()).filter(Boolean);\n\n if (paths) for (const item of items) if (!item.startsWith("/")) problems.push(`${at}.${key}: \u201C${item}\u201D should start with \u201C/\u201D (an address on the site, without the domain).`);\n return items;\n };\n\n const site = section(data.site, "site");\n\n if (site) out.site = { name: text(site, "name", "site"), summary: text(site, "summary", "site") };\n\n if (data.crawlers !== undefined) {\n if (typeof data.crawlers !== "object" || data.crawlers === null || Array.isArray(data.crawlers)) problems.push(\'crawlers should map a crawler\\\'s name to "allow" or "block", like { "GPTBot": "block" }.\');\n else {\n for (const [token, choice] of Object.entries(data.crawlers)) {\n if (!TOKEN.test(token)) problems.push(`crawlers: \u201C${token}\u201D isn\'t a crawler name robots.txt can use (letters, digits, \u201C-\u201D and \u201C_\u201D only).`);\n else if (choice !== "allow" && choice !== "block") problems.push(`crawlers.${token} should be "allow" or "block".`);\n else out.crawlers[token] = choice;\n }\n }\n }\n\n const robots = section(data.robots, "robots");\n\n if (robots === false) out.robots.enabled = false;\n else if (robots) out.robots = { enabled: bool(robots, "enabled", "robots", true), disallow: list(robots, "disallow", "robots", true), allow: list(robots, "allow", "robots", true) };\n\n const sitemap = section(data.sitemap, "sitemap");\n\n if (sitemap === false) out.sitemap.enabled = false;\n else if (sitemap) {\n const lastmod = sitemap.lastmod ?? "content";\n\n if (lastmod !== "content" && lastmod !== "none") problems.push(\'sitemap.lastmod should be "content" (dates the pages state) or "none".\');\n out.sitemap = { enabled: bool(sitemap, "enabled", "sitemap", true), exclude: list(sitemap, "exclude", "sitemap", true), lastmod: lastmod === "none" ? "none" : "content" };\n }\n\n const structured = section(data.structuredData, "structuredData");\n\n if (structured === false) out.structuredData = { website: false, organization: false, articles: false, breadcrumbs: false };\n else if (structured) {\n const organization = section(structured.organization, "structuredData.organization");\n const articles = structured.articles;\n\n out.structuredData = {\n website: bool(structured, "website", "structuredData", true),\n organization:\n organization === false\n ? false\n : {\n name: organization ? text(organization, "name", "structuredData.organization") : "",\n logo: organization ? text(organization, "logo", "structuredData.organization") : "",\n sameAs: organization ? list(organization, "sameAs", "structuredData.organization") : [],\n email: organization ? text(organization, "email", "structuredData.organization") : "",\n telephone: organization ? text(organization, "telephone", "structuredData.organization") : "",\n },\n articles: articles === undefined || articles === true || articles === "auto" ? "auto" : articles === false ? false : Array.isArray(articles) && articles.every((item) => typeof item === "string") ? articles.map((item) => item.trim()).filter(Boolean) : "auto",\n breadcrumbs: bool(structured, "breadcrumbs", "structuredData", true),\n };\n if (!(articles === undefined || typeof articles === "boolean" || articles === "auto" || (Array.isArray(articles) && articles.every((item) => typeof item === "string")))) {\n problems.push(\'structuredData.articles should list collections (like ["blog"]) or addresses (like ["/news/*"]), or be "auto" or false.\');\n }\n if (out.structuredData.organization) {\n for (const link of out.structuredData.organization.sameAs) if (!/^https?:\\/\\/\\S+$/i.test(link)) problems.push(`structuredData.organization.sameAs: \u201C${link}\u201D should be a full address starting with https://.`);\n const logo = out.structuredData.organization.logo;\n\n if (logo && !logo.startsWith("/") && !/^https?:\\/\\//i.test(logo)) problems.push(`structuredData.organization.logo: \u201C${logo}\u201D should be an address on the site (like "/images/logo.png") or a full address.`);\n }\n }\n\n const agent = section(data.agentReadable, "agentReadable");\n\n if (agent === false) out.agentReadable = { ...out.agentReadable, llmsTxt: false, llmsFullTxt: false, markdownTwins: false, agentPage: false };\n else if (agent) {\n const max = agent.fullMaxBytes;\n\n if (max !== undefined && (typeof max !== "number" || !Number.isInteger(max) || max < 10_000)) problems.push("agentReadable.fullMaxBytes should be a whole number of bytes, at least 10000.");\n out.agentReadable = {\n llmsTxt: bool(agent, "llmsTxt", "agentReadable", true),\n llmsFullTxt: bool(agent, "llmsFullTxt", "agentReadable", true),\n markdownTwins: bool(agent, "markdownTwins", "agentReadable", true),\n agentPage: bool(agent, "agentPage", "agentReadable", true),\n optional: list(agent, "optional", "agentReadable", true),\n exclude: list(agent, "exclude", "agentReadable", true),\n contact: text(agent, "contact", "agentReadable"),\n fullMaxBytes: typeof max === "number" && Number.isInteger(max) && max >= 10_000 ? max : FULL_MAX_BYTES,\n };\n }\n if (problems.length) {\n throw new VisibilityFileError(`${file} has ${problems.length === 1 ? "a problem" : `${problems.length} problems`}:\\n${problems.map((line) => ` - ${line}`).join("\\n")}`);\n }\n return out;\n}\n\n/**\n * The site\'s visibility file, read and checked (defaults when there is none).\n *\n * @param {string} root The site\'s folder.\n * @param {string} [file]\n * @returns {{ settings: VisibilitySettings; exists: boolean }}\n */\nexport function readSettings(root, file = DEFAULT_FILE) {\n const path = join(root, file);\n\n if (!existsSync(path)) return { settings: defaultSettings(), exists: false };\n let raw;\n\n try {\n raw = JSON.parse(readFileSync(path, "utf8"));\n } catch (error) {\n throw new VisibilityFileError(`${file} can\'t be read as JSON (${error instanceof Error ? error.message : String(error)}). Fix the file, or remove it to use the defaults.`);\n }\n return { settings: normalizeSettings(raw, file), exists: true };\n}\n', "visibility/content.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// What the site\'s content files say that a rendered page can\'t: which\n// collection a page belongs to (for "articles": ["blog"]), which entries\n// are drafts (so a dev server that shows drafts still never lists them), and\n// each entry\'s date, for a page whose HTML doesn\'t state it.\n//\n// Addresses come from galley.config.json\'s collection `url` patterns when\n// the site has one ("/blog/{slug}/"), else the folder name ("/blog/{slug}/";\n// "pages" is "/{slug}/"). Drafts are entries whose front matter (or JSON /\n// YAML) sets the collection\'s draft field \u2014 "draft" unless galley.config.json\n// names another \u2014 to true. Dates come from the collection\'s dateField in\n// galley.config.json, else `date`, `pubDate`, `publishDate` or `published`,\n// written as an ISO date ("2026-08-20", "2026-08-20T09:00:00Z"). Read with\n// plain text matching, so the kit needs no YAML parser; a field written some\n// other way is simply not seen.\n\nimport { existsSync, readdirSync, readFileSync, statSync } from "node:fs";\nimport { join, relative } from "node:path";\n\n/**\n * @typedef {object} SiteContent\n * @property {string} name galley.config.json\'s `name`, when there is one.\n * @property {Record<string, string>} patterns collection id \u2192 address pattern, e.g. "/blog/{slug}/".\n * @property {string[]} drafts Addresses (without the base) of draft entries.\n * @property {Record<string, string>} dates Address (without the base) \u2192 the entry\'s date, as written.\n */\n\nconst ENTRY = /\\.(md|mdx|markdown|mdoc|json|ya?ml)$/i;\n\n/** @param {string} dir @returns {string[]} */\nfunction files(dir) {\n /** @type {string[]} */\n const out = [];\n /** @param {string} at */\n const walk = (at) => {\n for (const name of readdirSync(at).sort()) {\n if (name.startsWith(".") || name.startsWith("_")) continue;\n const path = join(at, name);\n const info = statSync(path);\n\n if (info.isDirectory()) walk(path);\n else if (ENTRY.test(name)) out.push(path);\n }\n };\n\n walk(dir);\n return out;\n}\n\n/** Whether a content file sets `field` to true. */\nexport function isDraft(/** @type {string} */ text, /** @type {string} */ file, field = "draft") {\n const key = field.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n\n if (/\\.json$/i.test(file)) {\n try {\n const data = JSON.parse(text);\n\n return Boolean(data && typeof data === "object" && data[field] === true);\n } catch {\n return false;\n }\n }\n const yaml = /\\.ya?ml$/i.test(file) ? text : /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/.exec(text)?.[1] ?? "";\n\n return new RegExp(`^${key}\\\\s*:\\\\s*(true|yes|on)\\\\s*(#.*)?$`, "mi").test(yaml);\n}\n\nconst DATE_KEYS = ["date", "pubDate", "publishDate", "published"];\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(?:[T ][\\d:.]+(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/** The entry\'s date, as written, when it is an ISO date. */\nexport function entryDate(/** @type {string} */ text, /** @type {string} */ file, /** @type {string[]} */ keys) {\n if (/\\.json$/i.test(file)) {\n try {\n const data = JSON.parse(text);\n\n for (const key of keys) if (typeof data?.[key] === "string" && ISO_DATE.test(data[key].trim())) return data[key].trim();\n } catch {\n return "";\n }\n return "";\n }\n const yaml = /\\.ya?ml$/i.test(file) ? text : /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/.exec(text)?.[1] ?? "";\n\n for (const key of keys) {\n const match = new RegExp(`^${key.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")}\\\\s*:\\\\s*["\']?([^"\'#\\\\r\\\\n]+?)["\']?\\\\s*(#.*)?$`, "m").exec(yaml);\n const value = match?.[1]?.trim() ?? "";\n\n if (ISO_DATE.test(value)) return value;\n }\n return "";\n}\n\n/** An entry\'s slug from its file: "blog/first-post.md" \u2192 "first-post"; "guides/setup/index.md" \u2192 "guides/setup". */\nfunction slugOf(/** @type {string} */ path) {\n const bare = path.replace(/\\\\/g, "/").replace(ENTRY, "");\n\n return bare.endsWith("/index") ? bare.slice(0, -"/index".length) : bare === "index" ? "" : bare;\n}\n\n/** An address pattern as a path: "/blog/{slug}/" with slug "x" \u2192 "/blog/x/". */\nexport function fillPattern(/** @type {string} */ pattern, /** @type {string} */ slug) {\n const filled = pattern.replace(/\\{[^}]+\\}/g, slug.toLowerCase());\n\n return filled.replace(/\\/{2,}/g, "/") || "/";\n}\n\n/** An address pattern as a glob for one level of entries: "/blog/{slug}/" \u2192 "/blog/*". */\nexport function patternGlob(/** @type {string} */ pattern) {\n return pattern.replace(/\\{[^}]+\\}/g, "*").replace(/\\/+$/, "") || "/";\n}\n\n/**\n * @param {string} root The site\'s folder.\n * @returns {SiteContent}\n */\nexport function readSiteContent(root) {\n /** @type {SiteContent} */\n const out = { name: "", patterns: {}, drafts: [], dates: {} };\n /** @type {Record<string, string>} */\n const draftFields = {};\n /** @type {Record<string, string>} */\n const dateFields = {};\n const configPath = join(root, "galley.config.json");\n /** @type {Set<string>} */\n const pageless = new Set();\n\n if (existsSync(configPath)) {\n try {\n const config = JSON.parse(readFileSync(configPath, "utf8"));\n\n if (typeof config?.name === "string") out.name = config.name.trim();\n for (const collection of Array.isArray(config?.collections) ? config.collections : []) {\n if (typeof collection?.id !== "string") continue;\n if (typeof collection.url === "string" && collection.url.startsWith("/")) out.patterns[collection.id] = collection.url;\n else if (collection.url === null) pageless.add(collection.id);\n if (typeof collection.draftField === "string") draftFields[collection.id] = collection.draftField;\n if (typeof collection.dateField === "string") dateFields[collection.id] = collection.dateField;\n }\n } catch {\n // The app reports a broken galley.config.json; here it only means no patterns.\n }\n }\n const contentDir = join(root, "src", "content");\n\n if (!existsSync(contentDir)) return out;\n for (const id of readdirSync(contentDir).sort()) {\n const dir = join(contentDir, id);\n\n if (!statSync(dir).isDirectory() || pageless.has(id)) continue;\n const pattern = out.patterns[id] ?? (id === "pages" ? "/{slug}/" : `/${id}/{slug}/`);\n\n for (const file of files(dir)) {\n let text = "";\n\n try {\n text = readFileSync(file, "utf8");\n } catch {\n continue;\n }\n const slug = slugOf(relative(dir, file));\n const address = id === "pages" && (slug === "index" || slug === "") ? "/" : fillPattern(pattern, slug);\n\n if (isDraft(text, file, draftFields[id] ?? "draft")) {\n out.drafts.push(address);\n continue;\n }\n const date = entryDate(text, file, dateFields[id] ? [dateFields[id]] : DATE_KEYS);\n\n if (date) out.dates[address] = date;\n }\n }\n out.drafts.sort();\n return out;\n}\n', "visibility/crawlers.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163224
|
+
`, "visibility/config.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The visibility data file \u2014 src/data/visibility.json unless the\n// integration names another \u2014 read, checked and given its defaults. Every\n// part can be switched off; with no file at all a site gets the safe\n// defaults: markdown twins, llms.txt, llms-full.txt and the agent page on,\n// structured data where the page\'s own facts allow it, robots.txt and\n// sitemap.xml only when the site has none of its own, and no crawler\n// blocked.\n//\n// {\n// "site": { "name": "Ferrow", "summary": "One sentence about the site." },\n// "crawlers": { "GPTBot": "block", "OAI-SearchBot": "allow" },\n// "robots": { "disallow": ["/drafts/"] },\n// "sitemap": { "exclude": ["/thanks/"], "lastmod": "content" },\n// "structuredData": { "website": true, "organization": { "logo": "/images/logo.svg", "sameAs": [] },\n// "articles": ["blog"], "breadcrumbs": true },\n// "agentReadable": { "llmsTxt": true, "llmsFullTxt": true, "markdownTwins": true, "agentPage": true,\n// "optional": ["/privacy/"], "exclude": [], "contact": "hello@example.com" }\n// }\n\nimport { existsSync, readFileSync } from "node:fs";\nimport { join } from "node:path";\n\nexport const DEFAULT_FILE = "src/data/visibility.json";\n/** llms-full.txt stops before this many bytes. */\nexport const FULL_MAX_BYTES = 1_000_000;\n\n/**\n * @typedef {object} VisibilitySettings\n * @property {{ name: string; summary: string }} site\n * @property {Record<string, "allow" | "block">} crawlers\n * @property {{ enabled: boolean; disallow: string[]; allow: string[] }} robots\n * @property {{ enabled: boolean; exclude: string[]; lastmod: "content" | "none" }} sitemap\n * @property {{ website: boolean; organization: false | { name: string; logo: string; sameAs: string[]; email: string; telephone: string }; articles: "auto" | false | string[]; breadcrumbs: boolean }} structuredData\n * @property {{ llmsTxt: boolean; llmsFullTxt: boolean; markdownTwins: boolean; agentPage: boolean; optional: string[]; exclude: string[]; contact: string; fullMaxBytes: number }} agentReadable\n */\n\nexport class VisibilityFileError extends Error {}\n\n/** @returns {VisibilitySettings} */\nexport function defaultSettings() {\n return {\n site: { name: "", summary: "" },\n crawlers: {},\n robots: { enabled: true, disallow: [], allow: [] },\n sitemap: { enabled: true, exclude: [], lastmod: "content" },\n structuredData: { website: true, organization: { name: "", logo: "", sameAs: [], email: "", telephone: "" }, articles: "auto", breadcrumbs: true },\n agentReadable: { llmsTxt: true, llmsFullTxt: true, markdownTwins: true, agentPage: true, optional: [], exclude: [], contact: "", fullMaxBytes: FULL_MAX_BYTES },\n };\n}\n\n/** A robots.txt product token (RFC 9309: letters, "_" and "-"); digits are accepted as crawlers use them. */\nconst TOKEN = /^[A-Za-z0-9_-]+$/;\n\n/**\n * The file\'s contents with defaults applied. Throws a VisibilityFileError\n * listing every problem, in plain words, when something can\'t be used.\n *\n * @param {unknown} raw\n * @param {string} [file] For the messages.\n * @returns {VisibilitySettings}\n */\nexport function normalizeSettings(raw, file = DEFAULT_FILE) {\n const out = defaultSettings();\n /** @type {string[]} */\n const problems = [];\n\n if (raw === undefined || raw === null) return out;\n if (typeof raw !== "object" || Array.isArray(raw)) throw new VisibilityFileError(`${file} must hold an object, like { "crawlers": { "GPTBot": "block" } }.`);\n const data = /** @type {Record<string, unknown>} */ (raw);\n const known = new Set(["$schema", "site", "crawlers", "robots", "sitemap", "structuredData", "agentReadable"]);\n\n for (const key of Object.keys(data)) if (!known.has(key)) problems.push(`\u201C${key}\u201D isn\'t a setting this kit knows (it reads site, crawlers, robots, sitemap, structuredData and agentReadable).`);\n /** @param {unknown} value @param {string} at */\n const section = (value, at) => {\n if (value === undefined) return null;\n if (value === false) return false;\n if (value === true) return {};\n if (typeof value === "object" && value !== null && !Array.isArray(value)) return /** @type {Record<string, unknown>} */ (value);\n problems.push(`${at} should be an object of settings, or false to turn it off.`);\n return null;\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at @param {boolean} fallback */\n const bool = (from, key, at, fallback) => {\n const value = from[key];\n\n if (value === undefined) return fallback;\n if (typeof value === "boolean") return value;\n problems.push(`${at}.${key} should be true or false.`);\n return fallback;\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at */\n const text = (from, key, at) => {\n const value = from[key];\n\n if (value === undefined || value === null) return "";\n if (typeof value === "string") return value.trim();\n problems.push(`${at}.${key} should be text.`);\n return "";\n };\n /** @param {Record<string, unknown>} from @param {string} key @param {string} at @param {boolean} [paths] */\n const list = (from, key, at, paths = false) => {\n const value = from[key];\n\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {\n problems.push(`${at}.${key} should be a list of ${paths ? "addresses on the site, like \\"/thanks/\\"" : "texts"}.`);\n return [];\n }\n const items = /** @type {string[]} */ (value).map((item) => item.trim()).filter(Boolean);\n\n if (paths) for (const item of items) if (!item.startsWith("/")) problems.push(`${at}.${key}: \u201C${item}\u201D should start with \u201C/\u201D (an address on the site, without the domain).`);\n return items;\n };\n\n const site = section(data.site, "site");\n\n if (site) out.site = { name: text(site, "name", "site"), summary: text(site, "summary", "site") };\n\n if (data.crawlers !== undefined) {\n if (typeof data.crawlers !== "object" || data.crawlers === null || Array.isArray(data.crawlers)) problems.push(\'crawlers should map a crawler\\\'s name to "allow" or "block", like { "GPTBot": "block" }.\');\n else {\n for (const [token, choice] of Object.entries(data.crawlers)) {\n if (!TOKEN.test(token)) problems.push(`crawlers: \u201C${token}\u201D isn\'t a crawler name robots.txt can use (letters, digits, \u201C-\u201D and \u201C_\u201D only).`);\n else if (choice !== "allow" && choice !== "block") problems.push(`crawlers.${token} should be "allow" or "block".`);\n else out.crawlers[token] = choice;\n }\n }\n }\n\n const robots = section(data.robots, "robots");\n\n if (robots === false) out.robots.enabled = false;\n else if (robots) out.robots = { enabled: bool(robots, "enabled", "robots", true), disallow: list(robots, "disallow", "robots", true), allow: list(robots, "allow", "robots", true) };\n\n const sitemap = section(data.sitemap, "sitemap");\n\n if (sitemap === false) out.sitemap.enabled = false;\n else if (sitemap) {\n const lastmod = sitemap.lastmod ?? "content";\n\n if (lastmod !== "content" && lastmod !== "none") problems.push(\'sitemap.lastmod should be "content" (dates the pages state) or "none".\');\n out.sitemap = { enabled: bool(sitemap, "enabled", "sitemap", true), exclude: list(sitemap, "exclude", "sitemap", true), lastmod: lastmod === "none" ? "none" : "content" };\n }\n\n const structured = section(data.structuredData, "structuredData");\n\n if (structured === false) out.structuredData = { website: false, organization: false, articles: false, breadcrumbs: false };\n else if (structured) {\n const organization = section(structured.organization, "structuredData.organization");\n const articles = structured.articles;\n\n out.structuredData = {\n website: bool(structured, "website", "structuredData", true),\n organization:\n organization === false\n ? false\n : {\n name: organization ? text(organization, "name", "structuredData.organization") : "",\n logo: organization ? text(organization, "logo", "structuredData.organization") : "",\n sameAs: organization ? list(organization, "sameAs", "structuredData.organization") : [],\n email: organization ? text(organization, "email", "structuredData.organization") : "",\n telephone: organization ? text(organization, "telephone", "structuredData.organization") : "",\n },\n articles: articles === undefined || articles === true || articles === "auto" ? "auto" : articles === false ? false : Array.isArray(articles) && articles.every((item) => typeof item === "string") ? articles.map((item) => item.trim()).filter(Boolean) : "auto",\n breadcrumbs: bool(structured, "breadcrumbs", "structuredData", true),\n };\n if (!(articles === undefined || typeof articles === "boolean" || articles === "auto" || (Array.isArray(articles) && articles.every((item) => typeof item === "string")))) {\n problems.push(\'structuredData.articles should list collections (like ["blog"]) or addresses (like ["/news/*"]), or be "auto" or false.\');\n }\n if (out.structuredData.organization) {\n for (const link of out.structuredData.organization.sameAs) if (!/^https?:\\/\\/\\S+$/i.test(link)) problems.push(`structuredData.organization.sameAs: \u201C${link}\u201D should be a full address starting with https://.`);\n const logo = out.structuredData.organization.logo;\n\n if (logo && !logo.startsWith("/") && !/^https?:\\/\\//i.test(logo)) problems.push(`structuredData.organization.logo: \u201C${logo}\u201D should be an address on the site (like "/images/logo.png") or a full address.`);\n }\n }\n\n const agent = section(data.agentReadable, "agentReadable");\n\n if (agent === false) out.agentReadable = { ...out.agentReadable, llmsTxt: false, llmsFullTxt: false, markdownTwins: false, agentPage: false };\n else if (agent) {\n const max = agent.fullMaxBytes;\n\n if (max !== undefined && (typeof max !== "number" || !Number.isInteger(max) || max < 10_000)) problems.push("agentReadable.fullMaxBytes should be a whole number of bytes, at least 10000.");\n out.agentReadable = {\n llmsTxt: bool(agent, "llmsTxt", "agentReadable", true),\n llmsFullTxt: bool(agent, "llmsFullTxt", "agentReadable", true),\n markdownTwins: bool(agent, "markdownTwins", "agentReadable", true),\n agentPage: bool(agent, "agentPage", "agentReadable", true),\n optional: list(agent, "optional", "agentReadable", true),\n exclude: list(agent, "exclude", "agentReadable", true),\n contact: text(agent, "contact", "agentReadable"),\n fullMaxBytes: typeof max === "number" && Number.isInteger(max) && max >= 10_000 ? max : FULL_MAX_BYTES,\n };\n }\n if (problems.length) {\n throw new VisibilityFileError(`${file} has ${problems.length === 1 ? "a problem" : `${problems.length} problems`}:\\n${problems.map((line) => ` - ${line}`).join("\\n")}`);\n }\n return out;\n}\n\n/**\n * The site\'s visibility file, read and checked (defaults when there is none).\n *\n * @param {string} root The site\'s folder.\n * @param {string} [file]\n * @returns {{ settings: VisibilitySettings; exists: boolean }}\n */\nexport function readSettings(root, file = DEFAULT_FILE) {\n const path = join(root, file);\n\n if (!existsSync(path)) return { settings: defaultSettings(), exists: false };\n let raw;\n\n try {\n raw = JSON.parse(readFileSync(path, "utf8"));\n } catch (error) {\n throw new VisibilityFileError(`${file} can\'t be read as JSON (${error instanceof Error ? error.message : String(error)}). Fix the file, or remove it to use the defaults.`);\n }\n return { settings: normalizeSettings(raw, file), exists: true };\n}\n', "visibility/content.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// What the site\'s content files say that a rendered page can\'t: which\n// collection a page belongs to (for "articles": ["blog"]), which entries\n// are drafts (so a dev server that shows drafts still never lists them), and\n// each entry\'s date, for a page whose HTML doesn\'t state it.\n//\n// Addresses come from galley.config.json\'s collection `url` patterns when\n// the site has one ("/blog/{slug}/"), else the folder name ("/blog/{slug}/";\n// "pages" is "/{slug}/"). Drafts are entries whose front matter (or JSON /\n// YAML) sets the collection\'s draft field \u2014 "draft" unless galley.config.json\n// names another \u2014 to true. Dates come from the collection\'s dateField in\n// galley.config.json, else `date`, `pubDate`, `publishDate` or `published`,\n// written as an ISO date ("2026-08-20", "2026-08-20T09:00:00Z"). Read with\n// plain text matching, so the kit needs no YAML parser; a field written some\n// other way is simply not seen.\n\nimport { existsSync, readdirSync, readFileSync, statSync } from "node:fs";\nimport { join, relative } from "node:path";\n\n/**\n * @typedef {object} SiteContent\n * @property {string} name galley.config.json\'s `name`, when there is one.\n * @property {Record<string, string>} patterns collection id \u2192 address pattern, e.g. "/blog/{slug}/".\n * @property {string[]} drafts Addresses (without the base) of draft entries.\n * @property {Record<string, string>} dates Address (without the base) \u2192 the entry\'s date, as written.\n */\n\nconst ENTRY = /\\.(md|mdx|markdown|mdoc|json|ya?ml)$/i;\n\n/** @param {string} dir @returns {string[]} */\nfunction files(dir) {\n /** @type {string[]} */\n const out = [];\n /** @param {string} at */\n const walk = (at) => {\n for (const name of readdirSync(at).sort()) {\n if (name.startsWith(".") || name.startsWith("_")) continue;\n const path = join(at, name);\n const info = statSync(path);\n\n if (info.isDirectory()) walk(path);\n else if (ENTRY.test(name)) out.push(path);\n }\n };\n\n walk(dir);\n return out;\n}\n\n/** Whether a content file sets `field` to true. */\nexport function isDraft(/** @type {string} */ text, /** @type {string} */ file, field = "draft") {\n const key = field.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n\n if (/\\.json$/i.test(file)) {\n try {\n const data = JSON.parse(text);\n\n return Boolean(data && typeof data === "object" && data[field] === true);\n } catch {\n return false;\n }\n }\n const yaml = /\\.ya?ml$/i.test(file) ? text : /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/.exec(text)?.[1] ?? "";\n\n return new RegExp(`^${key}\\\\s*:\\\\s*(true|yes|on)\\\\s*(#.*)?$`, "mi").test(yaml);\n}\n\nconst DATE_KEYS = ["date", "pubDate", "publishDate", "published"];\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(?:[T ][\\d:.]+(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/** The entry\'s date, as written, when it is an ISO date. */\nexport function entryDate(/** @type {string} */ text, /** @type {string} */ file, /** @type {string[]} */ keys) {\n if (/\\.json$/i.test(file)) {\n try {\n const data = JSON.parse(text);\n\n for (const key of keys) if (typeof data?.[key] === "string" && ISO_DATE.test(data[key].trim())) return data[key].trim();\n } catch {\n return "";\n }\n return "";\n }\n const yaml = /\\.ya?ml$/i.test(file) ? text : /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/.exec(text)?.[1] ?? "";\n\n for (const key of keys) {\n const match = new RegExp(`^${key.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")}\\\\s*:\\\\s*["\']?([^"\'#\\\\r\\\\n]+?)["\']?\\\\s*(#.*)?$`, "m").exec(yaml);\n const value = match?.[1]?.trim() ?? "";\n\n if (ISO_DATE.test(value)) return value;\n }\n return "";\n}\n\n/** An entry\'s slug from its file: "blog/first-post.md" \u2192 "first-post"; "guides/setup/index.md" \u2192 "guides/setup". */\nfunction slugOf(/** @type {string} */ path) {\n const bare = path.replace(/\\\\/g, "/").replace(ENTRY, "");\n\n return bare.endsWith("/index") ? bare.slice(0, -"/index".length) : bare === "index" ? "" : bare;\n}\n\n/** An address pattern as a path: "/blog/{slug}/" with slug "x" \u2192 "/blog/x/". */\nexport function fillPattern(/** @type {string} */ pattern, /** @type {string} */ slug) {\n const filled = pattern.replace(/\\{[^}]+\\}/g, slug.toLowerCase());\n\n return filled.replace(/\\/{2,}/g, "/") || "/";\n}\n\n/** An address pattern as a glob for one level of entries: "/blog/{slug}/" \u2192 "/blog/*". */\nexport function patternGlob(/** @type {string} */ pattern) {\n return pattern.replace(/\\{[^}]+\\}/g, "*").replace(/\\/+$/, "") || "/";\n}\n\n/**\n * @param {string} root The site\'s folder.\n * @returns {SiteContent}\n */\nexport function readSiteContent(root) {\n /** @type {SiteContent} */\n const out = { name: "", patterns: {}, drafts: [], dates: {} };\n /** @type {Record<string, string>} */\n const draftFields = {};\n /** @type {Record<string, string>} */\n const dateFields = {};\n const configPath = join(root, "galley.config.json");\n /** @type {Set<string>} */\n const pageless = new Set();\n\n if (existsSync(configPath)) {\n try {\n const config = JSON.parse(readFileSync(configPath, "utf8"));\n\n if (typeof config?.name === "string") out.name = config.name.trim();\n for (const collection of Array.isArray(config?.collections) ? config.collections : []) {\n if (typeof collection?.id !== "string") continue;\n if (typeof collection.url === "string" && collection.url.startsWith("/")) out.patterns[collection.id] = collection.url;\n else if (collection.url === null) pageless.add(collection.id);\n if (typeof collection.draftField === "string") draftFields[collection.id] = collection.draftField;\n if (typeof collection.dateField === "string") dateFields[collection.id] = collection.dateField;\n }\n } catch {\n // The app reports a broken galley.config.json; here it only means no patterns.\n }\n }\n const contentDir = join(root, "src", "content");\n\n if (!existsSync(contentDir)) return out;\n for (const id of readdirSync(contentDir).sort()) {\n const dir = join(contentDir, id);\n\n if (!statSync(dir).isDirectory() || pageless.has(id)) continue;\n const pattern = out.patterns[id] ?? (id === "pages" ? "/{slug}/" : `/${id}/{slug}/`);\n\n for (const file of files(dir)) {\n let text = "";\n\n try {\n text = readFileSync(file, "utf8");\n } catch {\n continue;\n }\n const slug = slugOf(relative(dir, file));\n const address = id === "pages" && (slug === "index" || slug === "") ? "/" : fillPattern(pattern, slug);\n\n if (isDraft(text, file, draftFields[id] ?? "draft")) {\n out.drafts.push(address);\n continue;\n }\n const date = entryDate(text, file, dateFields[id] ? [dateFields[id]] : DATE_KEYS);\n\n if (date) out.dates[address] = date;\n }\n }\n out.drafts.sort();\n return out;\n}\n', "visibility/crawlers.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
162897
163225
|
// @ts-check
|
|
162898
163226
|
// The AI crawlers a site can allow or block one by one, from each provider's
|
|
162899
163227
|
// own documentation (read 23 November 2026 \u2014 the links are in \`docs\`). The
|
|
@@ -163088,7 +163416,7 @@ export function describePolicy(choices) {
|
|
|
163088
163416
|
|
|
163089
163417
|
return \`\${sentence.charAt(0).toUpperCase()}\${sentence.slice(1)}.\`;
|
|
163090
163418
|
}
|
|
163091
|
-
`, "visibility/html.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A small, tolerant HTML reader for the pages a site builds: enough of the\n// HTML parsing rules to turn Astro\'s (and any static generator\'s) output\n// into a tree \u2014 void elements, raw-text elements, comments, entities, the\n// common implied end tags \u2014 and no more. The kit depends on nothing but\n// Astro, so it can\'t bring a full parser; built pages are regular enough,\n// and everything built from this tree only ever reports what it found.\n\n/**\n * @typedef {object} Element\n * @property {"element"} type\n * @property {string} name Lower-case tag name.\n * @property {Record<string, string>} attrs Lower-case names, decoded values.\n * @property {Node[]} children\n * @property {Element | null} parent\n */\n/** @typedef {{ type: "text"; value: string; parent: Element | null }} Text */\n/** @typedef {Element | Text} Node */\n\nconst VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);\nconst RAW = new Set(["script", "style", "textarea", "title", "xmp", "noscript", "template", "iframe", "noembed", "noframes"]);\n/** Opening one of these closes an open <p> (HTML\'s "close a p element"). */\nconst CLOSES_P = new Set([\n "address", "article", "aside", "blockquote", "details", "dialog", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form",\n "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "main", "menu", "nav", "ol", "p", "pre", "section", "table", "ul",\n]);\n\nconst NAMED = /** @type {Record<string, string>} */ ({\n amp: "&", lt: "<", gt: ">", quot: \'"\', apos: "\'", nbsp: "\xA0", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009",\n ndash: "\u2013", mdash: "\u2014", hellip: "\u2026", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C",\n rdquo: "\u201D", bdquo: "\u201E", laquo: "\xAB", raquo: "\xBB", lsaquo: "\u2039", rsaquo: "\u203A", middot: "\xB7",\n bull: "\u2022", copy: "\xA9", reg: "\xAE", trade: "\u2122", times: "\xD7", divide: "\xF7", deg: "\xB0", euro: "\u20AC",\n pound: "\xA3", yen: "\xA5", cent: "\xA2", sect: "\xA7", para: "\xB6", plusmn: "\xB1", frac12: "\xBD",\n frac14: "\xBC", frac34: "\xBE", larr: "\u2190", rarr: "\u2192", uarr: "\u2191", darr: "\u2193", harr: "\u2194",\n check: "\u2713", minus: "\u2212", prime: "\u2032", Prime: "\u2033", shy: "\xAD", zwj: "\u200D", zwnj: "\u200C",\n eacute: "\xE9", egrave: "\xE8", aacute: "\xE1", agrave: "\xE0", iacute: "\xED", oacute: "\xF3", uacute: "\xFA",\n ouml: "\xF6", uuml: "\xFC", auml: "\xE4", szlig: "\xDF", ccedil: "\xE7", ntilde: "\xF1", colon: ":", sol: "/",\n num: "#", lpar: "(", rpar: ")", lsqb: "[", rsqb: "]", lowbar: "_", ast: "*", grave: "`", vert: "|", equals: "=",\n});\n\n/** Character references \u2192 characters. Unknown names stay as written. */\nexport function decodeEntities(/** @type {string} */ text) {\n if (!text.includes("&")) return text;\n return text.replace(/&(#x[0-9a-f]+|#\\d+|[a-z][a-z0-9]*);?/gi, (whole, ref) => {\n if (ref[0] === "#") {\n const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n\n return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;\n }\n const named = NAMED[ref];\n\n return named === undefined ? whole : named;\n });\n}\n\n/** @param {string} name @param {Element | null} parent @returns {Element} */\nfunction element(name, parent) {\n return { type: "element", name, attrs: {}, children: [], parent };\n}\n\n/**\n * Reads the attributes of a start tag (the text between the name and `>`).\n *\n * @param {string} source\n * @returns {Record<string, string>}\n */\nfunction readAttributes(source) {\n /** @type {Record<string, string>} */\n const attrs = {};\n const pattern = /([^\\s"\'>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\'|([^\\s>]+)))?/g;\n\n for (const match of source.matchAll(pattern)) {\n const name = (match[1] ?? "").toLowerCase();\n\n if (!name || name in attrs) continue;\n attrs[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");\n }\n return attrs;\n}\n\n/** Where a start tag ends: the first `>` outside quotes. */\nfunction tagEnd(/** @type {string} */ html, /** @type {number} */ from) {\n let quote = "";\n\n for (let index = from; index < html.length; index += 1) {\n const char = html[index];\n\n if (quote) {\n if (char === quote) quote = "";\n } else if (char === \'"\' || char === "\'") quote = char;\n else if (char === ">") return index;\n }\n return -1;\n}\n\n/**\n * The document as a tree under a root element named "#document".\n *\n * @param {string} html\n * @returns {Element}\n */\nexport function parseHtml(html) {\n const root = element("#document", null);\n /** @type {Element[]} */\n const stack = [root];\n const current = () => /** @type {Element} */ (stack[stack.length - 1]);\n /** @param {string} value */\n const addText = (value) => {\n if (!value) return;\n const parent = current();\n const last = parent.children[parent.children.length - 1];\n\n if (last && last.type === "text") last.value += value;\n else parent.children.push({ type: "text", value, parent });\n };\n /** Closes the innermost open `name`, and everything opened inside it. */\n const close = (/** @type {string} */ name) => {\n for (let index = stack.length - 1; index > 0; index -= 1) {\n if (stack[index]?.name === name) {\n stack.length = index;\n return true;\n }\n }\n return false;\n };\n /** Whether `name` is open, without crossing one of `scope`. */\n const openWithin = (/** @type {string} */ name, /** @type {Set<string>} */ scope) => {\n for (let index = stack.length - 1; index > 0; index -= 1) {\n const open = stack[index]?.name ?? "";\n\n if (open === name) return true;\n if (scope.has(open)) return false;\n }\n return false;\n };\n const LIST_SCOPE = new Set(["ul", "ol", "menu", "table", "div", "section", "article", "main", "body"]);\n const DL_SCOPE = new Set(["dl", "table", "div", "section", "article", "main", "body"]);\n const TABLE_SCOPE = new Set(["table"]);\n let at = 0;\n\n while (at < html.length) {\n const lt = html.indexOf("<", at);\n\n if (lt === -1) {\n addText(decodeEntities(html.slice(at)));\n break;\n }\n if (lt > at) addText(decodeEntities(html.slice(at, lt)));\n if (html.startsWith("<!--", lt)) {\n const end = html.indexOf("-->", lt + 4);\n\n at = end === -1 ? html.length : end + 3;\n continue;\n }\n if (html[lt + 1] === "!" || html[lt + 1] === "?") {\n const end = html.indexOf(">", lt);\n\n at = end === -1 ? html.length : end + 1;\n continue;\n }\n if (html[lt + 1] === "/") {\n const match = /^<\\/([a-zA-Z][^\\s/>]*)[^>]*>/.exec(html.slice(lt, lt + 200));\n\n if (!match) {\n addText("<");\n at = lt + 1;\n continue;\n }\n close((match[1] ?? "").toLowerCase());\n at = lt + match[0].length;\n continue;\n }\n const nameMatch = /^<([a-zA-Z][^\\s/>]*)/.exec(html.slice(lt, lt + 100));\n\n if (!nameMatch) {\n addText("<");\n at = lt + 1;\n continue;\n }\n const end = tagEnd(html, lt + nameMatch[0].length);\n\n if (end === -1) {\n addText(decodeEntities(html.slice(lt)));\n break;\n }\n const name = (nameMatch[1] ?? "").toLowerCase();\n const node = element(name, null);\n\n node.attrs = readAttributes(html.slice(lt + nameMatch[0].length, end).replace(/\\/\\s*$/, ""));\n // The implied end tags built pages rely on most.\n if (CLOSES_P.has(name) && openWithin("p", new Set(["button", "table", "td", "th"]))) close("p");\n if (name === "li" && openWithin("li", LIST_SCOPE)) close("li");\n if ((name === "dt" || name === "dd") && (openWithin("dt", DL_SCOPE) || openWithin("dd", DL_SCOPE))) {\n if (!close("dd")) close("dt");\n }\n if (name === "tr" && openWithin("tr", TABLE_SCOPE)) close("tr");\n if ((name === "td" || name === "th") && (openWithin("td", new Set(["tr", "table"])) || openWithin("th", new Set(["tr", "table"])))) {\n if (!close("td")) close("th");\n }\n if (name === "option" && openWithin("option", new Set(["select", "datalist"]))) close("option");\n node.parent = current();\n current().children.push(node);\n at = end + 1;\n if (VOID.has(name)) continue;\n if (RAW.has(name)) {\n const closeAt = html.toLowerCase().indexOf(`</${name}`, at);\n const text = html.slice(at, closeAt === -1 ? html.length : closeAt);\n\n if (text) node.children.push({ type: "text", value: name === "title" || name === "textarea" ? decodeEntities(text) : text, parent: node });\n if (closeAt === -1) break;\n const closeEnd = html.indexOf(">", closeAt);\n\n at = closeEnd === -1 ? html.length : closeEnd + 1;\n continue;\n }\n // `<path \u2026 />` in inline SVG closes itself (foreign content). HTML\n // elements written that way are treated the same: generators that emit\n // `<div />` mean an empty element too.\n if (html[end - 1] === "/") continue;\n stack.push(node);\n }\n return root;\n}\n\n/**\n * Every element under `node` (depth first, document order) for which `test`\n * is true. `skip` prunes a subtree.\n *\n * @param {Element} node\n * @param {(el: Element) => boolean} test\n * @param {(el: Element) => boolean} [skip]\n * @returns {Element[]}\n */\nexport function findAll(node, test, skip) {\n /** @type {Element[]} */\n const out = [];\n /** @param {Element} at */\n const walk = (at) => {\n for (const child of at.children) {\n if (child.type !== "element") continue;\n if (skip && skip(child)) continue;\n if (test(child)) out.push(child);\n walk(child);\n }\n };\n\n walk(node);\n return out;\n}\n\n/**\n * The first element under `node` for which `test` is true.\n *\n * @param {Element} node\n * @param {(el: Element) => boolean} test\n * @returns {Element | null}\n */\nexport function find(node, test) {\n for (const child of node.children) {\n if (child.type !== "element") continue;\n if (test(child)) return child;\n const inner = find(child, test);\n\n if (inner) return inner;\n }\n return null;\n}\n\n/** The text of a subtree, whitespace collapsed. Raw-text elements count as no text. */\nexport function textOf(/** @type {Node} */ node) {\n /** @type {string[]} */\n const parts = [];\n /** @param {Node} at */\n const walk = (at) => {\n if (at.type === "text") {\n parts.push(at.value);\n return;\n }\n if (at.name === "script" || at.name === "style" || at.name === "template" || at.name === "noscript") return;\n for (const child of at.children) walk(child);\n if (at.name === "br") parts.push(" ");\n };\n\n walk(node);\n return parts.join("").replace(/\\s+/g, " ").trim();\n}\n\n/** Whether the element (or one of its ancestors) is `name`. */\nexport function within(/** @type {Element | null} */ node, /** @type {string} */ name) {\n for (let at = node; at; at = at.parent) if (at.name === name) return true;\n return false;\n}\n', "visibility/integration.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The agent-readable output as an Astro integration part: after `astro\n// build` it reads every page the build wrote and adds the markdown twins,\n// llms.txt, llms-full.txt, agent.md, robots.txt, sitemap.xml and the tags\n// each page\'s <head> gains; in `astro dev` the same addresses answer, made\n// on request from the pages the dev server renders, so a preview shows what\n// a build will publish. No page gains any JavaScript.\n//\n// Used by the package\'s integration (galley({ visibility })) and, vendored,\n// as src/galley/integration.js (scripts/vendor.mjs).\n\nimport { existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs";\nimport { dirname, join, relative, sep } from "node:path";\nimport { fileURLToPath } from "node:url";\nimport { DEFAULT_FILE, readSettings } from "./config.js";\nimport { readSiteContent } from "./content.js";\nimport { addToHead, readPage } from "./page.js";\nimport { pagesForTwin, planSite, sitePath, twinPath } from "./site.js";\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {import("./site.js").SiteInput} SiteInput */\n\n/** The header the dev server\'s own requests carry, so they get the page as rendered. */\nexport const RAW_HEADER = "x-galley-visibility";\n/** Pages a dev server answer crawls at most (llms.txt, the sitemap). */\nexport const DEV_CRAWL_LIMIT = 500;\n/** Placeholder host for a site with no `site` address; removed from what is written. */\nconst NO_ORIGIN = "https://site.invalid";\n\n/**\n * @typedef {object} VisibilityOptions\n * @property {string} [file] The data file. Default "src/data/visibility.json".\n */\n\n/** @param {string} dir @returns {string[]} HTML files under dir, relative, "/"-separated, sorted. */\nfunction htmlFiles(dir) {\n /** @type {string[]} */\n const out = [];\n /** @param {string} at */\n const walk = (at) => {\n for (const name of readdirSync(at)) {\n const path = join(at, name);\n const info = statSync(path);\n\n if (info.isDirectory()) walk(path);\n else if (name.endsWith(".html")) out.push(relative(dir, path).split(sep).join("/"));\n }\n };\n\n walk(dir);\n return out.sort();\n}\n\n/** "about/index.html" \u2192 "/demo/about/"; "about.html" \u2192 "/demo/about"; "index.html" \u2192 "/demo/". */\nexport function pagePath(/** @type {string} */ file, /** @type {string} */ base) {\n if (file === "index.html") return `${base}/`;\n if (file.endsWith("/index.html")) return `${base}/${file.slice(0, -"index.html".length)}`;\n return `${base}/${file.replace(/\\.html$/, "")}`;\n}\n\n/** The site\'s origin and base path from Astro\'s config. */\nexport function siteAddress(/** @type {{ site?: string | URL | undefined; base?: string }} */ config) {\n let origin = "";\n\n try {\n origin = config.site ? new URL(String(config.site)).origin : "";\n } catch {\n origin = "";\n }\n return { origin, base: (config.base ?? "/").replace(/\\/+$/, "") };\n}\n\n/** Facts read with a placeholder origin, with the placeholder taken out again. */\nfunction withoutPlaceholder(/** @type {PageFacts} */ facts) {\n const strip = (/** @type {string} */ value) => value.split(NO_ORIGIN).join("");\n\n return {\n ...facts,\n url: strip(facts.url),\n canonical: facts.canonical ? strip(facts.canonical) : null,\n image: strip(facts.image),\n markdown: strip(facts.markdown),\n feeds: facts.feeds.map((feed) => ({ ...feed, href: strip(feed.href) })),\n };\n}\n\n/** @param {string} html @param {string} path @param {string} origin */\nfunction factsOf(html, path, origin) {\n const facts = readPage(html, { path, url: `${origin || NO_ORIGIN}${path}` });\n\n return origin ? facts : withoutPlaceholder(facts);\n}\n\n/**\n * Writes the agent-readable output into a finished build.\n *\n * @param {object} input\n * @param {string} input.dir The build\'s output folder.\n * @param {string} input.root The site\'s folder.\n * @param {string} input.file The data file, relative to the site.\n * @param {string} input.origin\n * @param {string} input.base\n * @param {boolean} [input.siteSitemap] An integration (such as @astrojs/sitemap) writes the sitemap.\n * @returns {{ notes: string[]; summary: string; written: string[]; changedPages: number; ms: number }}\n */\nexport function writeVisibility({ dir, root, file, origin, base, siteSitemap = false }) {\n const started = performance.now();\n const { settings } = readSettings(root, file);\n const content = readSiteContent(root);\n const files = htmlFiles(dir);\n const pages = files.map((name) => factsOf(readFileSync(join(dir, name), "utf8"), pagePath(name, base), origin));\n const has = (/** @type {string} */ name) => existsSync(join(dir, name));\n const plan = planSite({\n pages,\n settings,\n origin,\n base,\n own: {\n robots: has("robots.txt") ? "robots.txt" : null,\n sitemap: has("sitemap-index.xml") || siteSitemap ? "sitemap-index.xml" : has("sitemap.xml") ? "sitemap.xml" : null,\n llmsTxt: has("llms.txt"),\n llmsFullTxt: has("llms-full.txt"),\n agentPage: has("agent.md"),\n },\n drafts: content.drafts,\n dates: content.dates,\n patterns: content.patterns,\n fallbackName: content.name,\n fileExists: (path) => has(path.replace(/^\\/+/, "")) || existsSync(join(root, "public", path.replace(/^\\/+/, ""))),\n });\n const notes = [...plan.notes];\n /** @type {string[]} */\n const written = [];\n let changedPages = 0;\n\n for (const name of files) {\n const addition = plan.head.get(pagePath(name, base));\n\n if (!addition) continue;\n const path = join(dir, name);\n const html = readFileSync(path, "utf8");\n // A page that already links its markdown version keeps its own link.\n const kept = /type=["\']?text\\/markdown/i.test(html) ? addition.replace(/<link rel="alternate" type="text\\/markdown"[^>]*>/, "") : addition;\n const next = addToHead(html, kept);\n\n if (next !== html) {\n writeFileSync(path, next);\n changedPages += 1;\n }\n }\n for (const [name, text] of Object.entries(plan.files)) {\n const path = join(dir, ...name.split("/"));\n\n if (existsSync(path)) {\n if (name.endsWith(".md")) notes.push(`${base}/${name} is already one of the site\'s files; the kit\'s markdown version of that page was not written.`);\n continue;\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, text);\n written.push(name);\n }\n const c = plan.counts;\n const extras = ["llms.txt", "llms-full.txt", "agent.md", "robots.txt", "sitemap.xml"].filter((name) => written.includes(name));\n const summary =\n `visibility: ${c.listed} of ${c.pages} pages listed \xB7 ${c.twins} markdown versions \xB7 structured data on ${c.structured} pages` +\n (extras.length ? ` \xB7 ${extras.join(", ")}` : "") +\n (c.fullTruncated ? " (llms-full.txt cut at its size limit)" : "") +\n ` \xB7 ${Math.round(performance.now() - started)} ms`;\n\n return { notes, summary, written, changedPages, ms: performance.now() - started };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 astro dev\n\n/**\n * @typedef {object} Fetched\n * @property {number} status\n * @property {string} type\n * @property {string} body\n */\n\n/** Addresses the kit answers in dev (without the base). */\nexport function isVisibilityAddress(/** @type {string} */ local) {\n return /^\\/(llms\\.txt|llms-full\\.txt|agent\\.md|robots\\.txt|sitemap\\.xml|sitemap-\\d+\\.xml)$/.test(local) || (/\\.md$/.test(local) && !local.startsWith("/_") && !local.startsWith("/@"));\n}\n\n/**\n * A written chunk as bytes. Astro\'s dev server writes pages as `Uint8Array`s\n * (not Buffers): turning one into a string gives "60,33,68,\u2026", which is what\n * every page became. Strings honour the encoding passed alongside them.\n * @param {unknown} chunk\n * @param {unknown} [encoding]\n * @returns {Buffer}\n */\nexport function toBuffer(chunk, encoding) {\n if (Buffer.isBuffer(chunk)) return chunk;\n if (chunk instanceof Uint8Array) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n if (ArrayBuffer.isView(chunk)) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n if (chunk instanceof ArrayBuffer) return Buffer.from(chunk);\n return Buffer.from(String(chunk), typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8");\n}\n\n/**\n * Buffers a dev server\'s HTML answer so it can be changed before it is sent.\n * Anything else passes through untouched.\n *\n * @param {import("node:http").ServerResponse} res\n * @param {(html: string) => Promise<string>} transform\n */\nexport function interceptHtml(res, transform) {\n const original = { writeHead: res.writeHead.bind(res), write: res.write.bind(res), end: res.end.bind(res) };\n /** @type {Buffer[]} */\n const chunks = [];\n /** @type {boolean | null} */\n let buffering = null;\n const restore = () => {\n res.writeHead = original.writeHead;\n res.write = original.write;\n res.end = original.end;\n };\n const decide = () => {\n if (buffering !== null) return buffering;\n const type = String(res.getHeader("content-type") ?? "");\n\n buffering = res.statusCode === 200 && /text\\/html/i.test(type) && !res.getHeader("content-encoding");\n if (!buffering) restore();\n return buffering;\n };\n const anyRes = /** @type {any} */ (res);\n\n anyRes.writeHead = (/** @type {number} */ status, /** @type {any[]} */ ...rest) => {\n const headers = rest.find((item) => item && typeof item === "object");\n\n if (typeof rest[0] === "string") res.statusMessage = rest[0];\n res.statusCode = status;\n if (Array.isArray(headers)) for (let index = 0; index + 1 < headers.length; index += 2) res.setHeader(String(headers[index]), headers[index + 1]);\n else if (headers) for (const [name, value] of Object.entries(headers)) if (value !== undefined) res.setHeader(name, /** @type {any} */ (value));\n if (!decide()) return original.writeHead(res.statusCode);\n return res;\n };\n anyRes.write = (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) => {\n if (!decide()) return original.write(chunk, ...rest);\n if (chunk !== undefined && chunk !== null && typeof chunk !== "function") chunks.push(toBuffer(chunk, rest[0]));\n return true;\n };\n anyRes.end = (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) => {\n if (!decide()) return original.end(chunk, ...rest);\n if (chunk !== undefined && chunk !== null && typeof chunk !== "function") chunks.push(toBuffer(chunk, rest[0]));\n const html = Buffer.concat(chunks).toString("utf8");\n\n restore();\n transform(html)\n .catch(() => html)\n .then((out) => {\n if (!res.headersSent) {\n res.setHeader("content-length", Buffer.byteLength(out));\n original.writeHead(res.statusCode);\n }\n original.end(out);\n });\n return res;\n };\n}\n\n/** @typedef {{ pattern: string; regex: RegExp | null; dynamic: boolean }} RouteInfo */\n\n/**\n * Whether the site itself may serve `local` (an address without the base):\n * a file in public/, a route for exactly that address, or a dynamic route\n * ending in the same extension ("/[twin].md"). Only then is the dev server\n * asked \u2014 so a catch-all page route ("/[...slug]") isn\'t asked for every\n * generated address, and doesn\'t log a note for each.\n *\n * @param {string} root\n * @param {RouteInfo[]} routes\n * @param {string} local\n * @returns {"file" | "route" | "maybe" | null}\n */\nexport function siteServes(root, routes, local) {\n if (existsSync(join(root, "public", ...local.split("/").filter(Boolean)))) return "file";\n if (routes.some((route) => !route.dynamic && route.pattern === local)) return "route";\n const extension = /\\.[a-z0-9]+$/i.exec(local)?.[0];\n\n if (extension && routes.some((route) => route.dynamic && route.pattern.endsWith(extension) && (!route.regex || route.regex.test(local)))) return "maybe";\n return null;\n}\n\n/**\n * The dev server\'s answers: the generated addresses, and the extra <head>\n * tags on every page. Reads the data file on every request, so edits show\n * at once.\n *\n * @param {object} input\n * @param {string} input.root\n * @param {string} input.file\n * @param {string} input.origin The site\'s own origin ("" when unknown).\n * @param {string} input.base\n * @param {() => string} input.self The dev server\'s own origin, for its requests to itself.\n * @param {() => RouteInfo[]} [input.routes] The site\'s routes (astro:routes:resolved), to know which addresses it serves itself.\n * @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, next: () => void) => void}\n */\nexport function createDevMiddleware({ root, file, origin, base, self, routes = () => [] }) {\n /** @type {Map<string, { at: number; value: Promise<Fetched | null> }>} */\n const cache = new Map();\n /** @param {string} path @returns {Promise<Fetched | null>} */\n const get = (path) => {\n const hit = cache.get(path);\n\n if (hit && Date.now() - hit.at < 2000) return hit.value;\n const value = fetch(`${self()}${path}`, { headers: { [RAW_HEADER]: "raw", accept: "text/html,*/*" }, redirect: "follow" })\n .then(async (response) => ({ status: response.status, type: response.headers.get("content-type") ?? "", body: await response.text() }))\n .catch(() => null);\n\n cache.set(path, { at: Date.now(), value });\n return value;\n };\n /** @param {string} path @param {string} siteOrigin */\n const facts = async (path, siteOrigin) => {\n const got = await get(path);\n\n return got && got.status === 200 && /html/.test(got.type) ? factsOf(got.body, path, siteOrigin) : null;\n };\n /** Pages reachable from the home page by links, at most DEV_CRAWL_LIMIT. */\n const crawl = async (/** @type {string} */ siteOrigin) => {\n const seen = new Set([`${base}/`]);\n const queue = [`${base}/`];\n /** @type {PageFacts[]} */\n const pages = [];\n\n while (queue.length && pages.length < DEV_CRAWL_LIMIT) {\n const batch = queue.splice(0, 6);\n const results = await Promise.all(batch.map(async (path) => ({ path, got: await get(path) })));\n\n for (const { path, got } of results) {\n if (!got || got.status !== 200 || !/html/.test(got.type)) continue;\n pages.push(factsOf(got.body, path, siteOrigin));\n for (const match of got.body.matchAll(/<a\\b[^>]*?\\shref\\s*=\\s*["\']([^"\'#?]+)/gi)) {\n let target;\n\n try {\n const url = new URL(match[1] ?? "", `http://dev.invalid${path}`);\n\n if (url.origin !== "http://dev.invalid" && (!siteOrigin || url.origin !== siteOrigin)) continue;\n target = url.pathname;\n } catch {\n continue;\n }\n if (!(target === `${base}/` || target.startsWith(`${base}/`)) || /\\.(?!html?$)[a-z0-9]+$/i.test(target) || /\\/(_astro|@|__)/.test(target)) continue;\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n }\n return pages.sort((a, b) => (a.path < b.path ? -1 : 1));\n };\n /** What the site serves itself, at the addresses the kit would write. */\n /** Whether the site serves this address itself (asking the dev server only when a route might). */\n const served = async (/** @type {string} */ local) => {\n const kind = siteServes(root, routes(), local);\n\n if (kind === "file" || kind === "route") return true;\n if (kind === null) return false;\n const got = await get(`${base}${local}`);\n\n return Boolean(got && got.status === 200 && !/html/.test(got.type));\n };\n const own = async () => {\n const [robots, index, sitemap, llms, full, agent] = await Promise.all(["robots.txt", "sitemap-index.xml", "sitemap.xml", "llms.txt", "llms-full.txt", "agent.md"].map((name) => served(`/${name}`)));\n\n return { robots: robots ? "robots.txt" : null, sitemap: index ? "sitemap-index.xml" : sitemap ? "sitemap.xml" : null, llmsTxt: Boolean(llms), llmsFullTxt: Boolean(full), agentPage: Boolean(agent) };\n };\n /** @param {PageFacts[]} pages @param {string} siteOrigin @param {Awaited<ReturnType<typeof own>>} owned */\n const plan = (pages, siteOrigin, owned) => {\n const { settings } = readSettings(root, file);\n const content = readSiteContent(root);\n\n return planSite({\n pages,\n settings,\n origin: siteOrigin,\n base,\n own: owned,\n drafts: content.drafts,\n dates: content.dates,\n patterns: content.patterns,\n fallbackName: content.name,\n fileExists: (path) => existsSync(join(root, "public", path.replace(/^\\/+/, ""))),\n });\n };\n const none = { robots: null, sitemap: null, llmsTxt: false, llmsFullTxt: false, agentPage: false };\n /**\n * The page, its ancestors and the home page: all a page\'s own output\n * needs. `html`: the page as it is being sent, so it isn\'t rendered twice.\n *\n * @param {string} path\n * @param {string} siteOrigin\n * @param {string} [html]\n */\n const around = async (path, siteOrigin, html) => {\n const segments = sitePath(path, base).split("/").filter(Boolean);\n const wanted = [`${base}/`, ...segments.slice(0, -1).map((_, index) => `${base}/${segments.slice(0, index + 1).join("/")}/`), path].filter((item) => html === undefined || item !== path);\n const found = await Promise.all([...new Set(wanted)].map((item) => facts(item, siteOrigin)));\n const pages = found.filter((item) => item !== null);\n\n return html === undefined ? pages : [...pages, factsOf(html, path, siteOrigin)];\n };\n\n return (req, res, next) => {\n if (req.headers[RAW_HEADER] || (req.method !== "GET" && req.method !== "HEAD")) return next();\n // The address as asked: under a base path Vite has already taken the base\n // off req.url by the time this runs; connect keeps the original.\n const [path = "/"] = (/** @type {{ originalUrl?: string }} */ (req).originalUrl ?? req.url ?? "/").split("?");\n\n if (path !== base && !path.startsWith(`${base}/`)) return next();\n const local = sitePath(path, base);\n const siteOrigin = origin || `http://${req.headers.host ?? "localhost"}`;\n /** @param {number} status @param {string} type @param {string} body */\n const send = (status, type, body) => {\n res.statusCode = status;\n res.setHeader("content-type", type);\n res.setHeader("cache-control", "no-store");\n res.end(req.method === "HEAD" ? "" : body);\n };\n\n if (isVisibilityAddress(local)) {\n void (async () => {\n // The site\'s own file or route at this address wins, as in a build.\n if (await served(local)) return next();\n const fileName = local.replace(/^\\//, "");\n\n if (local.endsWith(".md") && local !== "/agent.md") {\n for (const candidate of pagesForTwin(path, base)) {\n const pages = await around(candidate, siteOrigin);\n const page = pages.find((item) => item.path === candidate);\n\n if (!page) continue;\n const result = plan(pages, siteOrigin, none);\n const text = result.files[fileName];\n\n if (text !== undefined && twinPath(page.path, base) === path) return send(200, "text/markdown; charset=utf-8", text);\n }\n return next();\n }\n const owned = await own();\n const pages = local === "/robots.txt" ? [] : await crawl(siteOrigin);\n const result = plan(pages, siteOrigin, owned);\n const text = result.files[fileName];\n\n if (text === undefined) return next();\n return send(200, result.types[fileName] ?? "text/plain; charset=utf-8", text);\n })().catch(() => next());\n return;\n }\n const accept = String(req.headers.accept ?? "");\n\n if (/\\.[a-z0-9]+$/i.test(local) && !/\\.html?$/i.test(local)) return next();\n if (accept && !/text\\/html|\\*\\/\\*/.test(accept)) return next();\n interceptHtml(res, async (html) => {\n const pages = await around(path, siteOrigin, html);\n const addition = plan(pages, siteOrigin, none).head.get(path);\n\n if (!addition) return html;\n const kept = /type=["\']?text\\/markdown/i.test(html) ? addition.replace(/<link rel="alternate" type="text\\/markdown"[^>]*>/, "") : addition;\n\n return addToHead(html, kept);\n });\n next();\n };\n}\n\n/**\n * The integration\'s hooks for this part.\n *\n * @param {VisibilityOptions | false | undefined} options\n * @returns {Partial<import("astro").AstroIntegration["hooks"]>}\n */\nexport function visibilityHooks(options) {\n if (options === false) return {};\n const file = (options && options.file) || DEFAULT_FILE;\n let root = "";\n let origin = "";\n let base = "";\n let siteSitemap = false;\n /** @type {RouteInfo[]} */\n let routes = [];\n\n return {\n "astro:config:setup": ({ config, addWatchFile }) => {\n if (!config) return;\n const siteRoot = fileURLToPath(config.root).replace(/[\\\\/]+$/, "");\n\n // Read once here so a broken file stops the build with its message.\n readSettings(siteRoot, file);\n addWatchFile(join(siteRoot, file));\n },\n "astro:config:done": ({ config }) => {\n root = fileURLToPath(config.root).replace(/[\\\\/]+$/, "");\n ({ origin, base } = siteAddress(config));\n siteSitemap = (config.integrations ?? []).some((integration) => integration.name === "@astrojs/sitemap");\n },\n // In dev this runs again whenever a page file is added or removed.\n "astro:routes:resolved": ({ routes: resolved }) => {\n routes = resolved\n .filter((route) => route.origin !== "internal")\n .map((route) => ({ pattern: route.pattern, regex: route.patternRegex instanceof RegExp ? route.patternRegex : null, dynamic: route.params.length > 0 }));\n },\n "astro:server:setup": ({ server }) => {\n const self = () => {\n const address = server.httpServer?.address();\n\n if (!address || typeof address === "string") return "http://127.0.0.1:4321";\n const host = address.address === "::" || address.address === "0.0.0.0" ? "127.0.0.1" : address.family === "IPv6" || address.address.includes(":") ? `[${address.address}]` : address.address;\n\n return `http://${host}:${address.port}`;\n };\n\n server.middlewares.use(createDevMiddleware({ root, file, origin, base, self, routes: () => routes }));\n },\n "astro:build:done": ({ dir, logger }) => {\n const result = writeVisibility({ dir: fileURLToPath(dir), root, file, origin, base, siteSitemap });\n\n logger.info(result.summary);\n for (const note of result.notes) logger.info(` ${note}`);\n },\n };\n}\n', "visibility/markdown.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A rendered page \u2192 the markdown an AI agent reads: the page\'s main content\n// as visitors see it, however it was authored (content collections, section\n// blocks, hand-written Astro), with every address made absolute and nothing\n// that only works in a browser \u2014 no navigation, scripts, styles, forms,\n// cookie banner or tracking.\n//\n// What counts as the main content, in order:\n// 1. an element marked data-galley-agent="main";\n// 2. <main> (or role="main");\n// 3. the only <article>;\n// 4. <body> without its header, footer, nav and aside.\n// Inside it, anything marked data-galley-agent="skip", hidden, aria-hidden or\n// inert is left out; elements outside it marked data-galley-agent="include"\n// are added at the end, in page order.\n//\n// The same tree always gives the same bytes.\n\nimport { find, findAll, textOf } from "./html.js";\n\n/** @typedef {import("./html.js").Element} Element */\n/** @typedef {import("./html.js").Node} Node */\n\n/** Elements whose content is never part of the twin. */\nconst DROP = new Set([\n "script", "style", "noscript", "template", "svg", "math", "canvas", "object", "embed", "form", "button", "input", "select",\n "textarea", "option", "datalist", "nav", "dialog", "link", "meta", "head", "title", "map", "area", "slot", "progress", "meter",\n]);\nconst BLOCK = new Set([\n "address", "article", "aside", "blockquote", "body", "dd", "details", "div", "dl", "dt", "fieldset", "figcaption", "figure",\n "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", "main", "ol", "p", "pre", "section", "summary",\n "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", "menu", "iframe", "video", "audio", "caption", "search", "center",\n]);\nconst BREAK = "\\u0000";\n\n/**\n * @typedef {object} Context\n * @property {string} base The page\'s absolute address, for resolving links.\n * @property {string} page The page\'s own address without its fragment.\n */\n\n/** @param {Element} el */\nexport function isSkipped(el) {\n if (DROP.has(el.name)) return true;\n const attrs = el.attrs;\n\n if ("hidden" in attrs || "inert" in attrs || attrs["aria-hidden"] === "true") return true;\n if (attrs["data-galley-agent"] === "skip") return true;\n if (attrs.role === "navigation" || attrs.role === "search" || attrs.role === "dialog" || attrs.role === "alertdialog") return true;\n // The kit\'s own pieces that only mean something in a browser.\n if ("data-galley-consent" in attrs || "data-galley-form" in attrs || "data-galley-mailto" in attrs) return true;\n return false;\n}\n\n/**\n * The element whose content is the page\'s main content, and the extra\n * elements marked to be included.\n *\n * @param {Element} doc\n * @returns {{ root: Element | null; extra: Element[]; whole: boolean }}\n */\nexport function mainContent(doc) {\n const body = find(doc, (el) => el.name === "body") ?? doc;\n const marked = find(body, (el) => el.attrs["data-galley-agent"] === "main");\n /** @type {Element | null} */\n let root = marked ?? find(body, (el) => el.name === "main") ?? find(body, (el) => el.attrs.role === "main");\n let whole = false;\n\n if (!root) {\n const all = findAll(body, (el) => el.name === "article");\n const top = all.filter((el) => !all.some((other) => other !== el && contains(other, el)));\n\n if (top.length === 1) root = top[0] ?? null;\n }\n if (!root) {\n // No main region: the body, without the site\'s header, footer and sidebars.\n root = { ...body, children: body.children.filter((child) => !(child.type === "element" && (child.name === "header" || child.name === "footer" || child.name === "aside"))) };\n whole = true;\n }\n const chosen = root;\n const extra = whole ? [] : findAll(body, (el) => el.attrs["data-galley-agent"] === "include" && !contains(chosen, el), (el) => el === chosen);\n\n return { root, extra, whole };\n}\n\n/** @param {Element} outer @param {Element} inner */\nfunction contains(outer, inner) {\n for (let at = inner.parent; at; at = at.parent) if (at === outer) return true;\n return false;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 escaping\n\n/** Text as markdown text: the characters markdown would read as syntax are escaped. */\nexport function escapeText(/** @type {string} */ text) {\n return text\n .replace(/\\\\/g, "\\\\\\\\")\n .replace(/[`*[\\]]/g, (char) => `\\\\${char}`)\n .replace(/(^|[^\\p{L}\\p{N}])_|_(?=[^\\p{L}\\p{N}]|$)/gu, (match) => match.replace("_", "\\\\_"))\n .replace(/<(?=[a-zA-Z/!?])/g, "\\\\<")\n .replace(/&(?=#?[a-zA-Z0-9]+;)/g, "\\\\&");\n}\n\n/** A paragraph\'s first characters that would start a heading, quote or list. */\nfunction escapeStart(/** @type {string} */ line) {\n return line\n .replace(/^(#{1,6})(?=\\s|$)/, "\\\\$1")\n .replace(/^>/, "\\\\>")\n .replace(/^([-+])(?=\\s)/, "\\\\$1")\n .replace(/^(\\d+)([.)])(?=\\s)/, "$1\\\\$2")\n .replace(/^([-=])\\1*$/, (match) => `\\\\${match}`);\n}\n\n/** A link or image address that markdown reads in one piece. */\nfunction destination(/** @type {string} */ url) {\n return url.replace(/ /g, "%20").replace(/\\(/g, "%28").replace(/\\)/g, "%29").replace(/</g, "%3C").replace(/>/g, "%3E");\n}\n\n/** @param {string} href @param {Context} ctx @returns {string | null} */\nfunction absolute(href, ctx) {\n const value = href.trim();\n\n if (!value || /^(javascript|data|vbscript):/i.test(value)) return null;\n try {\n const url = new URL(value, ctx.base);\n\n if (!/^(https?|mailto|tel|ftp):$/.test(url.protocol)) return null;\n return url.href;\n } catch {\n return null;\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 inline\n\n/** @param {Element} el @returns {boolean} */\nfunction hasBlock(el) {\n return el.children.some((child) => child.type === "element" && !isSkipped(child) && (BLOCK.has(child.name) || hasBlock(child)));\n}\n\n/**\n * The inline markdown of a node\'s children (one line; hard breaks marked).\n *\n * @param {Node} node\n * @param {Context} ctx\n * @returns {string}\n */\nfunction inline(node, ctx) {\n if (node.type === "text") return escapeText(node.value);\n if (isSkipped(node)) return "";\n const inner = () => joinInline(node.children, ctx);\n\n switch (node.name) {\n case "br":\n return BREAK;\n case "wbr":\n return "";\n case "strong":\n case "b": {\n const text = inner();\n\n return text.trim() ? wrap(text, "**") : text;\n }\n case "em":\n case "i":\n case "cite": {\n const text = inner();\n\n return text.trim() ? wrap(text, "*") : text;\n }\n case "del":\n case "s": {\n const text = inner();\n\n return text.trim() ? wrap(text, "~~") : text;\n }\n case "code":\n case "kbd":\n case "samp":\n return codeSpan(textOf(node));\n case "img":\n return image(node, ctx);\n case "a":\n return link(node, inner(), ctx);\n case "picture": {\n const img = find(node, (el) => el.name === "img");\n\n return img ? image(img, ctx) : "";\n }\n default:\n return inner();\n }\n}\n\n/**\n * Inline children joined. Two elements side by side with no text between\n * them (a row of links, "By <a>\u2026</a><time>\u2026</time>") are usually set apart\n * by the page\'s layout, not by a space in the HTML: they get a space here so\n * their words don\'t run together.\n *\n * @param {Node[]} children\n * @param {Context} ctx\n */\nfunction joinInline(children, ctx) {\n let out = "";\n let lastElement = false;\n let gap = false;\n\n for (const child of children) {\n // A left-out element between two words (an aria-hidden "\xB7") stood for a gap.\n if (child.type === "element" && isSkipped(child)) {\n gap = true;\n continue;\n }\n const part = inline(child, ctx);\n\n if (!part) continue;\n const element = child.type === "element";\n // Text only screen readers hear ("Published") stands apart from its neighbours.\n const hiddenLabel = element && /(^|\\s)(visually-hidden|sr-only|screen-reader-text|galley-visually-hidden)(\\s|$)/.test(child.attrs.class ?? "");\n\n if (hiddenLabel) gap = true;\n if ((gap || (element && lastElement)) && out && !/[\\s\\u0000]$/.test(out) && !/^[\\s\\u0000.,;:!?)\\]]/.test(part) && !/[([]$/.test(out)) out += " ";\n out += part;\n lastElement = element;\n gap = hiddenLabel;\n }\n return out;\n}\n\n/** `**text**` with the spaces kept outside the markers, as markdown needs. */\nfunction wrap(/** @type {string} */ text, /** @type {string} */ marker) {\n const lead = /^\\s*/.exec(text)?.[0] ?? "";\n const trail = /\\s*$/.exec(text)?.[0] ?? "";\n\n return `${lead}${marker}${text.trim()}${marker}${trail}`;\n}\n\nfunction codeSpan(/** @type {string} */ text) {\n if (!text) return "";\n const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length));\n const fence = "`".repeat(longest + 1);\n const pad = longest > 0 || text.startsWith("`") || text.endsWith("`") ? " " : "";\n\n return `${fence}${pad}${text}${pad}${fence}`;\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction image(el, ctx) {\n const alt = (el.attrs.alt ?? "").replace(/\\s+/g, " ").trim();\n const src = absolute(el.attrs.src ?? "", ctx);\n\n // An empty alt marks a decorative image: there is nothing to say about it.\n if (!alt || !src) return "";\n return `})`;\n}\n\n/** @param {Element} el @param {string} text @param {Context} ctx */\nfunction link(el, text, ctx) {\n const href = el.attrs.href ?? "";\n const label = text.replace(new RegExp(BREAK, "g"), " ").trim() || escapeText((el.attrs["aria-label"] ?? el.attrs.title ?? "").trim());\n const url = absolute(href, ctx);\n\n if (!label) return "";\n // A link to a part of this same page means nothing outside it.\n if (!url || href.trim().startsWith("#") || url.split("#")[0] === ctx.page) return text;\n return `[${label}](${destination(url)})`;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 blocks\n\n/**\n * @param {Element} el\n * @param {Context} ctx\n * @returns {string[]}\n */\nfunction blocks(el, ctx) {\n /** @type {string[]} */\n const out = [];\n let run = "";\n /** @type {Node[]} */\n let pending = [];\n const flush = () => {\n run += joinInline(pending, ctx);\n pending = [];\n const text = finishInline(run);\n\n if (text) out.push(escapeStart(text));\n run = "";\n };\n\n for (const child of el.children) {\n if (child.type === "text" || isSkipped(child)) {\n pending.push(child);\n continue;\n }\n if (child.name === "a" && hasBlock(child)) {\n flush();\n out.push(...linkedBlocks(child, ctx));\n continue;\n }\n if (!BLOCK.has(child.name) && !hasBlock(child)) {\n pending.push(child);\n continue;\n }\n flush();\n out.push(...block(child, ctx));\n }\n flush();\n return out;\n}\n\n/** Inline text as one paragraph: whitespace collapsed, hard breaks kept inside it. */\nfunction finishInline(/** @type {string} */ run) {\n return run\n .replace(/[ \\t\\r\\n\\f\xA0]+/g, (space) => (space.includes("\xA0") && !/[\\r\\n]/.test(space) ? "\xA0" : " "))\n .replace(/ ?\\u0000 ?/g, BREAK)\n .replace(/^[\\s\\u0000]+|[\\s\\u0000]+$/g, "")\n .replace(/\\u0000+/g, "\\\\\\n");\n}\n\n/**\n * A card-like link around headings and paragraphs: its blocks, with the\n * first heading (or else the first paragraph) carrying the link.\n *\n * @param {Element} el\n * @param {Context} ctx\n */\nfunction linkedBlocks(el, ctx) {\n const inner = blocks(el, ctx);\n const url = absolute(el.attrs.href ?? "", ctx);\n\n if (!url || (el.attrs.href ?? "").startsWith("#")) return inner;\n const index = Math.max(0, inner.findIndex((text) => /^#{1,6} /.test(text)));\n const first = inner[index];\n\n if (first === undefined) return inner;\n const heading = /^(#{1,6} )(.*)$/s.exec(first);\n\n // Links can\'t hold links: a block that has its own stays as it is.\n if (first.includes("](")) return inner;\n if (heading) inner[index] = `${heading[1]}[${heading[2]}](${destination(url)})`;\n else if (!/^(!\\[|\\||```|>|-|\\d+\\.)/.test(first)) inner[index] = `[${first}](${destination(url)})`;\n return inner;\n}\n\n/**\n * @param {Element} el\n * @param {Context} ctx\n * @returns {string[]}\n */\nfunction block(el, ctx) {\n const name = el.name;\n\n if (/^h[1-6]$/.test(name)) {\n const text = finishInline(joinInline(el.children, ctx)).replace(/\\\\\\n/g, " ");\n\n return text ? [`${"#".repeat(Number(name[1]))} ${text}`] : [];\n }\n switch (name) {\n case "p":\n case "summary":\n case "dt":\n case "caption":\n case "figcaption": {\n if (hasBlock(el)) return blocks(el, ctx);\n const text = finishInline(joinInline(el.children, ctx));\n\n if (!text) return [];\n return [escapeStart(name === "summary" || name === "dt" ? (/^\\*\\*.*\\*\\*$/.test(text) ? text : `**${text}**`) : text)];\n }\n case "hr":\n return ["---"];\n case "ul":\n case "ol":\n case "menu":\n return list(el, ctx);\n case "blockquote": {\n const inner = blocks(el, ctx).join("\\n\\n");\n\n return inner ? [inner.split("\\n").map((line) => (line ? `> ${line}` : ">")).join("\\n")] : [];\n }\n case "pre":\n return codeBlock(el);\n case "table":\n return table(el, ctx);\n case "iframe":\n case "video":\n case "audio":\n return media(el, ctx);\n default:\n return blocks(el, ctx);\n }\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction list(el, ctx) {\n const ordered = el.name === "ol";\n const start = Number.parseInt(el.attrs.start ?? "1", 10);\n /** @type {string[]} */\n const items = [];\n let number = Number.isFinite(start) ? start : 1;\n\n for (const child of el.children) {\n if (child.type !== "element" || isSkipped(child)) continue;\n const content = child.name === "li" ? blocks(child, ctx) : block(child, ctx);\n\n if (content.length === 0) continue;\n const marker = ordered ? `${number}.` : "-";\n const indent = " ".repeat(marker.length + 1);\n const lines = content\n .map((part, index) => {\n const indented = part.split("\\n").map((line, at) => (index === 0 && at === 0 ? line : line ? `${indent}${line}` : ""));\n\n return indented.join("\\n");\n })\n .reduce((all, part, index) => {\n if (index === 0) return part;\n // A nested list follows its item directly; other blocks get a blank line.\n const tight = /^\\s*(-|\\d+\\.) /.test(part);\n\n return `${all}${tight ? "\\n" : "\\n\\n"}${part}`;\n }, "");\n\n items.push(`${marker} ${lines}`);\n number += 1;\n }\n return items.length ? [items.join("\\n")] : [];\n}\n\n/** @param {Element} el */\nfunction codeBlock(el) {\n const code = find(el, (child) => child.name === "code");\n const className = `${code?.attrs.class ?? ""} ${el.attrs.class ?? ""}`;\n const language = el.attrs["data-language"] ?? /(?:^|\\s)(?:language|lang)-([\\w+#.-]+)/.exec(className)?.[1] ?? "";\n /** @param {import("./html.js").Node} node @returns {string} */\n const raw = (node) => (node.type === "text" ? node.value : node.name === "br" ? "\\n" : node.children.map(raw).join(""));\n const text = raw(code ?? el).replace(/^\\n/, "").replace(/\\s+$/, "");\n\n if (!text) return [];\n const longest = Math.max(2, ...[...text.matchAll(/^`{3,}/gm)].map((match) => match[0].length));\n const fence = "`".repeat(longest + 1);\n\n return [`${fence}${language === "plaintext" || language === "text" ? "" : language}\\n${text}\\n${fence}`];\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction table(el, ctx) {\n const rows = findAll(el, (child) => child.name === "tr", (child) => child.name === "table");\n const cells = rows\n .map((row) =>\n row.children\n .filter((cell) => cell.type === "element" && (cell.name === "td" || cell.name === "th"))\n .map((cell) =>\n finishInline(/** @type {Element} */ (cell).children.map((child) => (child.type === "element" && BLOCK.has(child.name) ? ` ${block(/** @type {Element} */ (child), ctx).join(" ")} ` : inline(child, ctx))).join(""))\n .replace(/\\\\\\n/g, " ")\n .replace(/\\n+/g, " ")\n .replace(/\\|/g, "\\\\|"),\n ),\n )\n .filter((row) => row.length > 0);\n const width = Math.max(0, ...cells.map((row) => row.length));\n\n if (cells.length === 0 || width === 0) return [];\n const pad = (/** @type {string[]} */ row) => [...row, ...Array(width - row.length).fill("")];\n const line = (/** @type {string[]} */ row) => `| ${pad(row).join(" | ")} |`.replace(/ {2,}\\|/g, " |");\n const caption = find(el, (child) => child.name === "caption");\n const out = [line(cells[0] ?? []), `| ${Array(width).fill("---").join(" | ")} |`, ...cells.slice(1).map(line)].join("\\n");\n\n return caption ? [...block(caption, ctx), out] : [out];\n}\n\n/** An embedded video, recording or frame: a link to it, named by its title. */\nfunction media(/** @type {Element} */ el, /** @type {Context} */ ctx) {\n const source = el.attrs.src ?? find(el, (child) => child.name === "source")?.attrs.src ?? "";\n const url = absolute(source, ctx);\n const label = (el.attrs.title ?? el.attrs["aria-label"] ?? "").trim();\n\n if (!url || !label) return [];\n return [`[${escapeText(label)}](${destination(url)})`];\n}\n\n/**\n * The markdown of the main content of a parsed page.\n *\n * @param {Element} doc\n * @param {{ url: string }} page The page\'s absolute address.\n * @returns {{ markdown: string; hasH1: boolean; whole: boolean }}\n */\nexport function pageMarkdown(doc, page) {\n const { root, extra, whole } = mainContent(doc);\n const ctx = { base: page.url, page: page.url.split("#")[0] ?? page.url };\n const parts = [...(root ? blocks(root, ctx) : []), ...extra.flatMap((el) => (isSkipped(el) ? [] : BLOCK.has(el.name) ? block(el, ctx) : blocks({ ...el, children: [el] }, ctx)))];\n const markdown = parts.filter((part) => part.trim()).join("\\n\\n");\n\n return { markdown, hasH1: /^# /m.test(markdown), whole };\n}\n', "visibility/page.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163419
|
+
`, "visibility/html.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A small, tolerant HTML reader for the pages a site builds: enough of the\n// HTML parsing rules to turn Astro\'s (and any static generator\'s) output\n// into a tree \u2014 void elements, raw-text elements, comments, entities, the\n// common implied end tags \u2014 and no more. The kit depends on nothing but\n// Astro, so it can\'t bring a full parser; built pages are regular enough,\n// and everything built from this tree only ever reports what it found.\n\n/**\n * @typedef {object} Element\n * @property {"element"} type\n * @property {string} name Lower-case tag name.\n * @property {Record<string, string>} attrs Lower-case names, decoded values.\n * @property {Node[]} children\n * @property {Element | null} parent\n */\n/** @typedef {{ type: "text"; value: string; parent: Element | null }} Text */\n/** @typedef {Element | Text} Node */\n\nconst VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);\nconst RAW = new Set(["script", "style", "textarea", "title", "xmp", "noscript", "template", "iframe", "noembed", "noframes"]);\n/** Opening one of these closes an open <p> (HTML\'s "close a p element"). */\nconst CLOSES_P = new Set([\n "address", "article", "aside", "blockquote", "details", "dialog", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form",\n "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "main", "menu", "nav", "ol", "p", "pre", "section", "table", "ul",\n]);\n\nconst NAMED = /** @type {Record<string, string>} */ ({\n amp: "&", lt: "<", gt: ">", quot: \'"\', apos: "\'", nbsp: "\xA0", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009",\n ndash: "\u2013", mdash: "\u2014", hellip: "\u2026", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C",\n rdquo: "\u201D", bdquo: "\u201E", laquo: "\xAB", raquo: "\xBB", lsaquo: "\u2039", rsaquo: "\u203A", middot: "\xB7",\n bull: "\u2022", copy: "\xA9", reg: "\xAE", trade: "\u2122", times: "\xD7", divide: "\xF7", deg: "\xB0", euro: "\u20AC",\n pound: "\xA3", yen: "\xA5", cent: "\xA2", sect: "\xA7", para: "\xB6", plusmn: "\xB1", frac12: "\xBD",\n frac14: "\xBC", frac34: "\xBE", larr: "\u2190", rarr: "\u2192", uarr: "\u2191", darr: "\u2193", harr: "\u2194",\n check: "\u2713", minus: "\u2212", prime: "\u2032", Prime: "\u2033", shy: "\xAD", zwj: "\u200D", zwnj: "\u200C",\n eacute: "\xE9", egrave: "\xE8", aacute: "\xE1", agrave: "\xE0", iacute: "\xED", oacute: "\xF3", uacute: "\xFA",\n ouml: "\xF6", uuml: "\xFC", auml: "\xE4", szlig: "\xDF", ccedil: "\xE7", ntilde: "\xF1", colon: ":", sol: "/",\n num: "#", lpar: "(", rpar: ")", lsqb: "[", rsqb: "]", lowbar: "_", ast: "*", grave: "`", vert: "|", equals: "=",\n});\n\n/** Character references \u2192 characters. Unknown names stay as written. */\nexport function decodeEntities(/** @type {string} */ text) {\n if (!text.includes("&")) return text;\n return text.replace(/&(#x[0-9a-f]+|#\\d+|[a-z][a-z0-9]*);?/gi, (whole, ref) => {\n if (ref[0] === "#") {\n const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n\n return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;\n }\n const named = NAMED[ref];\n\n return named === undefined ? whole : named;\n });\n}\n\n/** @param {string} name @param {Element | null} parent @returns {Element} */\nfunction element(name, parent) {\n return { type: "element", name, attrs: {}, children: [], parent };\n}\n\n/**\n * Reads the attributes of a start tag (the text between the name and `>`).\n *\n * @param {string} source\n * @returns {Record<string, string>}\n */\nfunction readAttributes(source) {\n /** @type {Record<string, string>} */\n const attrs = {};\n const pattern = /([^\\s"\'>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\'|([^\\s>]+)))?/g;\n\n for (const match of source.matchAll(pattern)) {\n const name = (match[1] ?? "").toLowerCase();\n\n if (!name || name in attrs) continue;\n attrs[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");\n }\n return attrs;\n}\n\n/** Where a start tag ends: the first `>` outside quotes. */\nfunction tagEnd(/** @type {string} */ html, /** @type {number} */ from) {\n let quote = "";\n\n for (let index = from; index < html.length; index += 1) {\n const char = html[index];\n\n if (quote) {\n if (char === quote) quote = "";\n } else if (char === \'"\' || char === "\'") quote = char;\n else if (char === ">") return index;\n }\n return -1;\n}\n\n/**\n * The document as a tree under a root element named "#document".\n *\n * @param {string} html\n * @returns {Element}\n */\nexport function parseHtml(html) {\n const root = element("#document", null);\n /** @type {Element[]} */\n const stack = [root];\n const current = () => /** @type {Element} */ (stack[stack.length - 1]);\n /** @param {string} value */\n const addText = (value) => {\n if (!value) return;\n const parent = current();\n const last = parent.children[parent.children.length - 1];\n\n if (last && last.type === "text") last.value += value;\n else parent.children.push({ type: "text", value, parent });\n };\n /** Closes the innermost open `name`, and everything opened inside it. */\n const close = (/** @type {string} */ name) => {\n for (let index = stack.length - 1; index > 0; index -= 1) {\n if (stack[index]?.name === name) {\n stack.length = index;\n return true;\n }\n }\n return false;\n };\n /** Whether `name` is open, without crossing one of `scope`. */\n const openWithin = (/** @type {string} */ name, /** @type {Set<string>} */ scope) => {\n for (let index = stack.length - 1; index > 0; index -= 1) {\n const open = stack[index]?.name ?? "";\n\n if (open === name) return true;\n if (scope.has(open)) return false;\n }\n return false;\n };\n const LIST_SCOPE = new Set(["ul", "ol", "menu", "table", "div", "section", "article", "main", "body"]);\n const DL_SCOPE = new Set(["dl", "table", "div", "section", "article", "main", "body"]);\n const TABLE_SCOPE = new Set(["table"]);\n let at = 0;\n\n while (at < html.length) {\n const lt = html.indexOf("<", at);\n\n if (lt === -1) {\n addText(decodeEntities(html.slice(at)));\n break;\n }\n if (lt > at) addText(decodeEntities(html.slice(at, lt)));\n if (html.startsWith("<!--", lt)) {\n const end = html.indexOf("-->", lt + 4);\n\n at = end === -1 ? html.length : end + 3;\n continue;\n }\n if (html[lt + 1] === "!" || html[lt + 1] === "?") {\n const end = html.indexOf(">", lt);\n\n at = end === -1 ? html.length : end + 1;\n continue;\n }\n if (html[lt + 1] === "/") {\n const match = /^<\\/([a-zA-Z][^\\s/>]*)[^>]*>/.exec(html.slice(lt, lt + 200));\n\n if (!match) {\n addText("<");\n at = lt + 1;\n continue;\n }\n close((match[1] ?? "").toLowerCase());\n at = lt + match[0].length;\n continue;\n }\n const nameMatch = /^<([a-zA-Z][^\\s/>]*)/.exec(html.slice(lt, lt + 100));\n\n if (!nameMatch) {\n addText("<");\n at = lt + 1;\n continue;\n }\n const end = tagEnd(html, lt + nameMatch[0].length);\n\n if (end === -1) {\n addText(decodeEntities(html.slice(lt)));\n break;\n }\n const name = (nameMatch[1] ?? "").toLowerCase();\n const node = element(name, null);\n\n node.attrs = readAttributes(html.slice(lt + nameMatch[0].length, end).replace(/\\/\\s*$/, ""));\n // The implied end tags built pages rely on most.\n if (CLOSES_P.has(name) && openWithin("p", new Set(["button", "table", "td", "th"]))) close("p");\n if (name === "li" && openWithin("li", LIST_SCOPE)) close("li");\n if ((name === "dt" || name === "dd") && (openWithin("dt", DL_SCOPE) || openWithin("dd", DL_SCOPE))) {\n if (!close("dd")) close("dt");\n }\n if (name === "tr" && openWithin("tr", TABLE_SCOPE)) close("tr");\n if ((name === "td" || name === "th") && (openWithin("td", new Set(["tr", "table"])) || openWithin("th", new Set(["tr", "table"])))) {\n if (!close("td")) close("th");\n }\n if (name === "option" && openWithin("option", new Set(["select", "datalist"]))) close("option");\n node.parent = current();\n current().children.push(node);\n at = end + 1;\n if (VOID.has(name)) continue;\n if (RAW.has(name)) {\n const closeAt = html.toLowerCase().indexOf(`</${name}`, at);\n const text = html.slice(at, closeAt === -1 ? html.length : closeAt);\n\n if (text) node.children.push({ type: "text", value: name === "title" || name === "textarea" ? decodeEntities(text) : text, parent: node });\n if (closeAt === -1) break;\n const closeEnd = html.indexOf(">", closeAt);\n\n at = closeEnd === -1 ? html.length : closeEnd + 1;\n continue;\n }\n // `<path \u2026 />` in inline SVG closes itself (foreign content). HTML\n // elements written that way are treated the same: generators that emit\n // `<div />` mean an empty element too.\n if (html[end - 1] === "/") continue;\n stack.push(node);\n }\n return root;\n}\n\n/**\n * Every element under `node` (depth first, document order) for which `test`\n * is true. `skip` prunes a subtree.\n *\n * @param {Element} node\n * @param {(el: Element) => boolean} test\n * @param {(el: Element) => boolean} [skip]\n * @returns {Element[]}\n */\nexport function findAll(node, test, skip) {\n /** @type {Element[]} */\n const out = [];\n /** @param {Element} at */\n const walk = (at) => {\n for (const child of at.children) {\n if (child.type !== "element") continue;\n if (skip && skip(child)) continue;\n if (test(child)) out.push(child);\n walk(child);\n }\n };\n\n walk(node);\n return out;\n}\n\n/**\n * The first element under `node` for which `test` is true.\n *\n * @param {Element} node\n * @param {(el: Element) => boolean} test\n * @returns {Element | null}\n */\nexport function find(node, test) {\n for (const child of node.children) {\n if (child.type !== "element") continue;\n if (test(child)) return child;\n const inner = find(child, test);\n\n if (inner) return inner;\n }\n return null;\n}\n\n/** The text of a subtree, whitespace collapsed. Raw-text elements count as no text. */\nexport function textOf(/** @type {Node} */ node) {\n /** @type {string[]} */\n const parts = [];\n /** @param {Node} at */\n const walk = (at) => {\n if (at.type === "text") {\n parts.push(at.value);\n return;\n }\n if (at.name === "script" || at.name === "style" || at.name === "template" || at.name === "noscript") return;\n for (const child of at.children) walk(child);\n if (at.name === "br") parts.push(" ");\n };\n\n walk(node);\n return parts.join("").replace(/\\s+/g, " ").trim();\n}\n\n/** Whether the element (or one of its ancestors) is `name`. */\nexport function within(/** @type {Element | null} */ node, /** @type {string} */ name) {\n for (let at = node; at; at = at.parent) if (at.name === name) return true;\n return false;\n}\n', "visibility/integration.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The agent-readable output as an Astro integration part: after `astro\n// build` it reads every page the build wrote and adds the markdown twins,\n// llms.txt, llms-full.txt, agent.md, robots.txt, sitemap.xml and the tags\n// each page\'s <head> gains; in `astro dev` the same addresses answer, made\n// on request from the pages the dev server renders, so a preview shows what\n// a build will publish. No page gains any JavaScript.\n//\n// Used by the package\'s integration (galley({ visibility })) and, vendored,\n// as src/galley/integration.js (scripts/vendor.mjs).\n\nimport { existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs";\nimport { dirname, join, relative, sep } from "node:path";\nimport { fileURLToPath } from "node:url";\nimport { DEFAULT_FILE, readSettings } from "./config.js";\nimport { readSiteContent } from "./content.js";\nimport { addToHead, readPage } from "./page.js";\nimport { pagesForTwin, planSite, sitePath, twinPath } from "./site.js";\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {import("./site.js").SiteInput} SiteInput */\n\n/** The header the dev server\'s own requests carry, so they get the page as rendered. */\nexport const RAW_HEADER = "x-galley-visibility";\n/** Pages a dev server answer crawls at most (llms.txt, the sitemap). */\nexport const DEV_CRAWL_LIMIT = 500;\n/** Placeholder host for a site with no `site` address; removed from what is written. */\nconst NO_ORIGIN = "https://site.invalid";\n\n/**\n * @typedef {object} VisibilityOptions\n * @property {string} [file] The data file. Default "src/data/visibility.json".\n */\n\n/** @param {string} dir @returns {string[]} HTML files under dir, relative, "/"-separated, sorted. */\nfunction htmlFiles(dir) {\n /** @type {string[]} */\n const out = [];\n /** @param {string} at */\n const walk = (at) => {\n for (const name of readdirSync(at)) {\n const path = join(at, name);\n const info = statSync(path);\n\n if (info.isDirectory()) walk(path);\n else if (name.endsWith(".html")) out.push(relative(dir, path).split(sep).join("/"));\n }\n };\n\n walk(dir);\n return out.sort();\n}\n\n/** "about/index.html" \u2192 "/demo/about/"; "about.html" \u2192 "/demo/about"; "index.html" \u2192 "/demo/". */\nexport function pagePath(/** @type {string} */ file, /** @type {string} */ base) {\n if (file === "index.html") return `${base}/`;\n if (file.endsWith("/index.html")) return `${base}/${file.slice(0, -"index.html".length)}`;\n return `${base}/${file.replace(/\\.html$/, "")}`;\n}\n\n/** The site\'s origin and base path from Astro\'s config. */\nexport function siteAddress(/** @type {{ site?: string | URL | undefined; base?: string }} */ config) {\n let origin = "";\n\n try {\n origin = config.site ? new URL(String(config.site)).origin : "";\n } catch {\n origin = "";\n }\n return { origin, base: (config.base ?? "/").replace(/\\/+$/, "") };\n}\n\n/** Facts read with a placeholder origin, with the placeholder taken out again. */\nfunction withoutPlaceholder(/** @type {PageFacts} */ facts) {\n const strip = (/** @type {string} */ value) => value.split(NO_ORIGIN).join("");\n\n return {\n ...facts,\n url: strip(facts.url),\n canonical: facts.canonical ? strip(facts.canonical) : null,\n image: strip(facts.image),\n markdown: strip(facts.markdown),\n feeds: facts.feeds.map((feed) => ({ ...feed, href: strip(feed.href) })),\n };\n}\n\n/** @param {string} html @param {string} path @param {string} origin */\nfunction factsOf(html, path, origin) {\n const facts = readPage(html, { path, url: `${origin || NO_ORIGIN}${path}` });\n\n return origin ? facts : withoutPlaceholder(facts);\n}\n\n/**\n * Writes the agent-readable output into a finished build.\n *\n * @param {object} input\n * @param {string} input.dir The build\'s output folder.\n * @param {string} input.root The site\'s folder.\n * @param {string} input.file The data file, relative to the site.\n * @param {string} input.origin\n * @param {string} input.base\n * @param {boolean} [input.siteSitemap] An integration (such as @astrojs/sitemap) writes the sitemap.\n * @returns {{ notes: string[]; summary: string; written: string[]; changedPages: number; ms: number }}\n */\nexport function writeVisibility({ dir, root, file, origin, base, siteSitemap = false }) {\n const started = performance.now();\n const { settings } = readSettings(root, file);\n const content = readSiteContent(root);\n const files = htmlFiles(dir);\n const pages = files.map((name) => factsOf(readFileSync(join(dir, name), "utf8"), pagePath(name, base), origin));\n const has = (/** @type {string} */ name) => existsSync(join(dir, name));\n const plan = planSite({\n pages,\n settings,\n origin,\n base,\n own: {\n robots: has("robots.txt") ? "robots.txt" : null,\n sitemap: has("sitemap-index.xml") || siteSitemap ? "sitemap-index.xml" : has("sitemap.xml") ? "sitemap.xml" : null,\n llmsTxt: has("llms.txt"),\n llmsFullTxt: has("llms-full.txt"),\n agentPage: has("agent.md"),\n },\n drafts: content.drafts,\n dates: content.dates,\n patterns: content.patterns,\n fallbackName: content.name,\n fileExists: (path) => has(path.replace(/^\\/+/, "")) || existsSync(join(root, "public", path.replace(/^\\/+/, ""))),\n });\n const notes = [...plan.notes];\n /** @type {string[]} */\n const written = [];\n let changedPages = 0;\n\n for (const name of files) {\n const addition = plan.head.get(pagePath(name, base));\n\n if (!addition) continue;\n const path = join(dir, name);\n const html = readFileSync(path, "utf8");\n // A page that already links its markdown version keeps its own link.\n const kept = /type=["\']?text\\/markdown/i.test(html) ? addition.replace(/<link rel="alternate" type="text\\/markdown"[^>]*>/, "") : addition;\n const next = addToHead(html, kept);\n\n if (next !== html) {\n writeFileSync(path, next);\n changedPages += 1;\n }\n }\n for (const [name, text] of Object.entries(plan.files)) {\n const path = join(dir, ...name.split("/"));\n\n if (existsSync(path)) {\n if (name.endsWith(".md")) notes.push(`${base}/${name} is already one of the site\'s files; the kit\'s markdown version of that page was not written.`);\n continue;\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, text);\n written.push(name);\n }\n const c = plan.counts;\n const extras = ["llms.txt", "llms-full.txt", "agent.md", "robots.txt", "sitemap.xml"].filter((name) => written.includes(name));\n const summary =\n `visibility: ${c.listed} of ${c.pages} pages listed \xB7 ${c.twins} markdown versions \xB7 structured data on ${c.structured} pages` +\n (extras.length ? ` \xB7 ${extras.join(", ")}` : "") +\n (c.fullTruncated ? " (llms-full.txt cut at its size limit)" : "") +\n ` \xB7 ${Math.round(performance.now() - started)} ms`;\n\n return { notes, summary, written, changedPages, ms: performance.now() - started };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 astro dev\n\n/**\n * @typedef {object} Fetched\n * @property {number} status\n * @property {string} type\n * @property {string} body\n */\n\n/** Addresses the kit answers in dev (without the base). */\nexport function isVisibilityAddress(/** @type {string} */ local) {\n return /^\\/(llms\\.txt|llms-full\\.txt|agent\\.md|robots\\.txt|sitemap\\.xml|sitemap-\\d+\\.xml)$/.test(local) || (/\\.md$/.test(local) && !local.startsWith("/_") && !local.startsWith("/@"));\n}\n\n/**\n * A written chunk as bytes. Astro\'s dev server writes pages as `Uint8Array`s\n * (not Buffers): turning one into a string gives "60,33,68,\u2026", which is what\n * every page became. Strings honour the encoding passed alongside them.\n * @param {unknown} chunk\n * @param {unknown} [encoding]\n * @returns {Buffer}\n */\nexport function toBuffer(chunk, encoding) {\n if (Buffer.isBuffer(chunk)) return chunk;\n if (chunk instanceof Uint8Array) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n if (ArrayBuffer.isView(chunk)) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n if (chunk instanceof ArrayBuffer) return Buffer.from(chunk);\n return Buffer.from(String(chunk), typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8");\n}\n\n/**\n * Buffers a dev server\'s HTML answer so it can be changed before it is sent.\n * Anything else passes through untouched.\n *\n * @param {import("node:http").ServerResponse} res\n * @param {(html: string) => Promise<string>} transform\n */\nexport function interceptHtml(res, transform) {\n const original = { writeHead: res.writeHead.bind(res), write: res.write.bind(res), end: res.end.bind(res) };\n /** @type {Buffer[]} */\n const chunks = [];\n /** @type {boolean | null} */\n let buffering = null;\n const restore = () => {\n res.writeHead = original.writeHead;\n res.write = original.write;\n res.end = original.end;\n };\n const decide = () => {\n if (buffering !== null) return buffering;\n const type = String(res.getHeader("content-type") ?? "");\n\n buffering = res.statusCode === 200 && /text\\/html/i.test(type) && !res.getHeader("content-encoding");\n if (!buffering) restore();\n return buffering;\n };\n const anyRes = /** @type {any} */ (res);\n\n anyRes.writeHead = (/** @type {number} */ status, /** @type {any[]} */ ...rest) => {\n const headers = rest.find((item) => item && typeof item === "object");\n\n if (typeof rest[0] === "string") res.statusMessage = rest[0];\n res.statusCode = status;\n if (Array.isArray(headers)) for (let index = 0; index + 1 < headers.length; index += 2) res.setHeader(String(headers[index]), headers[index + 1]);\n else if (headers) for (const [name, value] of Object.entries(headers)) if (value !== undefined) res.setHeader(name, /** @type {any} */ (value));\n if (!decide()) return original.writeHead(res.statusCode);\n return res;\n };\n anyRes.write = (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) => {\n if (!decide()) return original.write(chunk, ...rest);\n if (chunk !== undefined && chunk !== null && typeof chunk !== "function") chunks.push(toBuffer(chunk, rest[0]));\n return true;\n };\n anyRes.end = (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) => {\n if (!decide()) return original.end(chunk, ...rest);\n if (chunk !== undefined && chunk !== null && typeof chunk !== "function") chunks.push(toBuffer(chunk, rest[0]));\n const html = Buffer.concat(chunks).toString("utf8");\n\n restore();\n transform(html)\n .catch(() => html)\n .then((out) => {\n if (!res.headersSent) {\n res.setHeader("content-length", Buffer.byteLength(out));\n original.writeHead(res.statusCode);\n }\n original.end(out);\n });\n return res;\n };\n}\n\n/** @typedef {{ pattern: string; regex: RegExp | null; dynamic: boolean }} RouteInfo */\n\n/**\n * Whether the site itself may serve `local` (an address without the base):\n * a file in public/, a route for exactly that address, or a dynamic route\n * ending in the same extension ("/[twin].md"). Only then is the dev server\n * asked \u2014 so a catch-all page route ("/[...slug]") isn\'t asked for every\n * generated address, and doesn\'t log a note for each.\n *\n * @param {string} root\n * @param {RouteInfo[]} routes\n * @param {string} local\n * @returns {"file" | "route" | "maybe" | null}\n */\nexport function siteServes(root, routes, local) {\n if (existsSync(join(root, "public", ...local.split("/").filter(Boolean)))) return "file";\n if (routes.some((route) => !route.dynamic && route.pattern === local)) return "route";\n const extension = /\\.[a-z0-9]+$/i.exec(local)?.[0];\n\n if (extension && routes.some((route) => route.dynamic && route.pattern.endsWith(extension) && (!route.regex || route.regex.test(local)))) return "maybe";\n return null;\n}\n\n/**\n * The dev server\'s answers: the generated addresses, and the extra <head>\n * tags on every page. Reads the data file on every request, so edits show\n * at once.\n *\n * @param {object} input\n * @param {string} input.root\n * @param {string} input.file\n * @param {string} input.origin The site\'s own origin ("" when unknown).\n * @param {string} input.base\n * @param {() => string} input.self The dev server\'s own origin, for its requests to itself.\n * @param {() => RouteInfo[]} [input.routes] The site\'s routes (astro:routes:resolved), to know which addresses it serves itself.\n * @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, next: () => void) => void}\n */\nexport function createDevMiddleware({ root, file, origin, base, self, routes = () => [] }) {\n /** @type {Map<string, { at: number; value: Promise<Fetched | null> }>} */\n const cache = new Map();\n /** @param {string} path @returns {Promise<Fetched | null>} */\n const get = (path) => {\n const hit = cache.get(path);\n\n if (hit && Date.now() - hit.at < 2000) return hit.value;\n const value = fetch(`${self()}${path}`, { headers: { [RAW_HEADER]: "raw", accept: "text/html,*/*" }, redirect: "follow" })\n .then(async (response) => ({ status: response.status, type: response.headers.get("content-type") ?? "", body: await response.text() }))\n .catch(() => null);\n\n cache.set(path, { at: Date.now(), value });\n return value;\n };\n /** @param {string} path @param {string} siteOrigin */\n const facts = async (path, siteOrigin) => {\n const got = await get(path);\n\n return got && got.status === 200 && /html/.test(got.type) ? factsOf(got.body, path, siteOrigin) : null;\n };\n /** Pages reachable from the home page by links, at most DEV_CRAWL_LIMIT. */\n const crawl = async (/** @type {string} */ siteOrigin) => {\n const seen = new Set([`${base}/`]);\n const queue = [`${base}/`];\n /** @type {PageFacts[]} */\n const pages = [];\n\n while (queue.length && pages.length < DEV_CRAWL_LIMIT) {\n const batch = queue.splice(0, 6);\n const results = await Promise.all(batch.map(async (path) => ({ path, got: await get(path) })));\n\n for (const { path, got } of results) {\n if (!got || got.status !== 200 || !/html/.test(got.type)) continue;\n pages.push(factsOf(got.body, path, siteOrigin));\n for (const match of got.body.matchAll(/<a\\b[^>]*?\\shref\\s*=\\s*["\']([^"\'#?]+)/gi)) {\n let target;\n\n try {\n const url = new URL(match[1] ?? "", `http://dev.invalid${path}`);\n\n if (url.origin !== "http://dev.invalid" && (!siteOrigin || url.origin !== siteOrigin)) continue;\n target = url.pathname;\n } catch {\n continue;\n }\n if (!(target === `${base}/` || target.startsWith(`${base}/`)) || /\\.(?!html?$)[a-z0-9]+$/i.test(target) || /\\/(_astro|@|__)/.test(target)) continue;\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n }\n return pages.sort((a, b) => (a.path < b.path ? -1 : 1));\n };\n /** What the site serves itself, at the addresses the kit would write. */\n /** Whether the site serves this address itself (asking the dev server only when a route might). */\n const served = async (/** @type {string} */ local) => {\n const kind = siteServes(root, routes(), local);\n\n if (kind === "file" || kind === "route") return true;\n if (kind === null) return false;\n const got = await get(`${base}${local}`);\n\n return Boolean(got && got.status === 200 && !/html/.test(got.type));\n };\n const own = async () => {\n const [robots, index, sitemap, llms, full, agent] = await Promise.all(["robots.txt", "sitemap-index.xml", "sitemap.xml", "llms.txt", "llms-full.txt", "agent.md"].map((name) => served(`/${name}`)));\n\n return { robots: robots ? "robots.txt" : null, sitemap: index ? "sitemap-index.xml" : sitemap ? "sitemap.xml" : null, llmsTxt: Boolean(llms), llmsFullTxt: Boolean(full), agentPage: Boolean(agent) };\n };\n /** @param {PageFacts[]} pages @param {string} siteOrigin @param {Awaited<ReturnType<typeof own>>} owned */\n const plan = (pages, siteOrigin, owned) => {\n const { settings } = readSettings(root, file);\n const content = readSiteContent(root);\n\n return planSite({\n pages,\n settings,\n origin: siteOrigin,\n base,\n own: owned,\n drafts: content.drafts,\n dates: content.dates,\n patterns: content.patterns,\n fallbackName: content.name,\n fileExists: (path) => existsSync(join(root, "public", path.replace(/^\\/+/, ""))),\n });\n };\n const none = { robots: null, sitemap: null, llmsTxt: false, llmsFullTxt: false, agentPage: false };\n /**\n * The page, its ancestors and the home page: all a page\'s own output\n * needs. `html`: the page as it is being sent, so it isn\'t rendered twice.\n *\n * @param {string} path\n * @param {string} siteOrigin\n * @param {string} [html]\n */\n const around = async (path, siteOrigin, html) => {\n const segments = sitePath(path, base).split("/").filter(Boolean);\n const wanted = [`${base}/`, ...segments.slice(0, -1).map((_, index) => `${base}/${segments.slice(0, index + 1).join("/")}/`), path].filter((item) => html === undefined || item !== path);\n const found = await Promise.all([...new Set(wanted)].map((item) => facts(item, siteOrigin)));\n const pages = found.filter((item) => item !== null);\n\n return html === undefined ? pages : [...pages, factsOf(html, path, siteOrigin)];\n };\n\n return (req, res, next) => {\n if (req.headers[RAW_HEADER] || (req.method !== "GET" && req.method !== "HEAD")) return next();\n // The address as asked: under a base path Vite has already taken the base\n // off req.url by the time this runs; connect keeps the original.\n const [path = "/"] = (/** @type {{ originalUrl?: string }} */ (req).originalUrl ?? req.url ?? "/").split("?");\n\n if (path !== base && !path.startsWith(`${base}/`)) return next();\n const local = sitePath(path, base);\n const siteOrigin = origin || `http://${req.headers.host ?? "localhost"}`;\n /** @param {number} status @param {string} type @param {string} body */\n const send = (status, type, body) => {\n res.statusCode = status;\n res.setHeader("content-type", type);\n res.setHeader("cache-control", "no-store");\n res.end(req.method === "HEAD" ? "" : body);\n };\n\n if (isVisibilityAddress(local)) {\n void (async () => {\n // The site\'s own file or route at this address wins, as in a build.\n if (await served(local)) return next();\n const fileName = local.replace(/^\\//, "");\n\n if (local.endsWith(".md") && local !== "/agent.md") {\n for (const candidate of pagesForTwin(path, base)) {\n const pages = await around(candidate, siteOrigin);\n const page = pages.find((item) => item.path === candidate);\n\n if (!page) continue;\n const result = plan(pages, siteOrigin, none);\n const text = result.files[fileName];\n\n if (text !== undefined && twinPath(page.path, base) === path) return send(200, "text/markdown; charset=utf-8", text);\n }\n return next();\n }\n const owned = await own();\n const pages = local === "/robots.txt" ? [] : await crawl(siteOrigin);\n const result = plan(pages, siteOrigin, owned);\n const text = result.files[fileName];\n\n if (text === undefined) return next();\n return send(200, result.types[fileName] ?? "text/plain; charset=utf-8", text);\n })().catch(() => next());\n return;\n }\n const accept = String(req.headers.accept ?? "");\n\n if (/\\.[a-z0-9]+$/i.test(local) && !/\\.html?$/i.test(local)) return next();\n if (accept && !/text\\/html|\\*\\/\\*/.test(accept)) return next();\n interceptHtml(res, async (html) => {\n const pages = await around(path, siteOrigin, html);\n const addition = plan(pages, siteOrigin, none).head.get(path);\n\n if (!addition) return html;\n const kept = /type=["\']?text\\/markdown/i.test(html) ? addition.replace(/<link rel="alternate" type="text\\/markdown"[^>]*>/, "") : addition;\n\n return addToHead(html, kept);\n });\n next();\n };\n}\n\n/**\n * The integration\'s hooks for this part.\n *\n * @param {VisibilityOptions | false | undefined} options\n * @returns {Partial<import("astro").AstroIntegration["hooks"]>}\n */\nexport function visibilityHooks(options) {\n if (options === false) return {};\n const file = (options && options.file) || DEFAULT_FILE;\n let root = "";\n let origin = "";\n let base = "";\n let siteSitemap = false;\n /** @type {RouteInfo[]} */\n let routes = [];\n\n return {\n "astro:config:setup": ({ config, addWatchFile }) => {\n if (!config) return;\n const siteRoot = fileURLToPath(config.root).replace(/[\\\\/]+$/, "");\n\n // Read once here so a broken file stops the build with its message.\n readSettings(siteRoot, file);\n addWatchFile(join(siteRoot, file));\n },\n "astro:config:done": ({ config }) => {\n root = fileURLToPath(config.root).replace(/[\\\\/]+$/, "");\n ({ origin, base } = siteAddress(config));\n siteSitemap = (config.integrations ?? []).some((integration) => integration.name === "@astrojs/sitemap");\n },\n // In dev this runs again whenever a page file is added or removed.\n "astro:routes:resolved": ({ routes: resolved }) => {\n routes = resolved\n .filter((route) => route.origin !== "internal")\n .map((route) => ({ pattern: route.pattern, regex: route.patternRegex instanceof RegExp ? route.patternRegex : null, dynamic: route.params.length > 0 }));\n },\n "astro:server:setup": ({ server }) => {\n const self = () => {\n const address = server.httpServer?.address();\n\n if (!address || typeof address === "string") return "http://127.0.0.1:4321";\n const host = address.address === "::" || address.address === "0.0.0.0" ? "127.0.0.1" : address.family === "IPv6" || address.address.includes(":") ? `[${address.address}]` : address.address;\n\n return `http://${host}:${address.port}`;\n };\n\n server.middlewares.use(createDevMiddleware({ root, file, origin, base, self, routes: () => routes }));\n },\n "astro:build:done": ({ dir, logger }) => {\n const result = writeVisibility({ dir: fileURLToPath(dir), root, file, origin, base, siteSitemap });\n\n logger.info(result.summary);\n for (const note of result.notes) logger.info(` ${note}`);\n },\n };\n}\n', "visibility/markdown.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A rendered page \u2192 the markdown an AI agent reads: the page\'s main content\n// as visitors see it, however it was authored (content collections, section\n// blocks, hand-written Astro), with every address made absolute and nothing\n// that only works in a browser \u2014 no navigation, scripts, styles, forms,\n// cookie banner or tracking.\n//\n// What counts as the main content, in order:\n// 1. an element marked data-galley-agent="main";\n// 2. <main> (or role="main");\n// 3. the only <article>;\n// 4. <body> without its header, footer, nav and aside.\n// Inside it, anything marked data-galley-agent="skip", hidden, aria-hidden or\n// inert is left out; elements outside it marked data-galley-agent="include"\n// are added at the end, in page order.\n//\n// The same tree always gives the same bytes.\n\nimport { find, findAll, textOf } from "./html.js";\n\n/** @typedef {import("./html.js").Element} Element */\n/** @typedef {import("./html.js").Node} Node */\n\n/** Elements whose content is never part of the twin. */\nconst DROP = new Set([\n "script", "style", "noscript", "template", "svg", "math", "canvas", "object", "embed", "form", "button", "input", "select",\n "textarea", "option", "datalist", "nav", "dialog", "link", "meta", "head", "title", "map", "area", "slot", "progress", "meter",\n]);\nconst BLOCK = new Set([\n "address", "article", "aside", "blockquote", "body", "dd", "details", "div", "dl", "dt", "fieldset", "figcaption", "figure",\n "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", "main", "ol", "p", "pre", "section", "summary",\n "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", "menu", "iframe", "video", "audio", "caption", "search", "center",\n]);\nconst BREAK = "\\u0000";\n\n/**\n * @typedef {object} Context\n * @property {string} base The page\'s absolute address, for resolving links.\n * @property {string} page The page\'s own address without its fragment.\n */\n\n/** @param {Element} el */\nexport function isSkipped(el) {\n if (DROP.has(el.name)) return true;\n const attrs = el.attrs;\n\n if ("hidden" in attrs || "inert" in attrs || attrs["aria-hidden"] === "true") return true;\n if (attrs["data-galley-agent"] === "skip") return true;\n if (attrs.role === "navigation" || attrs.role === "search" || attrs.role === "dialog" || attrs.role === "alertdialog") return true;\n // The kit\'s own pieces that only mean something in a browser.\n if ("data-galley-consent" in attrs || "data-galley-form" in attrs || "data-galley-mailto" in attrs) return true;\n return false;\n}\n\n/**\n * The element whose content is the page\'s main content, and the extra\n * elements marked to be included.\n *\n * @param {Element} doc\n * @returns {{ root: Element | null; extra: Element[]; whole: boolean }}\n */\nexport function mainContent(doc) {\n const body = find(doc, (el) => el.name === "body") ?? doc;\n const marked = find(body, (el) => el.attrs["data-galley-agent"] === "main");\n /** @type {Element | null} */\n let root = marked ?? find(body, (el) => el.name === "main") ?? find(body, (el) => el.attrs.role === "main");\n let whole = false;\n\n if (!root) {\n const all = findAll(body, (el) => el.name === "article");\n const top = all.filter((el) => !all.some((other) => other !== el && contains(other, el)));\n\n if (top.length === 1) root = top[0] ?? null;\n }\n if (!root) {\n // No main region: the body, without the site\'s header, footer and sidebars.\n root = { ...body, children: body.children.filter((child) => !(child.type === "element" && (child.name === "header" || child.name === "footer" || child.name === "aside"))) };\n whole = true;\n }\n const chosen = root;\n const extra = whole ? [] : findAll(body, (el) => el.attrs["data-galley-agent"] === "include" && !contains(chosen, el), (el) => el === chosen);\n\n return { root, extra, whole };\n}\n\n/** @param {Element} outer @param {Element} inner */\nfunction contains(outer, inner) {\n for (let at = inner.parent; at; at = at.parent) if (at === outer) return true;\n return false;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 escaping\n\n/** Text as markdown text: the characters markdown would read as syntax are escaped. */\nexport function escapeText(/** @type {string} */ text) {\n return text\n .replace(/\\\\/g, "\\\\\\\\")\n .replace(/[`*[\\]]/g, (char) => `\\\\${char}`)\n .replace(/(^|[^\\p{L}\\p{N}])_|_(?=[^\\p{L}\\p{N}]|$)/gu, (match) => match.replace("_", "\\\\_"))\n .replace(/<(?=[a-zA-Z/!?])/g, "\\\\<")\n .replace(/&(?=#?[a-zA-Z0-9]+;)/g, "\\\\&");\n}\n\n/** A paragraph\'s first characters that would start a heading, quote or list. */\nfunction escapeStart(/** @type {string} */ line) {\n return line\n .replace(/^(#{1,6})(?=\\s|$)/, "\\\\$1")\n .replace(/^>/, "\\\\>")\n .replace(/^([-+])(?=\\s)/, "\\\\$1")\n .replace(/^(\\d+)([.)])(?=\\s)/, "$1\\\\$2")\n .replace(/^([-=])\\1*$/, (match) => `\\\\${match}`);\n}\n\n/** A link or image address that markdown reads in one piece. */\nfunction destination(/** @type {string} */ url) {\n return url.replace(/ /g, "%20").replace(/\\(/g, "%28").replace(/\\)/g, "%29").replace(/</g, "%3C").replace(/>/g, "%3E");\n}\n\n/** @param {string} href @param {Context} ctx @returns {string | null} */\nfunction absolute(href, ctx) {\n const value = href.trim();\n\n if (!value || /^(javascript|data|vbscript):/i.test(value)) return null;\n try {\n const url = new URL(value, ctx.base);\n\n if (!/^(https?|mailto|tel|ftp):$/.test(url.protocol)) return null;\n return url.href;\n } catch {\n return null;\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 inline\n\n/** @param {Element} el @returns {boolean} */\nfunction hasBlock(el) {\n return el.children.some((child) => child.type === "element" && !isSkipped(child) && (BLOCK.has(child.name) || hasBlock(child)));\n}\n\n/**\n * The inline markdown of a node\'s children (one line; hard breaks marked).\n *\n * @param {Node} node\n * @param {Context} ctx\n * @returns {string}\n */\nfunction inline(node, ctx) {\n if (node.type === "text") return escapeText(node.value);\n if (isSkipped(node)) return "";\n const inner = () => joinInline(node.children, ctx);\n\n switch (node.name) {\n case "br":\n return BREAK;\n case "wbr":\n return "";\n case "strong":\n case "b": {\n const text = inner();\n\n return text.trim() ? wrap(text, "**") : text;\n }\n case "em":\n case "i":\n case "cite": {\n const text = inner();\n\n return text.trim() ? wrap(text, "*") : text;\n }\n case "del":\n case "s": {\n const text = inner();\n\n return text.trim() ? wrap(text, "~~") : text;\n }\n case "code":\n case "kbd":\n case "samp":\n return codeSpan(textOf(node));\n case "img":\n return image(node, ctx);\n case "a":\n return link(node, inner(), ctx);\n case "picture": {\n const img = find(node, (el) => el.name === "img");\n\n return img ? image(img, ctx) : "";\n }\n default:\n return inner();\n }\n}\n\n/**\n * Inline children joined. Two elements side by side with no text between\n * them (a row of links, "By <a>\u2026</a><time>\u2026</time>") are usually set apart\n * by the page\'s layout, not by a space in the HTML: they get a space here so\n * their words don\'t run together.\n *\n * @param {Node[]} children\n * @param {Context} ctx\n */\nfunction joinInline(children, ctx) {\n let out = "";\n let lastElement = false;\n let gap = false;\n\n for (const child of children) {\n // A left-out element between two words (an aria-hidden "\xB7") stood for a gap.\n if (child.type === "element" && isSkipped(child)) {\n gap = true;\n continue;\n }\n const part = inline(child, ctx);\n\n if (!part) continue;\n const element = child.type === "element";\n // Text only screen readers hear ("Published") stands apart from its neighbours.\n const hiddenLabel = element && /(^|\\s)(visually-hidden|sr-only|screen-reader-text|galley-visually-hidden)(\\s|$)/.test(child.attrs.class ?? "");\n\n if (hiddenLabel) gap = true;\n if ((gap || (element && lastElement)) && out && !/[\\s\\u0000]$/.test(out) && !/^[\\s\\u0000.,;:!?)\\]]/.test(part) && !/[([]$/.test(out)) out += " ";\n out += part;\n lastElement = element;\n gap = hiddenLabel;\n }\n return out;\n}\n\n/** `**text**` with the spaces kept outside the markers, as markdown needs. */\nfunction wrap(/** @type {string} */ text, /** @type {string} */ marker) {\n const lead = /^\\s*/.exec(text)?.[0] ?? "";\n const trail = /\\s*$/.exec(text)?.[0] ?? "";\n\n return `${lead}${marker}${text.trim()}${marker}${trail}`;\n}\n\nfunction codeSpan(/** @type {string} */ text) {\n if (!text) return "";\n const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length));\n const fence = "`".repeat(longest + 1);\n const pad = longest > 0 || text.startsWith("`") || text.endsWith("`") ? " " : "";\n\n return `${fence}${pad}${text}${pad}${fence}`;\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction image(el, ctx) {\n const alt = (el.attrs.alt ?? "").replace(/\\s+/g, " ").trim();\n const src = absolute(el.attrs.src ?? "", ctx);\n\n // An empty alt marks a decorative image: there is nothing to say about it.\n if (!alt || !src) return "";\n return `})`;\n}\n\n/** @param {Element} el @param {string} text @param {Context} ctx */\nfunction link(el, text, ctx) {\n const href = el.attrs.href ?? "";\n const label = text.replace(new RegExp(BREAK, "g"), " ").trim() || escapeText((el.attrs["aria-label"] ?? el.attrs.title ?? "").trim());\n const url = absolute(href, ctx);\n\n if (!label) return "";\n // A link to a part of this same page means nothing outside it.\n if (!url || href.trim().startsWith("#") || url.split("#")[0] === ctx.page) return text;\n return `[${label}](${destination(url)})`;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 blocks\n\n/**\n * @param {Element} el\n * @param {Context} ctx\n * @returns {string[]}\n */\nfunction blocks(el, ctx) {\n /** @type {string[]} */\n const out = [];\n let run = "";\n /** @type {Node[]} */\n let pending = [];\n const flush = () => {\n run += joinInline(pending, ctx);\n pending = [];\n const text = finishInline(run);\n\n if (text) out.push(escapeStart(text));\n run = "";\n };\n\n for (const child of el.children) {\n if (child.type === "text" || isSkipped(child)) {\n pending.push(child);\n continue;\n }\n if (child.name === "a" && hasBlock(child)) {\n flush();\n out.push(...linkedBlocks(child, ctx));\n continue;\n }\n if (!BLOCK.has(child.name) && !hasBlock(child)) {\n pending.push(child);\n continue;\n }\n flush();\n out.push(...block(child, ctx));\n }\n flush();\n return out;\n}\n\n/** Inline text as one paragraph: whitespace collapsed, hard breaks kept inside it. */\nfunction finishInline(/** @type {string} */ run) {\n return run\n .replace(/[ \\t\\r\\n\\f\xA0]+/g, (space) => (space.includes("\xA0") && !/[\\r\\n]/.test(space) ? "\xA0" : " "))\n .replace(/ ?\\u0000 ?/g, BREAK)\n .replace(/^[\\s\\u0000]+|[\\s\\u0000]+$/g, "")\n .replace(/\\u0000+/g, "\\\\\\n");\n}\n\n/**\n * A card-like link around headings and paragraphs: its blocks, with the\n * first heading (or else the first paragraph) carrying the link.\n *\n * @param {Element} el\n * @param {Context} ctx\n */\nfunction linkedBlocks(el, ctx) {\n const inner = blocks(el, ctx);\n const url = absolute(el.attrs.href ?? "", ctx);\n\n if (!url || (el.attrs.href ?? "").startsWith("#")) return inner;\n const index = Math.max(0, inner.findIndex((text) => /^#{1,6} /.test(text)));\n const first = inner[index];\n\n if (first === undefined) return inner;\n const heading = /^(#{1,6} )(.*)$/s.exec(first);\n\n // Links can\'t hold links: a block that has its own stays as it is.\n if (first.includes("](")) return inner;\n if (heading) inner[index] = `${heading[1]}[${heading[2]}](${destination(url)})`;\n else if (!/^(!\\[|\\||```|>|-|\\d+\\.)/.test(first)) inner[index] = `[${first}](${destination(url)})`;\n return inner;\n}\n\n/**\n * @param {Element} el\n * @param {Context} ctx\n * @returns {string[]}\n */\nfunction block(el, ctx) {\n const name = el.name;\n\n if (/^h[1-6]$/.test(name)) {\n const text = finishInline(joinInline(el.children, ctx)).replace(/\\\\\\n/g, " ");\n\n return text ? [`${"#".repeat(Number(name[1]))} ${text}`] : [];\n }\n switch (name) {\n case "p":\n case "summary":\n case "dt":\n case "caption":\n case "figcaption": {\n if (hasBlock(el)) return blocks(el, ctx);\n const text = finishInline(joinInline(el.children, ctx));\n\n if (!text) return [];\n return [escapeStart(name === "summary" || name === "dt" ? (/^\\*\\*.*\\*\\*$/.test(text) ? text : `**${text}**`) : text)];\n }\n case "hr":\n return ["---"];\n case "ul":\n case "ol":\n case "menu":\n return list(el, ctx);\n case "blockquote": {\n const inner = blocks(el, ctx).join("\\n\\n");\n\n return inner ? [inner.split("\\n").map((line) => (line ? `> ${line}` : ">")).join("\\n")] : [];\n }\n case "pre":\n return codeBlock(el);\n case "table":\n return table(el, ctx);\n case "iframe":\n case "video":\n case "audio":\n return media(el, ctx);\n default:\n return blocks(el, ctx);\n }\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction list(el, ctx) {\n const ordered = el.name === "ol";\n const start = Number.parseInt(el.attrs.start ?? "1", 10);\n /** @type {string[]} */\n const items = [];\n let number = Number.isFinite(start) ? start : 1;\n\n for (const child of el.children) {\n if (child.type !== "element" || isSkipped(child)) continue;\n const content = child.name === "li" ? blocks(child, ctx) : block(child, ctx);\n\n if (content.length === 0) continue;\n const marker = ordered ? `${number}.` : "-";\n const indent = " ".repeat(marker.length + 1);\n const lines = content\n .map((part, index) => {\n const indented = part.split("\\n").map((line, at) => (index === 0 && at === 0 ? line : line ? `${indent}${line}` : ""));\n\n return indented.join("\\n");\n })\n .reduce((all, part, index) => {\n if (index === 0) return part;\n // A nested list follows its item directly; other blocks get a blank line.\n const tight = /^\\s*(-|\\d+\\.) /.test(part);\n\n return `${all}${tight ? "\\n" : "\\n\\n"}${part}`;\n }, "");\n\n items.push(`${marker} ${lines}`);\n number += 1;\n }\n return items.length ? [items.join("\\n")] : [];\n}\n\n/** @param {Element} el */\nfunction codeBlock(el) {\n const code = find(el, (child) => child.name === "code");\n const className = `${code?.attrs.class ?? ""} ${el.attrs.class ?? ""}`;\n const language = el.attrs["data-language"] ?? /(?:^|\\s)(?:language|lang)-([\\w+#.-]+)/.exec(className)?.[1] ?? "";\n /** @param {import("./html.js").Node} node @returns {string} */\n const raw = (node) => (node.type === "text" ? node.value : node.name === "br" ? "\\n" : node.children.map(raw).join(""));\n const text = raw(code ?? el).replace(/^\\n/, "").replace(/\\s+$/, "");\n\n if (!text) return [];\n const longest = Math.max(2, ...[...text.matchAll(/^`{3,}/gm)].map((match) => match[0].length));\n const fence = "`".repeat(longest + 1);\n\n return [`${fence}${language === "plaintext" || language === "text" ? "" : language}\\n${text}\\n${fence}`];\n}\n\n/** @param {Element} el @param {Context} ctx */\nfunction table(el, ctx) {\n const rows = findAll(el, (child) => child.name === "tr", (child) => child.name === "table");\n const cells = rows\n .map((row) =>\n row.children\n .filter((cell) => cell.type === "element" && (cell.name === "td" || cell.name === "th"))\n .map((cell) =>\n finishInline(/** @type {Element} */ (cell).children.map((child) => (child.type === "element" && BLOCK.has(child.name) ? ` ${block(/** @type {Element} */ (child), ctx).join(" ")} ` : inline(child, ctx))).join(""))\n .replace(/\\\\\\n/g, " ")\n .replace(/\\n+/g, " ")\n .replace(/\\|/g, "\\\\|"),\n ),\n )\n .filter((row) => row.length > 0);\n const width = Math.max(0, ...cells.map((row) => row.length));\n\n if (cells.length === 0 || width === 0) return [];\n const pad = (/** @type {string[]} */ row) => [...row, ...Array(width - row.length).fill("")];\n const line = (/** @type {string[]} */ row) => `| ${pad(row).join(" | ")} |`.replace(/ {2,}\\|/g, " |");\n const caption = find(el, (child) => child.name === "caption");\n const out = [line(cells[0] ?? []), `| ${Array(width).fill("---").join(" | ")} |`, ...cells.slice(1).map(line)].join("\\n");\n\n return caption ? [...block(caption, ctx), out] : [out];\n}\n\n/** An embedded video, recording or frame: a link to it, named by its title. */\nfunction media(/** @type {Element} */ el, /** @type {Context} */ ctx) {\n const source = el.attrs.src ?? find(el, (child) => child.name === "source")?.attrs.src ?? "";\n const url = absolute(source, ctx);\n const label = (el.attrs.title ?? el.attrs["aria-label"] ?? "").trim();\n\n if (!url || !label) return [];\n return [`[${escapeText(label)}](${destination(url)})`];\n}\n\n/**\n * The markdown of the main content of a parsed page.\n *\n * @param {Element} doc\n * @param {{ url: string }} page The page\'s absolute address.\n * @returns {{ markdown: string; hasH1: boolean; whole: boolean }}\n */\nexport function pageMarkdown(doc, page) {\n const { root, extra, whole } = mainContent(doc);\n const ctx = { base: page.url, page: page.url.split("#")[0] ?? page.url };\n const parts = [...(root ? blocks(root, ctx) : []), ...extra.flatMap((el) => (isSkipped(el) ? [] : BLOCK.has(el.name) ? block(el, ctx) : blocks({ ...el, children: [el] }, ctx)))];\n const markdown = parts.filter((part) => part.trim()).join("\\n\\n");\n\n return { markdown, hasH1: /^# /m.test(markdown), whole };\n}\n', "visibility/page.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163092
163420
|
// @ts-check
|
|
163093
163421
|
// What a rendered page says about itself, read from its HTML: the facts the
|
|
163094
163422
|
// twin, llms.txt, the sitemap and the structured data are built from. Only
|
|
@@ -163234,7 +163562,7 @@ export function addToHead(html, addition) {
|
|
|
163234
163562
|
if (body) return html.slice(0, body.index) + addition + html.slice(body.index);
|
|
163235
163563
|
return html + addition;
|
|
163236
163564
|
}
|
|
163237
|
-
`, "visibility/site.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The whole agent-readable output of a site, from its rendered pages: which\n// pages count, each page\'s markdown twin and the tags its <head> gains, and\n// the site-wide files \u2014 llms.txt, llms-full.txt, agent.md, robots.txt and\n// sitemap.xml. Pure: the same pages and settings always give the same bytes,\n// whether they come from a build\'s output folder or a running dev server.\n//\n// Addresses (every one under the site\'s base path):\n// a page /about/ its twin /about.md\n// the home page / its twin /index.md\n// a file-style page /about.html its twin /about.md\n// \u2014 the llms.txt proposal\'s "the page\'s address with .md" for pages without\n// a trailing slash, and its "index.md" form for the home page. A twin is a\n// plain file next to the page\'s folder, so it works on any static host,\n// under any sub-path, with no rewrite rules.\n\nimport { matchGlob } from "../shared/glob.js";\nimport { AI_CRAWLERS, aiCrawler, PURPOSE_NOTES } from "./crawlers.js";\nimport { patternGlob } from "./content.js";\nimport { articleLd, breadcrumbLd, jsonLdTag, organizationLd, websiteLd } from "./structured.js";\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {import("./config.js").VisibilitySettings} VisibilitySettings */\n\n/** llms.txt lists at most this many pages; the rest are in the sitemap. */\nexport const MAX_LLMS_LINKS = 2000;\n/** The sitemaps protocol\'s limit per file. */\nexport const MAX_SITEMAP_URLS = 50_000;\n\n/**\n * @typedef {object} SiteInput\n * @property {PageFacts[]} pages Every rendered page.\n * @property {VisibilitySettings} settings\n * @property {string} origin "https://www.example.com", or "" when the site has no `site` address.\n * @property {string} base The base path without a trailing slash ("" or "/demo").\n * @property {{ robots: string | null; sitemap: string | null; llmsTxt: boolean; llmsFullTxt: boolean; agentPage: boolean }} own\n * What the site already publishes itself (the kit then leaves it alone). `robots` / `sitemap`: the file\'s name, or null.\n * @property {string[]} [drafts] Addresses (without the base) of draft entries.\n * @property {Record<string, string>} [dates] Address (without the base) \u2192 its content entry\'s date, for pages whose HTML states none.\n * @property {Record<string, string>} [patterns] Collection id \u2192 address pattern ("/blog/{slug}/").\n * @property {string} [fallbackName] The site\'s name when no page states one (galley.config.json).\n * @property {(path: string) => boolean} [fileExists] Whether the site serves a file (for the logo).\n */\n\n/**\n * @typedef {object} SitePlan\n * @property {Map<string, string>} head page path \u2192 HTML to add before </head>.\n * @property {Record<string, string>} files File path under the output folder \u2192 text.\n * @property {Record<string, string>} types File path \u2192 content type, for a server.\n * @property {string[]} notes What the build log says.\n * @property {{ pages: number; listed: number; twins: number; structured: number; sitemap: number; llmsLinks: number; fullBytes: number; fullTruncated: boolean }} counts\n */\n\n/**\n * "/demo/about/" \u2192 "/demo/about.md"; the home page "/demo/" \u2192 "/demo/index.md".\n *\n * @param {string} path The page\'s address, with the base.\n * @param {string} [base] The base path ("" or "/demo"), to know the home page.\n */\nexport function twinPath(path, base = "") {\n const clean = path.split(/[?#]/)[0] ?? "/";\n\n if (clean === "/" || clean === `${base}/`) return `${clean}index.md`;\n if (clean.endsWith("/")) return `${clean.slice(0, -1)}.md`;\n if (/\\/index\\.html?$/.test(clean)) return clean.replace(/\\/index\\.html?$/, "/index.md");\n return `${clean.replace(/\\.html?$/, "")}.md`;\n}\n\n/** The page addresses a twin address can belong to, most likely first. */\nexport function pagesForTwin(/** @type {string} */ path, /** @type {string} */ base) {\n if (!path.endsWith(".md")) return [];\n const bare = path.slice(0, -3);\n\n if (bare === `${base}/index`) return [`${base}/`];\n if (bare.endsWith("/index")) return [`${bare.slice(0, -"index".length)}`, `${bare}/`];\n return [`${bare}/`, bare, `${bare}.html`];\n}\n\n/** "/about" and "/about/" as one key. */\nexport function pathKey(/** @type {string} */ path) {\n const bare = (path.split(/[?#]/)[0] ?? "").replace(/\\/index\\.html?$/, "/").replace(/\\.html?$/, "");\n\n return bare === "/" || bare === "" ? "/" : bare.replace(/\\/+$/, "");\n}\n\n/** The page\'s address on the site without the base: "/demo/about/" \u2192 "/about/". */\nexport function sitePath(/** @type {string} */ path, /** @type {string} */ base) {\n if (!base) return path;\n if (path === base) return "/";\n return path.startsWith(`${base}/`) ? path.slice(base.length) : path;\n}\n\nconst SPECIAL = /^\\/(404|500)(\\/|\\.html)?$/;\n\n/** @param {string} value */\nconst yaml = (value) => JSON.stringify(value);\n/** @param {string} value */\nconst xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/\'/g, "'");\n/** One line of text for a list: no line breaks. */\nconst oneLine = (/** @type {string} */ value) => value.replace(/\\s+/g, " ").trim();\n/** Link text for llms.txt: brackets would end the link early. */\nconst linkText = (/** @type {string} */ value) => oneLine(value).replace(/([[\\]\\\\])/g, "\\\\$1");\n\n/** @param {string} value */\nfunction dateOnly(value) {\n const time = Date.parse(value);\n\n return Number.isFinite(time) ? new Date(time).toISOString().slice(0, 10) : "";\n}\n\n/** "release-notes" \u2192 "Release notes". */\nfunction humanize(/** @type {string} */ segment) {\n const words = decodeURIComponent(segment).replace(/[-_]+/g, " ").trim();\n\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : segment;\n}\n\n/**\n * Whether a robots rule path (with `*` and `$`) matches an address.\n *\n * @param {string} rule\n * @param {string} path\n */\nfunction robotsMatch(rule, path) {\n const anchored = rule.endsWith("$");\n const body = anchored ? rule.slice(0, -1) : rule;\n const source = body\n .split("*")\n .map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, "\\\\$&"))\n .join(".*");\n\n return new RegExp(`^${source}${anchored ? "$" : ""}`).test(path);\n}\n\n/**\n * Whether the site-wide rules let crawlers fetch an address: the longest\n * matching rule wins, and Allow wins a tie (RFC 9309, section 2.2.2).\n *\n * @param {{ disallow: string[]; allow: string[] }} rules\n * @param {string} path\n */\nexport function robotsAllows(rules, path) {\n let best = { allow: true, length: -1 };\n\n for (const [allow, list] of /** @type {[boolean, string[]][]} */ ([[false, rules.disallow], [true, rules.allow]])) {\n for (const rule of list) {\n if (!robotsMatch(rule, path)) continue;\n if (rule.length > best.length || (rule.length === best.length && allow)) best = { allow, length: rule.length };\n }\n }\n return best.allow;\n}\n\n/**\n * @param {SiteInput} input\n * @returns {SitePlan}\n */\nexport function planSite(input) {\n const { settings, origin, base, own } = input;\n const agent = settings.agentReadable;\n const notes = /** @type {string[]} */ ([]);\n const abs = (/** @type {string} */ path) => (origin ? `${origin}${path}` : path);\n const home = input.pages.find((page) => pathKey(sitePath(page.path, base)) === "/");\n const drafts = new Set((input.drafts ?? []).map(pathKey));\n const siteName = settings.site.name || home?.siteName || input.fallbackName || home?.name || (origin ? new URL(origin).hostname : "This site");\n const summary = oneLine(settings.site.summary || home?.description || "");\n const rootUrl = abs(`${base}/`);\n // A page the kit\'s own robots.txt asks every crawler to stay away from isn\'t listed for them either.\n const disallowed = (/** @type {string} */ path) => settings.robots.enabled && !own.robots && !robotsAllows(settings.robots, sitePath(path, base));\n\n // \u2500\u2500 Which pages count \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {PageFacts} page */\n const listed = (page) => {\n const local = sitePath(page.path, base);\n\n if (page.noindex || page.redirect || SPECIAL.test(local) || drafts.has(pathKey(local)) || disallowed(page.path)) return false;\n // A page whose canonical address is another page is a copy of that page.\n if (page.canonical) {\n try {\n if (pathKey(new URL(page.canonical).pathname) !== pathKey(page.path)) return false;\n } catch {\n return false;\n }\n }\n return true;\n };\n // A page that states no date of its own takes its content entry\'s, when it has one.\n const dated = new Map(Object.entries(input.dates ?? {}).map(([path, date]) => [pathKey(path), date]));\n const pages = [...input.pages]\n .map((page) => {\n const date = page.published ? "" : dated.get(pathKey(sitePath(page.path, base)));\n\n return date ? { ...page, published: date } : page;\n })\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n const counted = pages.filter(listed);\n const byKey = new Map(counted.map((page) => [pathKey(page.path), page]));\n const twinned = agent.markdownTwins ? counted.filter((page) => page.markdown && !agent.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob))) : [];\n /** @type {Record<string, string>} */\n const files = {};\n /** @type {Record<string, string>} */\n const types = {};\n const twinOf = new Map(/** @type {[string, string][]} */ ([]));\n const fileFor = (/** @type {string} */ path) => sitePath(path, base).replace(/^\\/+/, "");\n\n // \u2500\u2500 Twins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const page of twinned) {\n const path = twinPath(page.path, base);\n const file = fileFor(path);\n\n if (files[file] !== undefined) {\n notes.push(`${path} would be the markdown version of two pages; only ${twinOf.get(file) ?? "the first"} got it.`);\n continue;\n }\n files[file] = twinText(page, page.canonical ?? page.url);\n types[file] = "text/markdown; charset=utf-8";\n twinOf.set(file, page.path);\n }\n const hasTwin = (/** @type {PageFacts} */ page) => twinOf.get(fileFor(twinPath(page.path, base))) === page.path;\n\n // \u2500\u2500 Structured data and the <head> link \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sd = settings.structuredData;\n const subPath = Boolean(base);\n const scopes = articleScopes(sd.articles, input.patterns ?? {});\n /** @type {Map<string, string>} */\n const head = new Map();\n let structured = 0;\n const logo = sd.organization && sd.organization.logo ? resolveLogo(sd.organization.logo, base, origin, input.fileExists, notes) : "";\n\n if (!origin && (sd.website || sd.organization || sd.articles || sd.breadcrumbs)) notes.push("Structured data needs full addresses: set `site` in astro.config (e.g. site: \\"https://www.example.com\\") to add it.");\n for (const page of counted) {\n const local = sitePath(page.path, base);\n const tags = [];\n const has = (/** @type {RegExp} */ type) => page.jsonldTypes.some((name) => type.test(name));\n\n if (hasTwin(page)) tags.push(`<link rel="alternate" type="text/markdown" href="${xml(twinPath(page.path, base))}">`);\n if (origin) {\n if (pathKey(local) === "/") {\n const website = sd.website && !has(/^WebSite$/) ? websiteLd({ name: siteName, url: rootUrl, subPath }) : null;\n const org = sd.organization && !has(/Organization$|^Corporation$|LocalBusiness|^Store$|^Restaurant$/)\n ? organizationLd({ name: sd.organization.name || siteName, url: rootUrl, logo, sameAs: sd.organization.sameAs, email: sd.organization.email, telephone: sd.organization.telephone })\n : null;\n\n if (website) tags.push(jsonLdTag(website));\n if (org) tags.push(jsonLdTag(org));\n }\n const scope = scopes(local, page);\n\n if (scope && !has(/^(Article|BlogPosting|NewsArticle|TechArticle|Report|ScholarlyArticle)$/)) {\n const article = articleLd(page, { type: scope, siteImage: home && home !== page ? home.image : "" });\n\n if (article) tags.push(jsonLdTag(article));\n }\n const segments = local.split("/").filter(Boolean);\n\n if (sd.breadcrumbs && segments.length >= 2 && !has(/^BreadcrumbList$/)) {\n // From the home page (named for the site) down to the page itself, through every level that is a page.\n const homePage = byKey.get(pathKey(`${base}/`));\n /** @type {{ name: string; url: string }[]} */\n const trail = homePage ? [{ name: oneLine(siteName), url: homePage.canonical ?? homePage.url }] : [];\n\n for (let depth = 1; depth < segments.length; depth += 1) {\n const parent = byKey.get(pathKey(`${base}/${segments.slice(0, depth).join("/")}/`));\n\n if (parent) trail.push({ name: oneLine(parent.name), url: parent.canonical ?? parent.url });\n }\n trail.push({ name: oneLine(page.name), url: page.canonical ?? page.url });\n const crumbs = breadcrumbLd(trail);\n\n if (crumbs) tags.push(jsonLdTag(crumbs));\n }\n }\n if (tags.length) {\n head.set(page.path, tags.join(""));\n if (tags.length > (hasTwin(page) ? 1 : 0)) structured += 1;\n }\n }\n\n // \u2500\u2500 llms.txt and llms-full.txt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const entries = (agent.markdownTwins ? twinned.filter(hasTwin) : counted).filter((page) => !agent.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob)));\n const linkFor = (/** @type {PageFacts} */ page) => (hasTwin(page) ? abs(twinPath(page.path, base)) : page.canonical ?? page.url);\n const sections = groupPages(entries, base, byKey, (page) => agent.optional.some((glob) => matchGlob(sitePath(page.path, base), glob)));\n let llmsLinks = 0;\n let fullBytes = 0;\n let fullTruncated = false;\n const writeLlms = agent.llmsTxt && !own.llmsTxt;\n const writeFull = agent.llmsFullTxt && !own.llmsFullTxt;\n const writeAgent = agent.agentPage && !own.agentPage && !files["agent.md"];\n\n if (own.llmsTxt && agent.llmsTxt) notes.push("llms.txt: the site publishes its own; left as it is.");\n if (writeLlms) {\n const lines = [`# ${oneLine(siteName)}`, ""];\n\n if (summary) lines.push(`> ${summary}`, "");\n const intro = [\n agent.markdownTwins ? `Each page below is linked to its markdown version: the page\'s own text, with no scripts or layout.` : "",\n writeFull ? `Everything in one file: ${abs(`${base}/llms-full.txt`)}.` : "",\n writeAgent ? `How to use and cite this site: ${abs(`${base}/agent.md`)}.` : "",\n ].filter(Boolean);\n\n if (intro.length) lines.push(intro.join(" "), "");\n let remaining = MAX_LLMS_LINKS;\n let left = 0;\n\n for (const section of sections) {\n const shown = section.pages.slice(0, Math.max(0, remaining));\n\n left += section.pages.length - shown.length;\n remaining -= shown.length;\n if (!shown.length) continue;\n lines.push(`## ${section.title}`, "");\n for (const page of shown) lines.push(`- [${linkText(page.name || page.path)}](${linkFor(page)})${page.description ? `: ${oneLine(page.description)}` : ""}`);\n lines.push("");\n llmsLinks += shown.length;\n }\n if (left > 0) lines.push(`${left} more pages are listed in the sitemap: ${abs(`${base}/sitemap.xml`)}.`, "");\n files["llms.txt"] = `${lines.join("\\n").replace(/\\n+$/, "")}\\n`;\n types["llms.txt"] = "text/plain; charset=utf-8";\n }\n if (own.llmsFullTxt && agent.llmsFullTxt) notes.push("llms-full.txt: the site publishes its own; left as it is.");\n if (writeFull) {\n const encoder = new TextEncoder();\n const headText = `# ${oneLine(siteName)}\\n\\n${summary ? `> ${summary}\\n\\n` : ""}Every page of ${rootUrl}${agent.markdownTwins ? " as markdown" : ""}, one after another. The list of pages is ${abs(`${base}/llms.txt`)}.\\n`;\n const parts = [headText];\n let size = encoder.encode(headText).length;\n const ordered = sections.flatMap((section) => section.pages);\n let index = 0;\n\n for (; index < ordered.length; index += 1) {\n const page = /** @type {PageFacts} */ (ordered[index]);\n const body = `\\n---\\n\\nSource: ${page.canonical ?? page.url}\\n\\n${pageBody(page)}\\n`;\n const bytes = encoder.encode(body).length;\n\n if (size + bytes > agent.fullMaxBytes - 400) break;\n parts.push(body);\n size += bytes;\n }\n if (index < ordered.length) {\n fullTruncated = true;\n const left = ordered.length - index;\n\n parts.push(`\\n---\\n\\nThis file stops here: it reached its size limit of ${agent.fullMaxBytes.toLocaleString("en-US")} bytes. ${left} more ${left === 1 ? "page is" : "pages are"} listed in ${abs(`${base}/llms.txt`)}, each with its own markdown version.\\n`);\n }\n files["llms-full.txt"] = parts.join("");\n types["llms-full.txt"] = "text/plain; charset=utf-8";\n fullBytes = encoder.encode(files["llms-full.txt"]).length;\n }\n\n // \u2500\u2500 sitemap.xml \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sitemapPages = settings.sitemap.enabled ? counted.filter((page) => !settings.sitemap.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob))) : [];\n const writeSitemap = settings.sitemap.enabled && !own.sitemap && Boolean(origin);\n\n if (settings.sitemap.enabled && own.sitemap) notes.push(`${own.sitemap}: the site writes its own sitemap; left as it is.`);\n if (settings.sitemap.enabled && !own.sitemap && !origin) notes.push("sitemap.xml needs full addresses: set `site` in astro.config to have one written.");\n if (writeSitemap) {\n const url = (/** @type {PageFacts} */ page) => {\n const lastmod = settings.sitemap.lastmod === "content" ? dateOnly(page.modified || page.published) : "";\n\n return ` <url><loc>${xml(page.canonical ?? page.url)}</loc>${lastmod ? `<lastmod>${lastmod}</lastmod>` : ""}</url>`;\n };\n const urlset = (/** @type {PageFacts[]} */ list) => [\'<?xml version="1.0" encoding="UTF-8"?>\', \'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\', ...list.map(url), "</urlset>", ""].join("\\n");\n\n if (sitemapPages.length <= MAX_SITEMAP_URLS) files["sitemap.xml"] = urlset(sitemapPages);\n else {\n const names = [];\n\n for (let start = 0, part = 1; start < sitemapPages.length; start += MAX_SITEMAP_URLS, part += 1) {\n const name = `sitemap-${part}.xml`;\n\n files[name] = urlset(sitemapPages.slice(start, start + MAX_SITEMAP_URLS));\n types[name] = "application/xml; charset=utf-8";\n names.push(name);\n }\n files["sitemap.xml"] = [\'<?xml version="1.0" encoding="UTF-8"?>\', \'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\', ...names.map((name) => ` <sitemap><loc>${xml(abs(`${base}/${name}`))}</loc></sitemap>`), "</sitemapindex>", ""].join("\\n");\n }\n types["sitemap.xml"] = "application/xml; charset=utf-8";\n }\n const sitemapUrl = own.sitemap ? abs(`${base}/${own.sitemap}`) : writeSitemap ? abs(`${base}/sitemap.xml`) : "";\n\n // \u2500\u2500 robots.txt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (settings.robots.enabled && own.robots) {\n notes.push(`robots.txt: the site writes its own (${own.robots}); left as it is.${Object.keys(settings.crawlers).length ? " The crawler choices in the visibility file are not applied: remove the site\'s own robots.txt to let the kit write them." : ""}`);\n }\n if (settings.robots.enabled && !own.robots) {\n files["robots.txt"] = robotsText({ settings, base, sitemap: origin ? sitemapUrl : "" });\n types["robots.txt"] = "text/plain; charset=utf-8";\n if (base) notes.push(`robots.txt is written for ${base}/, but crawlers only read the one at the root of the host; copy its rules there if this site is served under a sub-path.`);\n }\n\n // \u2500\u2500 agent.md \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (agent.agentPage && (own.agentPage || files["agent.md"] !== undefined)) notes.push("agent.md: the site has a page of its own at that address; left as it is.");\n if (writeAgent) {\n files["agent.md"] = agentText({ siteName, summary, rootUrl, base, abs, home, settings, has: { llms: writeLlms || own.llmsTxt, full: writeFull || own.llmsFullTxt, twins: twinOf.size > 0, robots: Boolean(files["robots.txt"] || own.robots), sitemap: sitemapUrl }, contactPage: byKey.get(pathKey(`${base}/contact/`)), example: twinned.find((page) => hasTwin(page) && pathKey(sitePath(page.path, base)) !== "/" && page.path.endsWith("/")) });\n types["agent.md"] = "text/markdown; charset=utf-8";\n }\n\n return {\n head,\n files,\n types,\n notes,\n counts: { pages: input.pages.length, listed: counted.length, twins: twinOf.size, structured, sitemap: writeSitemap ? sitemapPages.length : 0, llmsLinks, fullBytes, fullTruncated },\n };\n}\n\n/** The twin\'s body without its front matter: the page\'s heading first. */\nfunction pageBody(/** @type {PageFacts} */ page) {\n return page.hasH1 || !page.name ? page.markdown : `# ${page.name}\\n\\n${page.markdown}`;\n}\n\n/** A page\'s markdown twin: front matter, then its content. */\nexport function twinText(/** @type {PageFacts} */ page, /** @type {string} */ canonical) {\n const front = [`title: ${yaml(page.name || page.title)}`];\n\n if (page.description) front.push(`description: ${yaml(page.description)}`);\n front.push(`canonical: ${yaml(canonical)}`);\n if (page.lang) front.push(`language: ${yaml(page.lang)}`);\n if (page.published && Number.isFinite(Date.parse(page.published))) front.push(`published: ${yaml(page.published)}`);\n if (page.modified && Number.isFinite(Date.parse(page.modified))) front.push(`last_modified: ${yaml(page.modified)}`);\n return `---\\n${front.join("\\n")}\\n---\\n\\n${pageBody(page)}\\n`;\n}\n\n/**\n * Pages in llms.txt sections: "Pages" (the home page and pages one level\n * deep that have nothing under them), one section per first segment with\n * more than one page (its index page first, then newest first), and\n * "Optional" for what the settings mark secondary.\n *\n * @param {PageFacts[]} pages\n * @param {string} base\n * @param {Map<string, PageFacts>} byKey\n * @param {(page: PageFacts) => boolean} optional\n * @returns {{ title: string; pages: PageFacts[] }[]}\n */\nfunction groupPages(pages, base, byKey, optional) {\n /** @type {Map<string, PageFacts[]>} */\n const groups = new Map();\n const secondary = [];\n\n for (const page of pages) {\n if (optional(page)) {\n secondary.push(page);\n continue;\n }\n const segment = sitePath(page.path, base).split("/").filter(Boolean)[0] ?? "";\n\n (groups.get(segment) ?? groups.set(segment, []).get(segment) ?? []).push(page);\n }\n const main = /** @type {PageFacts[]} */ ([]);\n /** @type {{ title: string; pages: PageFacts[] }[]} */\n const sections = [];\n const newest = (/** @type {PageFacts} */ a, /** @type {PageFacts} */ b) => {\n const da = Date.parse(a.published) || 0;\n const db = Date.parse(b.published) || 0;\n\n return db - da || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);\n };\n\n for (const [segment, list] of [...groups.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n if (segment === "" || list.length === 1) {\n main.push(...list);\n continue;\n }\n const indexKey = pathKey(`${base}/${segment}/`);\n const index = list.filter((page) => pathKey(page.path) === indexKey);\n const rest = list.filter((page) => pathKey(page.path) !== indexKey).sort(newest);\n\n sections.push({ title: oneLine(byKey.get(indexKey)?.name || humanize(segment)), pages: [...index, ...rest] });\n }\n main.sort((a, b) => (pathKey(sitePath(a.path, base)) === "/" ? -1 : pathKey(sitePath(b.path, base)) === "/" ? 1 : a.path < b.path ? -1 : 1));\n return [...(main.length ? [{ title: "Pages", pages: main }] : []), ...sections, ...(secondary.length ? [{ title: "Optional", pages: secondary }] : [])];\n}\n\n/**\n * Which pages are articles, and of what type: the named collections (by\n * their address pattern) or address globs; "auto" means pages that say they\n * are articles (og:type "article").\n *\n * @param {"auto" | false | string[]} articles\n * @param {Record<string, string>} patterns\n * @returns {(path: string, page: PageFacts) => "Article" | "BlogPosting" | null}\n */\nfunction articleScopes(articles, patterns) {\n /** @type {(name: string) => "Article" | "BlogPosting"} */\n const typeFor = (name) => (/(^|\\/)(blog|posts?|journal)(\\/|$|\\*)/i.test(name) ? "BlogPosting" : "Article");\n\n if (articles === false) return () => null;\n if (articles === "auto") return (path, page) => (page.type === "article" ? typeFor(path.split("/").filter(Boolean)[0] ?? "") : null);\n const globs = articles.map((item) => (item.startsWith("/") ? { glob: item, type: typeFor(item) } : { glob: patternGlob(patterns[item] ?? `/${item}/{slug}/`), type: typeFor(item) }));\n\n return (path) => globs.find((entry) => matchGlob(path, entry.glob))?.type ?? null;\n}\n\n/** The logo\'s full address, when its file is really there. */\nfunction resolveLogo(/** @type {string} */ logo, /** @type {string} */ base, /** @type {string} */ origin, /** @type {((path: string) => boolean) | undefined} */ exists, /** @type {string[]} */ notes) {\n if (/^https?:\\/\\//i.test(logo)) return logo;\n if (!origin) return "";\n if (exists && !exists(logo)) {\n notes.push(`structuredData.organization.logo: ${logo} isn\'t among the site\'s files, so the logo was left out.`);\n return "";\n }\n return `${origin}${base}${logo}`;\n}\n\n/**\n * robots.txt from the settings: the site-wide rules for every crawler, then\n * one group per AI crawler the settings name. A crawler with a group of its\n * own ignores the `*` group (RFC 9309), so an allowed crawler\'s group\n * repeats the site-wide rules rather than lifting them.\n *\n * @param {{ settings: VisibilitySettings; base: string; sitemap: string }} input\n */\nexport function robotsText({ settings, base, sitemap }) {\n const rules = [...settings.robots.disallow.map((path) => `Disallow: ${base}${path}`), ...settings.robots.allow.map((path) => `Allow: ${base}${path}`)];\n const siteWide = rules.length ? rules : ["Allow: /"];\n const lines = ["User-agent: *", ...siteWide, ""];\n const known = AI_CRAWLERS.map((crawler) => crawler.token).filter((token) => Object.keys(settings.crawlers).some((key) => key.toLowerCase() === token.toLowerCase()));\n const others = Object.keys(settings.crawlers)\n .filter((key) => !aiCrawler(key))\n .sort((a, b) => a.localeCompare(b));\n const choiceOf = (/** @type {string} */ token) => settings.crawlers[Object.keys(settings.crawlers).find((key) => key.toLowerCase() === token.toLowerCase()) ?? token];\n\n for (const token of [...known, ...others]) {\n const crawler = aiCrawler(token);\n const choice = choiceOf(token);\n\n const note = crawler ? PURPOSE_NOTES[crawler.crawls ? crawler.purpose : "control"] : "";\n\n lines.push(`# ${crawler ? `${crawler.label} (${note})` : "Another crawler named in the visibility settings"}: ${choice === "block" ? "blocked" : "allowed"}`);\n lines.push(`User-agent: ${token}`, ...(choice === "block" ? ["Disallow: /"] : siteWide), "");\n }\n if (sitemap) lines.push(`Sitemap: ${sitemap}`, "");\n return `${lines.join("\\n").replace(/\\n+$/, "")}\\n`;\n}\n\n/**\n * The agent entry page: what the site is, where everything is, how to cite\n * it and how to reach its owner. Plain markdown, no scripts.\n *\n * @param {object} input\n * @param {string} input.siteName\n * @param {string} input.summary\n * @param {string} input.rootUrl\n * @param {string} input.base\n * @param {(path: string) => string} input.abs\n * @param {PageFacts | undefined} input.home\n * @param {VisibilitySettings} input.settings\n * @param {{ llms: boolean; full: boolean; twins: boolean; robots: boolean; sitemap: string }} input.has\n * @param {PageFacts | undefined} input.contactPage\n * @param {PageFacts | undefined} input.example A page to show the twin address with.\n */\nfunction agentText({ siteName, summary, rootUrl, base, abs, home, settings, has, contactPage, example }) {\n const lines = [`# ${oneLine(siteName)}: a guide for AI agents`, ""];\n\n if (summary) lines.push(`> ${summary}`, "");\n lines.push(`This page is for AI agents and assistants reading ${rootUrl}. It says where the site\'s content is in plain text and how to cite it.`, "", "## Where things are", "");\n if (has.llms) lines.push(`- Every page, with a one-line description: ${abs(`${base}/llms.txt`)}`);\n if (has.full) lines.push(`- The whole site in one file: ${abs(`${base}/llms-full.txt`)}`);\n if (has.twins) {\n const shown = example ? `: ${abs(example.path)} has ${abs(twinPath(example.path, base))}, and the home page has ${abs(`${base}/index.md`)}` : `; the home page\'s is ${abs(`${base}/index.md`)}`;\n\n lines.push(`- The markdown version of a page is at its address with \\`.md\\` in place of the last slash${shown}. Each page also names its own in \\`<link rel="alternate" type="text/markdown">\\`.`);\n }\n if (has.sitemap) lines.push(`- Every address, for crawlers: ${has.sitemap}`);\n for (const feed of home?.feeds ?? []) lines.push(`- ${feed.title ? `${oneLine(feed.title)} (feed)` : "Feed"}: ${feed.href}`);\n if (has.robots) lines.push(`- What crawlers may visit: ${abs(`${base}/robots.txt`)}`);\n lines.push(\n "",\n "## How to cite this site",\n "",\n `Name the page and ${oneLine(siteName)}, and link to the page\'s own address (the \\`canonical\\` line at the top of each markdown version), not to the markdown copy. Quote the words as they are; dates and figures are as stated on the page.`,\n "",\n );\n const contact = settings.agentReadable.contact || home?.emails[0] || "";\n const contactLines = [];\n\n if (contact) contactLines.push(/^https?:\\/\\//i.test(contact) ? `- ${contact}` : contact.includes("@") ? `- Email: ${contact}` : `- ${contact}`);\n if (contactPage && contactPage.url !== contact) contactLines.push(`- Contact page: ${contactPage.canonical ?? contactPage.url}`);\n if (contactLines.length) lines.push("## Contact", "", ...contactLines, "");\n lines.push("## About this file", "", "It is written from the site\'s published pages each time the site is built. It holds no scripts and changes only when the site does.", "");\n return lines.join("\\n").replace(/\\n+$/, "\\n");\n}\n', "visibility/structured.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// JSON-LD for the facts a site actually has, checked against Google\'s\n// current documentation (read 23 November 2026). Each builder returns null\n// rather than something incomplete:\n//\n// WebSite home page only; `name` and `url` are required, and the\n// url must be the root of the host \u2014 so nothing is written\n// for a site built under a sub-path.\n// developers.google.com/search/docs/appearance/site-names\n// Organization home page; no required properties \u2014 written with the\n// name and url, plus logo/sameAs/email/telephone when the\n// data file gives them (a logo only when its file exists).\n// \u2026/appearance/structured-data/organization\n// Article / no required properties; written only when the page\n// BlogPosting states a headline and a publication date\n// (article:published_time), with dateModified, author\n// (as a Person, by name) and image when the page states\n// them. The site\'s generic share picture is never used as\n// a post\'s image: Google asks for images of the article.\n// \u2026/appearance/structured-data/article\n// BreadcrumbList pages two or more levels deep; at least two ListItems,\n// each with position, name and an absolute item address.\n// \u2026/appearance/structured-data/breadcrumb\n//\n// A page that already carries a type of its own keeps it, and gets no second\n// one from the kit.\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {Record<string, unknown>} JsonLd */\n\nconst CONTEXT = "https://schema.org";\n\n/** @param {string} value */\nfunction isoDate(value) {\n if (!value) return "";\n const time = Date.parse(value);\n\n return Number.isFinite(time) ? value.trim() : "";\n}\n\n/**\n * @param {{ name: string; url: string; subPath: boolean }} site\n * @returns {JsonLd | null}\n */\nexport function websiteLd(site) {\n if (!site.name || !/^https?:\\/\\//.test(site.url) || site.subPath) return null;\n return { "@context": CONTEXT, "@type": "WebSite", name: site.name, url: site.url };\n}\n\n/**\n * @param {{ name: string; url: string; logo?: string; sameAs?: string[]; email?: string; telephone?: string }} org\n * @returns {JsonLd | null}\n */\nexport function organizationLd(org) {\n if (!org.name || !/^https?:\\/\\//.test(org.url)) return null;\n /** @type {JsonLd} */\n const out = { "@context": CONTEXT, "@type": "Organization", name: org.name, url: org.url };\n\n if (org.logo) out.logo = org.logo;\n if (org.sameAs && org.sameAs.length) out.sameAs = [...org.sameAs];\n if (org.email) out.email = org.email;\n if (org.telephone) out.telephone = org.telephone;\n return out;\n}\n\n/**\n * @param {PageFacts} page\n * @param {{ type: "Article" | "BlogPosting"; siteImage: string }} options\n * @returns {JsonLd | null}\n */\nexport function articleLd(page, options) {\n const headline = page.name.trim();\n const published = isoDate(page.published);\n\n if (!headline || !published) return null;\n /** @type {JsonLd} */\n const out = { "@context": CONTEXT, "@type": options.type, headline, datePublished: published };\n const modified = isoDate(page.modified);\n\n if (modified) out.dateModified = modified;\n if (page.author) out.author = [{ "@type": "Person", name: page.author }];\n if (page.image && page.image !== options.siteImage) out.image = [page.image];\n out.url = page.canonical ?? page.url;\n return out;\n}\n\n/**\n * @param {{ name: string; url: string }[]} trail From the top section down to the page itself.\n * @returns {JsonLd | null}\n */\nexport function breadcrumbLd(trail) {\n const items = trail.filter((step) => step.name && /^https?:\\/\\//.test(step.url));\n\n if (items.length < 2 || items.length !== trail.length) return null;\n return {\n "@context": CONTEXT,\n "@type": "BreadcrumbList",\n itemListElement: items.map((step, index) => ({ "@type": "ListItem", position: index + 1, name: step.name, item: step.url })),\n };\n}\n\n/**\n * Required properties, per Google\'s docs, of what this module writes \u2014 the\n * same rules the app\'s audit applies (packages/core/src/seo/rendered-checks.ts).\n *\n * @param {JsonLd} node\n * @returns {string[]} What is missing; empty when complete.\n */\nexport function missingRequired(node) {\n const type = node["@type"];\n\n if (type === "WebSite") return ["name", "url"].filter((key) => !node[key]);\n if (type === "BreadcrumbList") {\n const items = Array.isArray(node.itemListElement) ? /** @type {Record<string, unknown>[]} */ (node.itemListElement) : [];\n const missing = items.length < 2 ? ["at least two itemListElement entries"] : [];\n\n items.forEach((item, index) => {\n if (typeof item.position !== "number") missing.push(`position on item ${index + 1}`);\n if (!item.name) missing.push(`name on item ${index + 1}`);\n if (typeof item.item !== "string" || !/^https?:\\/\\//.test(item.item)) missing.push(`an absolute item on item ${index + 1}`);\n });\n return missing;\n }\n return [];\n}\n\n/** A JSON-LD block, safe inside HTML. */\nexport function jsonLdTag(/** @type {JsonLd} */ node) {\n return `<script type="application/ld+json" data-galley-jsonld>${JSON.stringify(node).replace(/</g, "\\\\u003c")}</script>`;\n}\n', "client/providers/frame-post.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A real form post \u2014 the way Web-to-Lead and Account Engagement form\n// handlers expect browsers to send \u2014 either into a hidden frame (the visitor\n// stays on the page) or as a normal navigation (the visitor goes on to the\n// provider\'s return page). Neither provider sends CORS headers, so `fetch`\n// could not read their answer anyway; a frame at least tells us the post\n// completed (its `load` event), and when the provider sends the frame on to a\n// page of *this* site, the runtime can read where it landed.\n\nlet counter = 0;\n\n/**\n * @param {string} action\n * @param {{ [name: string]: string | string[] }} values\n * @param {{ navigate?: boolean; timeoutMs?: number }} [options]\n * @returns {Promise<{ loaded: boolean; location: string | null }>}\n * `location` is the frame\'s final address when it is on this site\'s origin.\n */\nexport function framePost(action, values, options = {}) {\n const form = document.createElement("form");\n\n form.method = "POST";\n form.action = action;\n form.acceptCharset = "UTF-8";\n form.hidden = true;\n for (const [name, value] of Object.entries(values)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n const input = document.createElement("input");\n\n input.type = "hidden";\n input.name = name;\n input.value = item;\n form.append(input);\n }\n }\n if (options.navigate) {\n document.body.append(form);\n form.submit();\n return Promise.resolve({ loaded: false, location: null });\n }\n const name = `galley-post-${Date.now().toString(36)}-${(counter += 1)}`;\n const frame = document.createElement("iframe");\n\n frame.name = name;\n frame.title = "";\n frame.hidden = true;\n frame.setAttribute("aria-hidden", "true");\n frame.tabIndex = -1;\n form.target = name;\n document.body.append(frame, form);\n\n return new Promise((resolve) => {\n let settled = false;\n const finish = (/** @type {boolean} */ loaded) => {\n if (settled) return;\n settled = true;\n let location = null;\n\n try {\n location = frame.contentWindow?.location.href ?? null;\n if (location === "about:blank") location = null;\n } catch {\n // Another origin: the browser doesn\'t say where the frame is.\n }\n resolve({ loaded, location });\n setTimeout(() => {\n frame.remove();\n form.remove();\n }, 1000);\n };\n\n frame.addEventListener("load", () => finish(true));\n setTimeout(() => finish(false), options.timeoutMs ?? 20000);\n form.submit();\n });\n}\n', "client/providers/galley.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Galley\'s own capture endpoint \u2014 the default destination. The request and\n// response are specified in docs/forms.md, "The capture endpoint":\n// POST <endpoint> content-type: application/json\n// { form, values, page: { url, title, referrer }, meta }\n// 200 { ok: true, id } \xB7 422 { ok: false, errors: { fieldId: message }, message? }\n// 429 { ok: false, message } + Retry-After \xB7 403 origin refused \xB7 404 form not taken here\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const own = destination.settings.endpoint;\n const root = /** @type {HTMLElement | null} */ (context.form.closest(".galley-form"));\n const configured = root?.querySelector("script[data-galley-form-config]")?.textContent;\n // Which address, in the order docs/forms.md gives: the destination\'s own\n // settings.endpoint; else the page\'s <html data-galley-endpoint> (how\n // Galley\'s preview sends test submissions to its own inbox, so it wins over\n // the site-wide address \u2014 a published page never carries it unless the site\n // sets it on purpose); else the site-wide capture address.\n const endpoint = (typeof own === "string" && own) || document.documentElement.dataset.galleyEndpoint || (configured ? JSON.parse(configured).endpoint : "") || "";\n\n if (!endpoint) return { ok: false, notConnected: true, detail: "No capture address is set for the Galley inbox." };\n let response;\n\n try {\n response = await fetch(endpoint, {\n method: "POST",\n headers: { "content-type": "application/json", accept: "application/json" },\n body: JSON.stringify({ form: context.formId, values, page: context.page, meta: context.meta }),\n });\n } catch (error) {\n return { ok: false, detail: `The capture endpoint couldn\'t be reached: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (response.status === 429) {\n // The capture server says how long to wait, and exposes the header to the page.\n const header = response.headers.get("retry-after") ?? "";\n const seconds = /^\\d+$/.test(header) ? Number(header) : header ? Math.max(1, Math.ceil((Date.parse(header) - Date.now()) / 1000)) : NaN;\n\n return { ok: false, retry: true, ...(Number.isFinite(seconds) && seconds > 0 ? { retryAfter: seconds } : {}), detail: "The capture endpoint asked to slow down (429)." };\n }\n /** @type {any} */\n const answer = await response.json().catch(() => null);\n\n if (response.ok && answer?.ok === true) return { ok: true, detail: `Stored as ${answer.id ?? "a new submission"}.` };\n if (response.status === 404) return { ok: false, notConnected: true, detail: `The capture endpoint doesn\'t take this form (404)${answer?.message ? `: ${answer.message}` : ""}.` };\n if (response.status === 403) return { ok: false, detail: "The capture endpoint refused this page\'s origin (403). Check the site\'s addresses in the app\'s capture settings." };\n return {\n ok: false,\n errors: answer && typeof answer.errors === "object" && answer.errors ? answer.errors : {},\n ...(typeof answer?.message === "string" && answer.message ? { message: answer.message } : {}),\n detail: `The capture endpoint answered ${response.status}${answer?.message ? `: ${answer.message}` : ""}.`,\n };\n}\n', "client/providers/hubspot.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// HubSpot: the Forms API\'s unauthenticated, CORS-enabled "submit data to a\n// form" endpoint (legacy v3, still supported):\n// POST https://api.hsforms.com/submissions/v3/integration/submit/{portalId}/{formGuid}\n// (api-{region}.hsforms.com for accounts in another data region, e.g. eu1)\n// { submittedAt, fields: [{ objectTypeId, name, value }],\n// context: { hutk, pageUri, pageName }, legalConsentOptions? }\n// The form must exist in HubSpot with the same field names; HubSpot runs its\n// own validation and answers 400 with `errors: [{ message, errorType }]`.\n//\n// Mapping conventions (docs/forms.md):\n// "email" a contact property (objectTypeId 0-1)\n// "0-2/name" another object\'s property (here: company name)\n// "consent:process" a consent field \u2192 legalConsentOptions.consent.consentToProcess\n// "consent:communication:<subscriptionTypeId>"\n// a consent field \u2192 one communications subscription\n// An unmapped consent field counts as consent to process.\n\nimport { plainText } from "../../shared/markdown.js";\n\n/** @param {string} name */\nfunction cookie(name) {\n const match = document.cookie.split(/;\\s*/).find((part) => part.startsWith(`${name}=`));\n\n return match ? decodeURIComponent(match.slice(name.length + 1)) : "";\n}\n\n/** @param {string} region */\nexport function hubspotHost(region) {\n return !region || region === "na1" ? "https://api.hsforms.com" : `https://api-${region}.hsforms.com`;\n}\n\n/** @type {import("../types").Submitter} */\nexport async function submit(_values, destination, context) {\n const settings = destination.settings;\n const portalId = String(settings.portalId ?? "");\n const formId = String(settings.formId ?? "");\n\n if (!portalId || !formId) return { ok: false, notConnected: true, detail: "HubSpot needs settings.portalId and settings.formId." };\n /** @type {{ objectTypeId: string; name: string; value: string }[]} */\n const fields = [];\n /** @type {{ consentToProcess: boolean; text: string; communications: { value: boolean; subscriptionTypeId: number; text: string }[] } | null} */\n let consent = null;\n const consentBlock = () => (consent ??= { consentToProcess: false, text: "", communications: [] });\n\n for (const item of context.items) {\n const value = Array.isArray(item.value) ? item.value.join(";") : item.value;\n\n if (item.field.type === "consent") {\n const text = plainText(item.field.text ?? item.field.label ?? "");\n const agreed = value === "true";\n const communication = /^consent:communication:(\\d+)$/.exec(item.name);\n\n if (communication) consentBlock().communications.push({ value: agreed, subscriptionTypeId: Number(communication[1]), text });\n else if (item.name === "consent:process" || !destination.mapping?.[item.field.id]) Object.assign(consentBlock(), { consentToProcess: agreed, text });\n else fields.push({ objectTypeId: "0-1", name: item.name, value });\n continue;\n }\n const [, objectTypeId = "0-1", name = item.name] = /^(\\d+-\\d+)\\/(.+)$/.exec(item.name) ?? [];\n\n fields.push({ objectTypeId, name, value });\n }\n for (const [name, value] of Object.entries(destination.constants ?? {})) {\n const [, objectTypeId = "0-1", property = name] = /^(\\d+-\\d+)\\/(.+)$/.exec(name) ?? [];\n\n fields.push({ objectTypeId, name: property, value });\n }\n const hutk = cookie("hubspotutk");\n /** @type {Record<string, unknown>} */\n const body = {\n submittedAt: String(Date.now()),\n fields,\n context: { ...(hutk ? { hutk } : {}), pageUri: context.page.url, pageName: context.page.title },\n };\n\n if (consent) body.legalConsentOptions = { consent };\n const region = typeof settings.region === "string" ? settings.region : "";\n let response;\n\n try {\n response = await fetch(`${hubspotHost(region)}/submissions/v3/integration/submit/${encodeURIComponent(portalId)}/${encodeURIComponent(formId)}`, {\n method: "POST",\n headers: { "content-type": "application/json" },\n body: JSON.stringify(body),\n });\n } catch (error) {\n return { ok: false, detail: `HubSpot couldn\'t be reached: ${error instanceof Error ? error.message : String(error)}` };\n }\n /** @type {any} */\n const answer = await response.json().catch(() => ({}));\n\n if (response.ok) return { ok: true, redirect: answer.redirectUri, detail: "HubSpot accepted the submission." };\n if (response.status === 429) return { ok: false, retry: true, detail: "HubSpot asked to slow down (429)." };\n /** @type {Record<string, string>} */\n const errors = {};\n\n for (const error of Array.isArray(answer.errors) ? answer.errors : []) {\n // e.g. "Error in \'fields.email\'. Invalid email address"\n const field = /fields\\.([\\w-]+)/.exec(String(error.message ?? ""))?.[1];\n const item = field ? context.items.find((entry) => entry.name === field || entry.name.endsWith(`/${field}`)) : undefined;\n\n if (item) errors[item.field.id] = error.errorType === "INVALID_EMAIL" ? context.messages.email ?? String(error.message) : String(error.message).replace(/^Error in \'[^\']*\'\\.\\s*/, "");\n }\n return {\n ok: false,\n errors,\n detail: `HubSpot refused the submission (${response.status}): ${(Array.isArray(answer.errors) ? answer.errors : []).map((/** @type {any} */ error) => error.errorType ?? error.message).join(", ") || answer.message || "no reason given"}`,\n };\n}\n', "client/providers/mailto.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The last resort: opens the visitor\'s own mail program with the answers in a\n// new message. Nothing is stored and the page can\'t know whether the message\n// was sent \u2014 only that the mail program was asked to open.\n\n/** @type {import("../types").Submitter} */\nexport function submit(_values, destination, context) {\n const to = typeof destination.settings.to === "string" ? destination.settings.to : "";\n\n if (!to) return { ok: false, notConnected: true, detail: "The mail destination needs settings.to." };\n const subject = typeof destination.settings.subject === "string" ? destination.settings.subject : "";\n const lines = context.items.map(({ field, value }) => `${field.label ?? field.id}: ${Array.isArray(value) ? value.join(", ") : value}`);\n\n for (const [name, value] of Object.entries(destination.constants ?? {})) lines.push(`${name}: ${value}`);\n const query = [subject ? `subject=${encodeURIComponent(subject)}` : "", `body=${encodeURIComponent(lines.join("\\n"))}`].filter(Boolean).join("&");\n\n location.href = `mailto:${to}?${query}`;\n return { ok: true, detail: "Asked the mail program to open." };\n}\n', "client/providers/marketo.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Marketo, through Marketo\'s own Forms 2.0 library and a hidden Marketo form,\n// as Adobe documents it: load {host}/js/forms2/js/forms2.min.js, call\n// MktoForms2.loadForm(host, munchkinId, formId), put the answers on the\n// Marketo form (setValues for fields the form has, addHiddenFields for the\n// rest \u2014 the only way values reach a known-visitor form), then submit() with\n// an onSuccess that returns false so the page stays put.\n//\n// Posting straight to Marketo\'s endpoint is not a supported API; going\n// through the library keeps Marketo\'s own validation, its anti-spam checks\n// and the Munchkin cookie association (the library sends _mkto_trk itself).\n// When Marketo refuses a value, its message is shown on our field.\n\n/** @type {Map<string, Promise<void>>} */\nconst libraries = new Map();\n/** @type {Map<string, Promise<any>>} */\nconst loaded = new Map();\n\n/** @param {string} host */\nfunction library(host) {\n if (window.MktoForms2) return Promise.resolve();\n const known = libraries.get(host);\n\n if (known) return known;\n const promise = new Promise((resolve, reject) => {\n const script = document.createElement("script");\n\n script.src = `${host}/js/forms2/js/forms2.min.js`;\n script.async = true;\n script.onload = () => (window.MktoForms2 ? resolve(undefined) : reject(new Error("Marketo\'s forms library loaded but did not start.")));\n script.onerror = () => reject(new Error(`Marketo\'s forms library couldn\'t load from ${host}.`));\n document.head.append(script);\n });\n\n libraries.set(host, /** @type {Promise<void>} */ (promise));\n return /** @type {Promise<void>} */ (promise);\n}\n\n/** @param {string} host @param {string} munchkinId @param {string} formId */\nfunction marketoForm(host, munchkinId, formId) {\n const key = `${host}|${munchkinId}|${formId}`;\n const known = loaded.get(key);\n\n if (known) return known;\n const promise = library(host).then(\n () =>\n new Promise((resolve, reject) => {\n let element = document.getElementById(`mktoForm_${formId}`);\n\n if (!element) {\n element = document.createElement("form");\n element.id = `mktoForm_${formId}`;\n element.hidden = true;\n element.setAttribute("aria-hidden", "true");\n element.style.display = "none";\n document.body.append(element);\n }\n const timer = setTimeout(() => reject(new Error("Marketo\'s form didn\'t load in time.")), 15000);\n\n window.MktoForms2.loadForm(host, munchkinId, Number(formId), (/** @type {any} */ form) => {\n clearTimeout(timer);\n resolve(form);\n });\n }),\n );\n\n loaded.set(key, promise);\n promise.catch(() => loaded.delete(key));\n return promise;\n}\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination) {\n const settings = destination.settings;\n const host = String(settings.host ?? "").replace(/\\/+$/, "");\n const munchkinId = String(settings.munchkinId ?? "");\n const formId = String(settings.formId ?? "");\n\n if (!host || !munchkinId || !formId) return { ok: false, notConnected: true, detail: "Marketo needs settings.host, settings.munchkinId and settings.formId." };\n let form;\n\n try {\n form = await marketoForm(host, munchkinId, formId);\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n /** @type {Record<string, string>} */\n const flat = {};\n\n for (const [name, value] of Object.entries(values)) flat[name] = Array.isArray(value) ? value.join(";") : value;\n const onForm = Object.keys(form.getValues?.() ?? {});\n /** @type {Record<string, string>} */\n const present = {};\n /** @type {Record<string, string>} */\n const extra = {};\n\n for (const [name, value] of Object.entries(flat)) (onForm.includes(name) ? present : extra)[name] = value;\n form.setValues(present);\n if (Object.keys(extra).length > 0) form.addHiddenFields(extra);\n\n // Marketo\'s callbacks can\'t be removed, so each form gets them once and\n // they answer whichever submission is in flight.\n if (!form.__galley) {\n form.__galley = { end: null };\n form.onValidate((/** @type {boolean} */ valid) => {\n if (valid) return;\n // Marketo marks the refused field and writes its message into its own DOM.\n const element = form.getFormElem?.()?.[0];\n const invalid = element?.querySelector(".mktoInvalid");\n const message = element?.querySelector(".mktoErrorMsg")?.textContent?.trim() || "Marketo refused this answer.";\n const name = invalid?.getAttribute("name");\n\n form.__galley.end?.({ ok: false, errors: name ? { [name]: message } : {}, detail: `Marketo refused the submission: ${message}` });\n });\n form.onSuccess((/** @type {unknown} */ _values, /** @type {string} */ followUpUrl) => {\n form.__galley.end?.({ ok: true, redirect: followUpUrl || undefined, detail: "Marketo accepted the submission." });\n return false;\n });\n }\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => end({ ok: false, detail: "Marketo didn\'t confirm the submission in time." }), 20000);\n const end = (/** @type {import("../types").SubmitResult} */ result) => {\n clearTimeout(timer);\n form.__galley.end = null;\n resolve(result);\n };\n\n form.__galley.end = end;\n form.submit();\n });\n}\n', "client/providers/pardot.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Account Engagement (Pardot) form handler: a form post to the handler\'s\n// address with fields under the handler\'s external field names (`mapping`).\n// Handlers don\'t accept fetch/XHR posts (no CORS), so the post goes through a\n// hidden frame \u2014 or, with `mode: "navigate"`, as a normal navigation, which\n// is the better choice when visitor tracking matters (the handler\'s cookie is\n// set in a top-level page, not a third-party frame).\n//\n// Telling success from failure: point the handler\'s Success Location and\n// Error Location at two pages on this site and copy them into\n// `successLocation` / `errorLocation`. The frame then lands on one of them\n// (same origin, so the page can read where) and the runtime knows which.\n// Without them, a completed post counts as success.\n\nimport { framePost } from "./frame-post.js";\n\n/** @param {string} a @param {string} b */\nconst samePage = (a, b) => {\n try {\n const x = new URL(a);\n const y = new URL(b, location.href);\n\n return x.origin === y.origin && x.pathname.replace(/\\/+$/, "") === y.pathname.replace(/\\/+$/, "");\n } catch {\n return false;\n }\n};\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination) {\n const settings = destination.settings;\n const handler = typeof settings.handlerUrl === "string" ? settings.handlerUrl : "";\n\n if (!handler) return { ok: false, notConnected: true, detail: "Account Engagement needs settings.handlerUrl." };\n const navigate = settings.mode === "navigate";\n const result = await framePost(handler, values, { navigate });\n\n if (navigate) return { ok: true };\n if (!result.loaded) return { ok: false, detail: "The form handler didn\'t answer in time." };\n const errorLocation = typeof settings.errorLocation === "string" ? settings.errorLocation : "";\n const successLocation = typeof settings.successLocation === "string" ? settings.successLocation : "";\n\n if (result.location && errorLocation && samePage(result.location, errorLocation)) {\n const message = new URL(result.location).searchParams.get("errorMessage");\n\n return { ok: false, detail: message ? `The form handler refused the submission: ${message}` : "The form handler sent the visitor to its error location." };\n }\n if (result.location && successLocation && !samePage(result.location, successLocation) && errorLocation) {\n return { ok: false, detail: `The form handler finished on ${result.location}, which is neither its success nor its error location.` };\n }\n return { ok: true, detail: result.location ? "The form handler reached its success location." : "Posted to the form handler; it does not tell the page more." };\n}\n', "client/providers/salesforce.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Salesforce Web-to-Lead. A form post to the Web-to-Lead servlet with the\n// org\'s `oid`, standard lead fields by their Salesforce names (first_name,\n// last_name, email, company, phone, lead_source, \u2026) and custom fields by\n// their field ids (00N\u2026), mapped in the destination\'s `mapping`. Fixed\n// values (lead_source, Campaign_ID, recordType, debug, debugEmail) go in\n// `constants`.\n//\n// What the browser cannot know: Salesforce answers with a redirect to\n// `retURL` and no CORS headers, so the page never learns whether the lead was\n// accepted (duplicate rules, bad picklist values, the daily limit all look\n// the same). A completed post counts as success; docs/forms.md says so.\n\nimport { framePost } from "./frame-post.js";\n\nexport const SERVLET = "https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const settings = destination.settings;\n const orgId = typeof settings.orgId === "string" ? settings.orgId : "";\n\n if (!orgId) return { ok: false, notConnected: true, detail: "Salesforce needs settings.orgId." };\n /** @type {{ [name: string]: string | string[] }} */\n const fields = {};\n\n for (const [name, value] of Object.entries(values)) {\n // Checkboxes: Salesforce reads "1" as ticked; an unticked box is left out.\n if (value === "true" || value === "false") {\n const field = context.items.find((item) => item.name === name)?.field;\n\n if (field && (field.type === "checkbox" || field.type === "consent")) {\n if (value === "true") fields[name] = "1";\n continue;\n }\n }\n fields[name] = value;\n }\n const navigate = settings.mode === "navigate";\n const returnUrl = typeof settings.returnUrl === "string" ? settings.returnUrl : "";\n // In a frame, no retURL means Salesforce answers with an empty page \u2014 the\n // lightest possible end to the post. (A page of this site loaded in the\n // frame skips its third-party scripts: see scripts/runtime.js.)\n const target = navigate ? returnUrl || location.href : returnUrl;\n const result = await framePost(SERVLET, { oid: orgId, ...(target ? { retURL: target } : {}), ...fields }, { navigate });\n\n if (navigate) return { ok: true, detail: "Sent to Salesforce; the visitor is on their way to the return address." };\n return result.loaded ? { ok: true, detail: "Posted to Web-to-Lead. Salesforce does not tell the page whether it created the lead." } : { ok: false, detail: "Web-to-Lead didn\'t answer in time." };\n}\n', "client/providers/webhook.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Any address that accepts a POST: an automation tool, a serverless\n// function, the site owner\'s own service. `format: "json"` (default) sends\n// { form, values, page, at }; `format: "form"` sends the values\n// form-encoded. The receiving server must allow this site\'s origin (CORS):\n// a JSON post is preceded by an OPTIONS preflight; a form-encoded one is not,\n// but its answer is still only readable with Access-Control-Allow-Origin.\n// An answer of { errors: { name: message } } puts messages on the fields.\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const url = typeof destination.settings.url === "string" ? destination.settings.url : "";\n\n if (!url) return { ok: false, notConnected: true, detail: "The webhook needs settings.url." };\n const form = destination.settings.format === "form";\n let body;\n\n if (form) {\n const params = new URLSearchParams();\n\n for (const [name, value] of Object.entries(values)) for (const item of Array.isArray(value) ? value : [value]) params.append(name, item);\n body = params;\n } else {\n body = JSON.stringify({ form: context.formId, values, page: context.page, at: new Date().toISOString() });\n }\n let response;\n\n try {\n response = await fetch(url, { method: "POST", body, ...(form ? {} : { headers: { "content-type": "application/json" } }) });\n } catch (error) {\n return { ok: false, detail: `The webhook couldn\'t be reached (or doesn\'t allow this site\'s origin): ${error instanceof Error ? error.message : String(error)}` };\n }\n if (response.status === 429) return { ok: false, retry: true, detail: "The webhook asked to slow down (429)." };\n if (response.ok) return { ok: true, detail: `The webhook answered ${response.status}.` };\n /** @type {any} */\n const answer = await response.json().catch(() => null);\n\n return { ok: false, errors: answer?.errors && typeof answer.errors === "object" ? answer.errors : {}, detail: `The webhook answered ${response.status}.` };\n}\n', "runtime/site-config.js": '// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The site\'s kit settings, read from files (a vendored kit has no\n// integration to pass them): src/galley/settings.json for the forms,\n// src/data/scripts.json for the managed scripts, src/content/forms/ for the\n// site-wide UTM memory, and the email-link dialog\'s settings.\nimport settings from "../settings.json";\nimport { resolveMailto } from "../mailto/config.js";\nimport { describeIssues, scriptsSchema } from "../schema.js";\nimport { resolveEntries } from "../scripts/plan.js";\n\n/** @typedef {import("../kit").ScriptsConfig} ScriptsConfig */\n\nconst scriptFiles = import.meta.glob("/src/data/scripts.json", { eager: true, import: "default" });\nconst formFiles = import.meta.glob("/src/content/forms/*.json", { eager: true, import: "default" });\n\nexport const scriptsFile = "src/data/scripts.json";\n\n/** @returns {ScriptsConfig | null} */\nfunction readScripts() {\n const raw = scriptFiles["/src/data/scripts.json"];\n\n if (raw === undefined) return null;\n const parsed = scriptsSchema.safeParse(raw);\n\n if (!parsed.success) throw new Error(`src/data/scripts.json has problems:\\n${describeIssues(parsed.error).map((line) => ` - ${line}`).join("\\n")}`);\n const config = /** @type {ScriptsConfig} */ (parsed.data);\n\n resolveEntries(config);\n return config;\n}\n\nexport const scripts = readScripts();\n\nconst forms = /** @type {Record<string, unknown>} */ (settings.forms ?? {});\n\nexport const options = {\n collection: typeof forms.collection === "string" ? forms.collection : "forms",\n endpoint: typeof forms.endpoint === "string" ? forms.endpoint : "",\n allowFormScripts: forms.allowFormScripts === true,\n messages: /** @type {Record<string, string>} */ (forms.messages ?? {}),\n freeEmailDomains: /** @type {string[]} */ (forms.freeEmailDomains ?? []),\n};\n\n/** The email-link dialog: on unless settings.json says "mailto": false. */\nexport const mailto = resolveMailto(/** @type {any} */ (settings).mailto);\n\nexport const utm = Object.values(formFiles).some(\n (form) => Array.isArray(/** @type {any} */ (form)?.fields) && /** @type {any} */ (form).fields.some((/** @type {any} */ field) => field?.autofill?.from === "utm"),\n);\n', "integration.js": `// Vendored from @galley/astro 0.1.0 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163565
|
+
`, "visibility/site.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The whole agent-readable output of a site, from its rendered pages: which\n// pages count, each page\'s markdown twin and the tags its <head> gains, and\n// the site-wide files \u2014 llms.txt, llms-full.txt, agent.md, robots.txt and\n// sitemap.xml. Pure: the same pages and settings always give the same bytes,\n// whether they come from a build\'s output folder or a running dev server.\n//\n// Addresses (every one under the site\'s base path):\n// a page /about/ its twin /about.md\n// the home page / its twin /index.md\n// a file-style page /about.html its twin /about.md\n// \u2014 the llms.txt proposal\'s "the page\'s address with .md" for pages without\n// a trailing slash, and its "index.md" form for the home page. A twin is a\n// plain file next to the page\'s folder, so it works on any static host,\n// under any sub-path, with no rewrite rules.\n\nimport { matchGlob } from "../shared/glob.js";\nimport { AI_CRAWLERS, aiCrawler, PURPOSE_NOTES } from "./crawlers.js";\nimport { patternGlob } from "./content.js";\nimport { articleLd, breadcrumbLd, jsonLdTag, organizationLd, websiteLd } from "./structured.js";\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {import("./config.js").VisibilitySettings} VisibilitySettings */\n\n/** llms.txt lists at most this many pages; the rest are in the sitemap. */\nexport const MAX_LLMS_LINKS = 2000;\n/** The sitemaps protocol\'s limit per file. */\nexport const MAX_SITEMAP_URLS = 50_000;\n\n/**\n * @typedef {object} SiteInput\n * @property {PageFacts[]} pages Every rendered page.\n * @property {VisibilitySettings} settings\n * @property {string} origin "https://www.example.com", or "" when the site has no `site` address.\n * @property {string} base The base path without a trailing slash ("" or "/demo").\n * @property {{ robots: string | null; sitemap: string | null; llmsTxt: boolean; llmsFullTxt: boolean; agentPage: boolean }} own\n * What the site already publishes itself (the kit then leaves it alone). `robots` / `sitemap`: the file\'s name, or null.\n * @property {string[]} [drafts] Addresses (without the base) of draft entries.\n * @property {Record<string, string>} [dates] Address (without the base) \u2192 its content entry\'s date, for pages whose HTML states none.\n * @property {Record<string, string>} [patterns] Collection id \u2192 address pattern ("/blog/{slug}/").\n * @property {string} [fallbackName] The site\'s name when no page states one (galley.config.json).\n * @property {(path: string) => boolean} [fileExists] Whether the site serves a file (for the logo).\n */\n\n/**\n * @typedef {object} SitePlan\n * @property {Map<string, string>} head page path \u2192 HTML to add before </head>.\n * @property {Record<string, string>} files File path under the output folder \u2192 text.\n * @property {Record<string, string>} types File path \u2192 content type, for a server.\n * @property {string[]} notes What the build log says.\n * @property {{ pages: number; listed: number; twins: number; structured: number; sitemap: number; llmsLinks: number; fullBytes: number; fullTruncated: boolean }} counts\n */\n\n/**\n * "/demo/about/" \u2192 "/demo/about.md"; the home page "/demo/" \u2192 "/demo/index.md".\n *\n * @param {string} path The page\'s address, with the base.\n * @param {string} [base] The base path ("" or "/demo"), to know the home page.\n */\nexport function twinPath(path, base = "") {\n const clean = path.split(/[?#]/)[0] ?? "/";\n\n if (clean === "/" || clean === `${base}/`) return `${clean}index.md`;\n if (clean.endsWith("/")) return `${clean.slice(0, -1)}.md`;\n if (/\\/index\\.html?$/.test(clean)) return clean.replace(/\\/index\\.html?$/, "/index.md");\n return `${clean.replace(/\\.html?$/, "")}.md`;\n}\n\n/** The page addresses a twin address can belong to, most likely first. */\nexport function pagesForTwin(/** @type {string} */ path, /** @type {string} */ base) {\n if (!path.endsWith(".md")) return [];\n const bare = path.slice(0, -3);\n\n if (bare === `${base}/index`) return [`${base}/`];\n if (bare.endsWith("/index")) return [`${bare.slice(0, -"index".length)}`, `${bare}/`];\n return [`${bare}/`, bare, `${bare}.html`];\n}\n\n/** "/about" and "/about/" as one key. */\nexport function pathKey(/** @type {string} */ path) {\n const bare = (path.split(/[?#]/)[0] ?? "").replace(/\\/index\\.html?$/, "/").replace(/\\.html?$/, "");\n\n return bare === "/" || bare === "" ? "/" : bare.replace(/\\/+$/, "");\n}\n\n/** The page\'s address on the site without the base: "/demo/about/" \u2192 "/about/". */\nexport function sitePath(/** @type {string} */ path, /** @type {string} */ base) {\n if (!base) return path;\n if (path === base) return "/";\n return path.startsWith(`${base}/`) ? path.slice(base.length) : path;\n}\n\nconst SPECIAL = /^\\/(404|500)(\\/|\\.html)?$/;\n\n/** @param {string} value */\nconst yaml = (value) => JSON.stringify(value);\n/** @param {string} value */\nconst xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/\'/g, "'");\n/** One line of text for a list: no line breaks. */\nconst oneLine = (/** @type {string} */ value) => value.replace(/\\s+/g, " ").trim();\n/** Link text for llms.txt: brackets would end the link early. */\nconst linkText = (/** @type {string} */ value) => oneLine(value).replace(/([[\\]\\\\])/g, "\\\\$1");\n\n/** @param {string} value */\nfunction dateOnly(value) {\n const time = Date.parse(value);\n\n return Number.isFinite(time) ? new Date(time).toISOString().slice(0, 10) : "";\n}\n\n/** "release-notes" \u2192 "Release notes". */\nfunction humanize(/** @type {string} */ segment) {\n const words = decodeURIComponent(segment).replace(/[-_]+/g, " ").trim();\n\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : segment;\n}\n\n/**\n * Whether a robots rule path (with `*` and `$`) matches an address.\n *\n * @param {string} rule\n * @param {string} path\n */\nfunction robotsMatch(rule, path) {\n const anchored = rule.endsWith("$");\n const body = anchored ? rule.slice(0, -1) : rule;\n const source = body\n .split("*")\n .map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, "\\\\$&"))\n .join(".*");\n\n return new RegExp(`^${source}${anchored ? "$" : ""}`).test(path);\n}\n\n/**\n * Whether the site-wide rules let crawlers fetch an address: the longest\n * matching rule wins, and Allow wins a tie (RFC 9309, section 2.2.2).\n *\n * @param {{ disallow: string[]; allow: string[] }} rules\n * @param {string} path\n */\nexport function robotsAllows(rules, path) {\n let best = { allow: true, length: -1 };\n\n for (const [allow, list] of /** @type {[boolean, string[]][]} */ ([[false, rules.disallow], [true, rules.allow]])) {\n for (const rule of list) {\n if (!robotsMatch(rule, path)) continue;\n if (rule.length > best.length || (rule.length === best.length && allow)) best = { allow, length: rule.length };\n }\n }\n return best.allow;\n}\n\n/**\n * @param {SiteInput} input\n * @returns {SitePlan}\n */\nexport function planSite(input) {\n const { settings, origin, base, own } = input;\n const agent = settings.agentReadable;\n const notes = /** @type {string[]} */ ([]);\n const abs = (/** @type {string} */ path) => (origin ? `${origin}${path}` : path);\n const home = input.pages.find((page) => pathKey(sitePath(page.path, base)) === "/");\n const drafts = new Set((input.drafts ?? []).map(pathKey));\n const siteName = settings.site.name || home?.siteName || input.fallbackName || home?.name || (origin ? new URL(origin).hostname : "This site");\n const summary = oneLine(settings.site.summary || home?.description || "");\n const rootUrl = abs(`${base}/`);\n // A page the kit\'s own robots.txt asks every crawler to stay away from isn\'t listed for them either.\n const disallowed = (/** @type {string} */ path) => settings.robots.enabled && !own.robots && !robotsAllows(settings.robots, sitePath(path, base));\n\n // \u2500\u2500 Which pages count \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** @param {PageFacts} page */\n const listed = (page) => {\n const local = sitePath(page.path, base);\n\n if (page.noindex || page.redirect || SPECIAL.test(local) || drafts.has(pathKey(local)) || disallowed(page.path)) return false;\n // A page whose canonical address is another page is a copy of that page.\n if (page.canonical) {\n try {\n if (pathKey(new URL(page.canonical).pathname) !== pathKey(page.path)) return false;\n } catch {\n return false;\n }\n }\n return true;\n };\n // A page that states no date of its own takes its content entry\'s, when it has one.\n const dated = new Map(Object.entries(input.dates ?? {}).map(([path, date]) => [pathKey(path), date]));\n const pages = [...input.pages]\n .map((page) => {\n const date = page.published ? "" : dated.get(pathKey(sitePath(page.path, base)));\n\n return date ? { ...page, published: date } : page;\n })\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n const counted = pages.filter(listed);\n const byKey = new Map(counted.map((page) => [pathKey(page.path), page]));\n const twinned = agent.markdownTwins ? counted.filter((page) => page.markdown && !agent.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob))) : [];\n /** @type {Record<string, string>} */\n const files = {};\n /** @type {Record<string, string>} */\n const types = {};\n const twinOf = new Map(/** @type {[string, string][]} */ ([]));\n const fileFor = (/** @type {string} */ path) => sitePath(path, base).replace(/^\\/+/, "");\n\n // \u2500\u2500 Twins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const page of twinned) {\n const path = twinPath(page.path, base);\n const file = fileFor(path);\n\n if (files[file] !== undefined) {\n notes.push(`${path} would be the markdown version of two pages; only ${twinOf.get(file) ?? "the first"} got it.`);\n continue;\n }\n files[file] = twinText(page, page.canonical ?? page.url);\n types[file] = "text/markdown; charset=utf-8";\n twinOf.set(file, page.path);\n }\n const hasTwin = (/** @type {PageFacts} */ page) => twinOf.get(fileFor(twinPath(page.path, base))) === page.path;\n\n // \u2500\u2500 Structured data and the <head> link \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sd = settings.structuredData;\n const subPath = Boolean(base);\n const scopes = articleScopes(sd.articles, input.patterns ?? {});\n /** @type {Map<string, string>} */\n const head = new Map();\n let structured = 0;\n const logo = sd.organization && sd.organization.logo ? resolveLogo(sd.organization.logo, base, origin, input.fileExists, notes) : "";\n\n if (!origin && (sd.website || sd.organization || sd.articles || sd.breadcrumbs)) notes.push("Structured data needs full addresses: set `site` in astro.config (e.g. site: \\"https://www.example.com\\") to add it.");\n for (const page of counted) {\n const local = sitePath(page.path, base);\n const tags = [];\n const has = (/** @type {RegExp} */ type) => page.jsonldTypes.some((name) => type.test(name));\n\n if (hasTwin(page)) tags.push(`<link rel="alternate" type="text/markdown" href="${xml(twinPath(page.path, base))}">`);\n if (origin) {\n if (pathKey(local) === "/") {\n const website = sd.website && !has(/^WebSite$/) ? websiteLd({ name: siteName, url: rootUrl, subPath }) : null;\n const org = sd.organization && !has(/Organization$|^Corporation$|LocalBusiness|^Store$|^Restaurant$/)\n ? organizationLd({ name: sd.organization.name || siteName, url: rootUrl, logo, sameAs: sd.organization.sameAs, email: sd.organization.email, telephone: sd.organization.telephone })\n : null;\n\n if (website) tags.push(jsonLdTag(website));\n if (org) tags.push(jsonLdTag(org));\n }\n const scope = scopes(local, page);\n\n if (scope && !has(/^(Article|BlogPosting|NewsArticle|TechArticle|Report|ScholarlyArticle)$/)) {\n const article = articleLd(page, { type: scope, siteImage: home && home !== page ? home.image : "" });\n\n if (article) tags.push(jsonLdTag(article));\n }\n const segments = local.split("/").filter(Boolean);\n\n if (sd.breadcrumbs && segments.length >= 2 && !has(/^BreadcrumbList$/)) {\n // From the home page (named for the site) down to the page itself, through every level that is a page.\n const homePage = byKey.get(pathKey(`${base}/`));\n /** @type {{ name: string; url: string }[]} */\n const trail = homePage ? [{ name: oneLine(siteName), url: homePage.canonical ?? homePage.url }] : [];\n\n for (let depth = 1; depth < segments.length; depth += 1) {\n const parent = byKey.get(pathKey(`${base}/${segments.slice(0, depth).join("/")}/`));\n\n if (parent) trail.push({ name: oneLine(parent.name), url: parent.canonical ?? parent.url });\n }\n trail.push({ name: oneLine(page.name), url: page.canonical ?? page.url });\n const crumbs = breadcrumbLd(trail);\n\n if (crumbs) tags.push(jsonLdTag(crumbs));\n }\n }\n if (tags.length) {\n head.set(page.path, tags.join(""));\n if (tags.length > (hasTwin(page) ? 1 : 0)) structured += 1;\n }\n }\n\n // \u2500\u2500 llms.txt and llms-full.txt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const entries = (agent.markdownTwins ? twinned.filter(hasTwin) : counted).filter((page) => !agent.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob)));\n const linkFor = (/** @type {PageFacts} */ page) => (hasTwin(page) ? abs(twinPath(page.path, base)) : page.canonical ?? page.url);\n const sections = groupPages(entries, base, byKey, (page) => agent.optional.some((glob) => matchGlob(sitePath(page.path, base), glob)));\n let llmsLinks = 0;\n let fullBytes = 0;\n let fullTruncated = false;\n const writeLlms = agent.llmsTxt && !own.llmsTxt;\n const writeFull = agent.llmsFullTxt && !own.llmsFullTxt;\n const writeAgent = agent.agentPage && !own.agentPage && !files["agent.md"];\n\n if (own.llmsTxt && agent.llmsTxt) notes.push("llms.txt: the site publishes its own; left as it is.");\n if (writeLlms) {\n const lines = [`# ${oneLine(siteName)}`, ""];\n\n if (summary) lines.push(`> ${summary}`, "");\n const intro = [\n agent.markdownTwins ? `Each page below is linked to its markdown version: the page\'s own text, with no scripts or layout.` : "",\n writeFull ? `Everything in one file: ${abs(`${base}/llms-full.txt`)}.` : "",\n writeAgent ? `How to use and cite this site: ${abs(`${base}/agent.md`)}.` : "",\n ].filter(Boolean);\n\n if (intro.length) lines.push(intro.join(" "), "");\n let remaining = MAX_LLMS_LINKS;\n let left = 0;\n\n for (const section of sections) {\n const shown = section.pages.slice(0, Math.max(0, remaining));\n\n left += section.pages.length - shown.length;\n remaining -= shown.length;\n if (!shown.length) continue;\n lines.push(`## ${section.title}`, "");\n for (const page of shown) lines.push(`- [${linkText(page.name || page.path)}](${linkFor(page)})${page.description ? `: ${oneLine(page.description)}` : ""}`);\n lines.push("");\n llmsLinks += shown.length;\n }\n if (left > 0) lines.push(`${left} more pages are listed in the sitemap: ${abs(`${base}/sitemap.xml`)}.`, "");\n files["llms.txt"] = `${lines.join("\\n").replace(/\\n+$/, "")}\\n`;\n types["llms.txt"] = "text/plain; charset=utf-8";\n }\n if (own.llmsFullTxt && agent.llmsFullTxt) notes.push("llms-full.txt: the site publishes its own; left as it is.");\n if (writeFull) {\n const encoder = new TextEncoder();\n const headText = `# ${oneLine(siteName)}\\n\\n${summary ? `> ${summary}\\n\\n` : ""}Every page of ${rootUrl}${agent.markdownTwins ? " as markdown" : ""}, one after another. The list of pages is ${abs(`${base}/llms.txt`)}.\\n`;\n const parts = [headText];\n let size = encoder.encode(headText).length;\n const ordered = sections.flatMap((section) => section.pages);\n let index = 0;\n\n for (; index < ordered.length; index += 1) {\n const page = /** @type {PageFacts} */ (ordered[index]);\n const body = `\\n---\\n\\nSource: ${page.canonical ?? page.url}\\n\\n${pageBody(page)}\\n`;\n const bytes = encoder.encode(body).length;\n\n if (size + bytes > agent.fullMaxBytes - 400) break;\n parts.push(body);\n size += bytes;\n }\n if (index < ordered.length) {\n fullTruncated = true;\n const left = ordered.length - index;\n\n parts.push(`\\n---\\n\\nThis file stops here: it reached its size limit of ${agent.fullMaxBytes.toLocaleString("en-US")} bytes. ${left} more ${left === 1 ? "page is" : "pages are"} listed in ${abs(`${base}/llms.txt`)}, each with its own markdown version.\\n`);\n }\n files["llms-full.txt"] = parts.join("");\n types["llms-full.txt"] = "text/plain; charset=utf-8";\n fullBytes = encoder.encode(files["llms-full.txt"]).length;\n }\n\n // \u2500\u2500 sitemap.xml \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sitemapPages = settings.sitemap.enabled ? counted.filter((page) => !settings.sitemap.exclude.some((glob) => matchGlob(sitePath(page.path, base), glob))) : [];\n const writeSitemap = settings.sitemap.enabled && !own.sitemap && Boolean(origin);\n\n if (settings.sitemap.enabled && own.sitemap) notes.push(`${own.sitemap}: the site writes its own sitemap; left as it is.`);\n if (settings.sitemap.enabled && !own.sitemap && !origin) notes.push("sitemap.xml needs full addresses: set `site` in astro.config to have one written.");\n if (writeSitemap) {\n const url = (/** @type {PageFacts} */ page) => {\n const lastmod = settings.sitemap.lastmod === "content" ? dateOnly(page.modified || page.published) : "";\n\n return ` <url><loc>${xml(page.canonical ?? page.url)}</loc>${lastmod ? `<lastmod>${lastmod}</lastmod>` : ""}</url>`;\n };\n const urlset = (/** @type {PageFacts[]} */ list) => [\'<?xml version="1.0" encoding="UTF-8"?>\', \'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\', ...list.map(url), "</urlset>", ""].join("\\n");\n\n if (sitemapPages.length <= MAX_SITEMAP_URLS) files["sitemap.xml"] = urlset(sitemapPages);\n else {\n const names = [];\n\n for (let start = 0, part = 1; start < sitemapPages.length; start += MAX_SITEMAP_URLS, part += 1) {\n const name = `sitemap-${part}.xml`;\n\n files[name] = urlset(sitemapPages.slice(start, start + MAX_SITEMAP_URLS));\n types[name] = "application/xml; charset=utf-8";\n names.push(name);\n }\n files["sitemap.xml"] = [\'<?xml version="1.0" encoding="UTF-8"?>\', \'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\', ...names.map((name) => ` <sitemap><loc>${xml(abs(`${base}/${name}`))}</loc></sitemap>`), "</sitemapindex>", ""].join("\\n");\n }\n types["sitemap.xml"] = "application/xml; charset=utf-8";\n }\n const sitemapUrl = own.sitemap ? abs(`${base}/${own.sitemap}`) : writeSitemap ? abs(`${base}/sitemap.xml`) : "";\n\n // \u2500\u2500 robots.txt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (settings.robots.enabled && own.robots) {\n notes.push(`robots.txt: the site writes its own (${own.robots}); left as it is.${Object.keys(settings.crawlers).length ? " The crawler choices in the visibility file are not applied: remove the site\'s own robots.txt to let the kit write them." : ""}`);\n }\n if (settings.robots.enabled && !own.robots) {\n files["robots.txt"] = robotsText({ settings, base, sitemap: origin ? sitemapUrl : "" });\n types["robots.txt"] = "text/plain; charset=utf-8";\n if (base) notes.push(`robots.txt is written for ${base}/, but crawlers only read the one at the root of the host; copy its rules there if this site is served under a sub-path.`);\n }\n\n // \u2500\u2500 agent.md \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (agent.agentPage && (own.agentPage || files["agent.md"] !== undefined)) notes.push("agent.md: the site has a page of its own at that address; left as it is.");\n if (writeAgent) {\n files["agent.md"] = agentText({ siteName, summary, rootUrl, base, abs, home, settings, has: { llms: writeLlms || own.llmsTxt, full: writeFull || own.llmsFullTxt, twins: twinOf.size > 0, robots: Boolean(files["robots.txt"] || own.robots), sitemap: sitemapUrl }, contactPage: byKey.get(pathKey(`${base}/contact/`)), example: twinned.find((page) => hasTwin(page) && pathKey(sitePath(page.path, base)) !== "/" && page.path.endsWith("/")) });\n types["agent.md"] = "text/markdown; charset=utf-8";\n }\n\n return {\n head,\n files,\n types,\n notes,\n counts: { pages: input.pages.length, listed: counted.length, twins: twinOf.size, structured, sitemap: writeSitemap ? sitemapPages.length : 0, llmsLinks, fullBytes, fullTruncated },\n };\n}\n\n/** The twin\'s body without its front matter: the page\'s heading first. */\nfunction pageBody(/** @type {PageFacts} */ page) {\n return page.hasH1 || !page.name ? page.markdown : `# ${page.name}\\n\\n${page.markdown}`;\n}\n\n/** A page\'s markdown twin: front matter, then its content. */\nexport function twinText(/** @type {PageFacts} */ page, /** @type {string} */ canonical) {\n const front = [`title: ${yaml(page.name || page.title)}`];\n\n if (page.description) front.push(`description: ${yaml(page.description)}`);\n front.push(`canonical: ${yaml(canonical)}`);\n if (page.lang) front.push(`language: ${yaml(page.lang)}`);\n if (page.published && Number.isFinite(Date.parse(page.published))) front.push(`published: ${yaml(page.published)}`);\n if (page.modified && Number.isFinite(Date.parse(page.modified))) front.push(`last_modified: ${yaml(page.modified)}`);\n return `---\\n${front.join("\\n")}\\n---\\n\\n${pageBody(page)}\\n`;\n}\n\n/**\n * Pages in llms.txt sections: "Pages" (the home page and pages one level\n * deep that have nothing under them), one section per first segment with\n * more than one page (its index page first, then newest first), and\n * "Optional" for what the settings mark secondary.\n *\n * @param {PageFacts[]} pages\n * @param {string} base\n * @param {Map<string, PageFacts>} byKey\n * @param {(page: PageFacts) => boolean} optional\n * @returns {{ title: string; pages: PageFacts[] }[]}\n */\nfunction groupPages(pages, base, byKey, optional) {\n /** @type {Map<string, PageFacts[]>} */\n const groups = new Map();\n const secondary = [];\n\n for (const page of pages) {\n if (optional(page)) {\n secondary.push(page);\n continue;\n }\n const segment = sitePath(page.path, base).split("/").filter(Boolean)[0] ?? "";\n\n (groups.get(segment) ?? groups.set(segment, []).get(segment) ?? []).push(page);\n }\n const main = /** @type {PageFacts[]} */ ([]);\n /** @type {{ title: string; pages: PageFacts[] }[]} */\n const sections = [];\n const newest = (/** @type {PageFacts} */ a, /** @type {PageFacts} */ b) => {\n const da = Date.parse(a.published) || 0;\n const db = Date.parse(b.published) || 0;\n\n return db - da || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);\n };\n\n for (const [segment, list] of [...groups.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n if (segment === "" || list.length === 1) {\n main.push(...list);\n continue;\n }\n const indexKey = pathKey(`${base}/${segment}/`);\n const index = list.filter((page) => pathKey(page.path) === indexKey);\n const rest = list.filter((page) => pathKey(page.path) !== indexKey).sort(newest);\n\n sections.push({ title: oneLine(byKey.get(indexKey)?.name || humanize(segment)), pages: [...index, ...rest] });\n }\n main.sort((a, b) => (pathKey(sitePath(a.path, base)) === "/" ? -1 : pathKey(sitePath(b.path, base)) === "/" ? 1 : a.path < b.path ? -1 : 1));\n return [...(main.length ? [{ title: "Pages", pages: main }] : []), ...sections, ...(secondary.length ? [{ title: "Optional", pages: secondary }] : [])];\n}\n\n/**\n * Which pages are articles, and of what type: the named collections (by\n * their address pattern) or address globs; "auto" means pages that say they\n * are articles (og:type "article").\n *\n * @param {"auto" | false | string[]} articles\n * @param {Record<string, string>} patterns\n * @returns {(path: string, page: PageFacts) => "Article" | "BlogPosting" | null}\n */\nfunction articleScopes(articles, patterns) {\n /** @type {(name: string) => "Article" | "BlogPosting"} */\n const typeFor = (name) => (/(^|\\/)(blog|posts?|journal)(\\/|$|\\*)/i.test(name) ? "BlogPosting" : "Article");\n\n if (articles === false) return () => null;\n if (articles === "auto") return (path, page) => (page.type === "article" ? typeFor(path.split("/").filter(Boolean)[0] ?? "") : null);\n const globs = articles.map((item) => (item.startsWith("/") ? { glob: item, type: typeFor(item) } : { glob: patternGlob(patterns[item] ?? `/${item}/{slug}/`), type: typeFor(item) }));\n\n return (path) => globs.find((entry) => matchGlob(path, entry.glob))?.type ?? null;\n}\n\n/** The logo\'s full address, when its file is really there. */\nfunction resolveLogo(/** @type {string} */ logo, /** @type {string} */ base, /** @type {string} */ origin, /** @type {((path: string) => boolean) | undefined} */ exists, /** @type {string[]} */ notes) {\n if (/^https?:\\/\\//i.test(logo)) return logo;\n if (!origin) return "";\n if (exists && !exists(logo)) {\n notes.push(`structuredData.organization.logo: ${logo} isn\'t among the site\'s files, so the logo was left out.`);\n return "";\n }\n return `${origin}${base}${logo}`;\n}\n\n/**\n * robots.txt from the settings: the site-wide rules for every crawler, then\n * one group per AI crawler the settings name. A crawler with a group of its\n * own ignores the `*` group (RFC 9309), so an allowed crawler\'s group\n * repeats the site-wide rules rather than lifting them.\n *\n * @param {{ settings: VisibilitySettings; base: string; sitemap: string }} input\n */\nexport function robotsText({ settings, base, sitemap }) {\n const rules = [...settings.robots.disallow.map((path) => `Disallow: ${base}${path}`), ...settings.robots.allow.map((path) => `Allow: ${base}${path}`)];\n const siteWide = rules.length ? rules : ["Allow: /"];\n const lines = ["User-agent: *", ...siteWide, ""];\n const known = AI_CRAWLERS.map((crawler) => crawler.token).filter((token) => Object.keys(settings.crawlers).some((key) => key.toLowerCase() === token.toLowerCase()));\n const others = Object.keys(settings.crawlers)\n .filter((key) => !aiCrawler(key))\n .sort((a, b) => a.localeCompare(b));\n const choiceOf = (/** @type {string} */ token) => settings.crawlers[Object.keys(settings.crawlers).find((key) => key.toLowerCase() === token.toLowerCase()) ?? token];\n\n for (const token of [...known, ...others]) {\n const crawler = aiCrawler(token);\n const choice = choiceOf(token);\n\n const note = crawler ? PURPOSE_NOTES[crawler.crawls ? crawler.purpose : "control"] : "";\n\n lines.push(`# ${crawler ? `${crawler.label} (${note})` : "Another crawler named in the visibility settings"}: ${choice === "block" ? "blocked" : "allowed"}`);\n lines.push(`User-agent: ${token}`, ...(choice === "block" ? ["Disallow: /"] : siteWide), "");\n }\n if (sitemap) lines.push(`Sitemap: ${sitemap}`, "");\n return `${lines.join("\\n").replace(/\\n+$/, "")}\\n`;\n}\n\n/**\n * The agent entry page: what the site is, where everything is, how to cite\n * it and how to reach its owner. Plain markdown, no scripts.\n *\n * @param {object} input\n * @param {string} input.siteName\n * @param {string} input.summary\n * @param {string} input.rootUrl\n * @param {string} input.base\n * @param {(path: string) => string} input.abs\n * @param {PageFacts | undefined} input.home\n * @param {VisibilitySettings} input.settings\n * @param {{ llms: boolean; full: boolean; twins: boolean; robots: boolean; sitemap: string }} input.has\n * @param {PageFacts | undefined} input.contactPage\n * @param {PageFacts | undefined} input.example A page to show the twin address with.\n */\nfunction agentText({ siteName, summary, rootUrl, base, abs, home, settings, has, contactPage, example }) {\n const lines = [`# ${oneLine(siteName)}: a guide for AI agents`, ""];\n\n if (summary) lines.push(`> ${summary}`, "");\n lines.push(`This page is for AI agents and assistants reading ${rootUrl}. It says where the site\'s content is in plain text and how to cite it.`, "", "## Where things are", "");\n if (has.llms) lines.push(`- Every page, with a one-line description: ${abs(`${base}/llms.txt`)}`);\n if (has.full) lines.push(`- The whole site in one file: ${abs(`${base}/llms-full.txt`)}`);\n if (has.twins) {\n const shown = example ? `: ${abs(example.path)} has ${abs(twinPath(example.path, base))}, and the home page has ${abs(`${base}/index.md`)}` : `; the home page\'s is ${abs(`${base}/index.md`)}`;\n\n lines.push(`- The markdown version of a page is at its address with \\`.md\\` in place of the last slash${shown}. Each page also names its own in \\`<link rel="alternate" type="text/markdown">\\`.`);\n }\n if (has.sitemap) lines.push(`- Every address, for crawlers: ${has.sitemap}`);\n for (const feed of home?.feeds ?? []) lines.push(`- ${feed.title ? `${oneLine(feed.title)} (feed)` : "Feed"}: ${feed.href}`);\n if (has.robots) lines.push(`- What crawlers may visit: ${abs(`${base}/robots.txt`)}`);\n lines.push(\n "",\n "## How to cite this site",\n "",\n `Name the page and ${oneLine(siteName)}, and link to the page\'s own address (the \\`canonical\\` line at the top of each markdown version), not to the markdown copy. Quote the words as they are; dates and figures are as stated on the page.`,\n "",\n );\n const contact = settings.agentReadable.contact || home?.emails[0] || "";\n const contactLines = [];\n\n if (contact) contactLines.push(/^https?:\\/\\//i.test(contact) ? `- ${contact}` : contact.includes("@") ? `- Email: ${contact}` : `- ${contact}`);\n if (contactPage && contactPage.url !== contact) contactLines.push(`- Contact page: ${contactPage.canonical ?? contactPage.url}`);\n if (contactLines.length) lines.push("## Contact", "", ...contactLines, "");\n lines.push("## About this file", "", "It is written from the site\'s published pages each time the site is built. It holds no scripts and changes only when the site does.", "");\n return lines.join("\\n").replace(/\\n+$/, "\\n");\n}\n', "visibility/structured.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// JSON-LD for the facts a site actually has, checked against Google\'s\n// current documentation (read 23 November 2026). Each builder returns null\n// rather than something incomplete:\n//\n// WebSite home page only; `name` and `url` are required, and the\n// url must be the root of the host \u2014 so nothing is written\n// for a site built under a sub-path.\n// developers.google.com/search/docs/appearance/site-names\n// Organization home page; no required properties \u2014 written with the\n// name and url, plus logo/sameAs/email/telephone when the\n// data file gives them (a logo only when its file exists).\n// \u2026/appearance/structured-data/organization\n// Article / no required properties; written only when the page\n// BlogPosting states a headline and a publication date\n// (article:published_time), with dateModified, author\n// (as a Person, by name) and image when the page states\n// them. The site\'s generic share picture is never used as\n// a post\'s image: Google asks for images of the article.\n// \u2026/appearance/structured-data/article\n// BreadcrumbList pages two or more levels deep; at least two ListItems,\n// each with position, name and an absolute item address.\n// \u2026/appearance/structured-data/breadcrumb\n//\n// A page that already carries a type of its own keeps it, and gets no second\n// one from the kit.\n\n/** @typedef {import("./page.js").PageFacts} PageFacts */\n/** @typedef {Record<string, unknown>} JsonLd */\n\nconst CONTEXT = "https://schema.org";\n\n/** @param {string} value */\nfunction isoDate(value) {\n if (!value) return "";\n const time = Date.parse(value);\n\n return Number.isFinite(time) ? value.trim() : "";\n}\n\n/**\n * @param {{ name: string; url: string; subPath: boolean }} site\n * @returns {JsonLd | null}\n */\nexport function websiteLd(site) {\n if (!site.name || !/^https?:\\/\\//.test(site.url) || site.subPath) return null;\n return { "@context": CONTEXT, "@type": "WebSite", name: site.name, url: site.url };\n}\n\n/**\n * @param {{ name: string; url: string; logo?: string; sameAs?: string[]; email?: string; telephone?: string }} org\n * @returns {JsonLd | null}\n */\nexport function organizationLd(org) {\n if (!org.name || !/^https?:\\/\\//.test(org.url)) return null;\n /** @type {JsonLd} */\n const out = { "@context": CONTEXT, "@type": "Organization", name: org.name, url: org.url };\n\n if (org.logo) out.logo = org.logo;\n if (org.sameAs && org.sameAs.length) out.sameAs = [...org.sameAs];\n if (org.email) out.email = org.email;\n if (org.telephone) out.telephone = org.telephone;\n return out;\n}\n\n/**\n * @param {PageFacts} page\n * @param {{ type: "Article" | "BlogPosting"; siteImage: string }} options\n * @returns {JsonLd | null}\n */\nexport function articleLd(page, options) {\n const headline = page.name.trim();\n const published = isoDate(page.published);\n\n if (!headline || !published) return null;\n /** @type {JsonLd} */\n const out = { "@context": CONTEXT, "@type": options.type, headline, datePublished: published };\n const modified = isoDate(page.modified);\n\n if (modified) out.dateModified = modified;\n if (page.author) out.author = [{ "@type": "Person", name: page.author }];\n if (page.image && page.image !== options.siteImage) out.image = [page.image];\n out.url = page.canonical ?? page.url;\n return out;\n}\n\n/**\n * @param {{ name: string; url: string }[]} trail From the top section down to the page itself.\n * @returns {JsonLd | null}\n */\nexport function breadcrumbLd(trail) {\n const items = trail.filter((step) => step.name && /^https?:\\/\\//.test(step.url));\n\n if (items.length < 2 || items.length !== trail.length) return null;\n return {\n "@context": CONTEXT,\n "@type": "BreadcrumbList",\n itemListElement: items.map((step, index) => ({ "@type": "ListItem", position: index + 1, name: step.name, item: step.url })),\n };\n}\n\n/**\n * Required properties, per Google\'s docs, of what this module writes \u2014 the\n * same rules the app\'s audit applies (packages/core/src/seo/rendered-checks.ts).\n *\n * @param {JsonLd} node\n * @returns {string[]} What is missing; empty when complete.\n */\nexport function missingRequired(node) {\n const type = node["@type"];\n\n if (type === "WebSite") return ["name", "url"].filter((key) => !node[key]);\n if (type === "BreadcrumbList") {\n const items = Array.isArray(node.itemListElement) ? /** @type {Record<string, unknown>[]} */ (node.itemListElement) : [];\n const missing = items.length < 2 ? ["at least two itemListElement entries"] : [];\n\n items.forEach((item, index) => {\n if (typeof item.position !== "number") missing.push(`position on item ${index + 1}`);\n if (!item.name) missing.push(`name on item ${index + 1}`);\n if (typeof item.item !== "string" || !/^https?:\\/\\//.test(item.item)) missing.push(`an absolute item on item ${index + 1}`);\n });\n return missing;\n }\n return [];\n}\n\n/** A JSON-LD block, safe inside HTML. */\nexport function jsonLdTag(/** @type {JsonLd} */ node) {\n return `<script type="application/ld+json" data-galley-jsonld>${JSON.stringify(node).replace(/</g, "\\\\u003c")}</script>`;\n}\n', "client/providers/frame-post.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// A real form post \u2014 the way Web-to-Lead and Account Engagement form\n// handlers expect browsers to send \u2014 either into a hidden frame (the visitor\n// stays on the page) or as a normal navigation (the visitor goes on to the\n// provider\'s return page). Neither provider sends CORS headers, so `fetch`\n// could not read their answer anyway; a frame at least tells us the post\n// completed (its `load` event), and when the provider sends the frame on to a\n// page of *this* site, the runtime can read where it landed.\n\nlet counter = 0;\n\n/**\n * @param {string} action\n * @param {{ [name: string]: string | string[] }} values\n * @param {{ navigate?: boolean; timeoutMs?: number }} [options]\n * @returns {Promise<{ loaded: boolean; location: string | null }>}\n * `location` is the frame\'s final address when it is on this site\'s origin.\n */\nexport function framePost(action, values, options = {}) {\n const form = document.createElement("form");\n\n form.method = "POST";\n form.action = action;\n form.acceptCharset = "UTF-8";\n form.hidden = true;\n for (const [name, value] of Object.entries(values)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n const input = document.createElement("input");\n\n input.type = "hidden";\n input.name = name;\n input.value = item;\n form.append(input);\n }\n }\n if (options.navigate) {\n document.body.append(form);\n form.submit();\n return Promise.resolve({ loaded: false, location: null });\n }\n const name = `galley-post-${Date.now().toString(36)}-${(counter += 1)}`;\n const frame = document.createElement("iframe");\n\n frame.name = name;\n frame.title = "";\n frame.hidden = true;\n frame.setAttribute("aria-hidden", "true");\n frame.tabIndex = -1;\n form.target = name;\n document.body.append(frame, form);\n\n return new Promise((resolve) => {\n let settled = false;\n const finish = (/** @type {boolean} */ loaded) => {\n if (settled) return;\n settled = true;\n let location = null;\n\n try {\n location = frame.contentWindow?.location.href ?? null;\n if (location === "about:blank") location = null;\n } catch {\n // Another origin: the browser doesn\'t say where the frame is.\n }\n resolve({ loaded, location });\n setTimeout(() => {\n frame.remove();\n form.remove();\n }, 1000);\n };\n\n frame.addEventListener("load", () => finish(true));\n setTimeout(() => finish(false), options.timeoutMs ?? 20000);\n form.submit();\n });\n}\n', "client/providers/galley.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Galley\'s own capture endpoint \u2014 the default destination. The request and\n// response are specified in docs/forms.md, "The capture endpoint":\n// POST <endpoint> content-type: application/json\n// { form, values, page: { url, title, referrer }, meta }\n// 200 { ok: true, id } \xB7 422 { ok: false, errors: { fieldId: message }, message? }\n// 429 { ok: false, message } + Retry-After \xB7 403 origin refused \xB7 404 form not taken here\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const own = destination.settings.endpoint;\n const root = /** @type {HTMLElement | null} */ (context.form.closest(".galley-form"));\n const configured = root?.querySelector("script[data-galley-form-config]")?.textContent;\n // Which address, in the order docs/forms.md gives: the destination\'s own\n // settings.endpoint; else the page\'s <html data-galley-endpoint> (how\n // Galley\'s preview sends test submissions to its own inbox, so it wins over\n // the site-wide address \u2014 a published page never carries it unless the site\n // sets it on purpose); else the site-wide capture address.\n const endpoint = (typeof own === "string" && own) || document.documentElement.dataset.galleyEndpoint || (configured ? JSON.parse(configured).endpoint : "") || "";\n\n if (!endpoint) return { ok: false, notConnected: true, detail: "No capture address is set for the Galley inbox." };\n let response;\n\n try {\n response = await fetch(endpoint, {\n method: "POST",\n headers: { "content-type": "application/json", accept: "application/json" },\n body: JSON.stringify({ form: context.formId, values, page: context.page, meta: context.meta }),\n });\n } catch (error) {\n return { ok: false, detail: `The capture endpoint couldn\'t be reached: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (response.status === 429) {\n // The capture server says how long to wait, and exposes the header to the page.\n const header = response.headers.get("retry-after") ?? "";\n const seconds = /^\\d+$/.test(header) ? Number(header) : header ? Math.max(1, Math.ceil((Date.parse(header) - Date.now()) / 1000)) : NaN;\n\n return { ok: false, retry: true, ...(Number.isFinite(seconds) && seconds > 0 ? { retryAfter: seconds } : {}), detail: "The capture endpoint asked to slow down (429)." };\n }\n /** @type {any} */\n const answer = await response.json().catch(() => null);\n\n if (response.ok && answer?.ok === true) return { ok: true, detail: `Stored as ${answer.id ?? "a new submission"}.` };\n if (response.status === 404) return { ok: false, notConnected: true, detail: `The capture endpoint doesn\'t take this form (404)${answer?.message ? `: ${answer.message}` : ""}.` };\n if (response.status === 403) return { ok: false, detail: "The capture endpoint refused this page\'s origin (403). Check the site\'s addresses in the app\'s capture settings." };\n return {\n ok: false,\n errors: answer && typeof answer.errors === "object" && answer.errors ? answer.errors : {},\n ...(typeof answer?.message === "string" && answer.message ? { message: answer.message } : {}),\n detail: `The capture endpoint answered ${response.status}${answer?.message ? `: ${answer.message}` : ""}.`,\n };\n}\n', "client/providers/hubspot.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// HubSpot: the Forms API\'s unauthenticated, CORS-enabled "submit data to a\n// form" endpoint (legacy v3, still supported):\n// POST https://api.hsforms.com/submissions/v3/integration/submit/{portalId}/{formGuid}\n// (api-{region}.hsforms.com for accounts in another data region, e.g. eu1)\n// { submittedAt, fields: [{ objectTypeId, name, value }],\n// context: { hutk, pageUri, pageName }, legalConsentOptions? }\n// The form must exist in HubSpot with the same field names; HubSpot runs its\n// own validation and answers 400 with `errors: [{ message, errorType }]`.\n//\n// Mapping conventions (docs/forms.md):\n// "email" a contact property (objectTypeId 0-1)\n// "0-2/name" another object\'s property (here: company name)\n// "consent:process" a consent field \u2192 legalConsentOptions.consent.consentToProcess\n// "consent:communication:<subscriptionTypeId>"\n// a consent field \u2192 one communications subscription\n// An unmapped consent field counts as consent to process.\n\nimport { plainText } from "../../shared/markdown.js";\n\n/** @param {string} name */\nfunction cookie(name) {\n const match = document.cookie.split(/;\\s*/).find((part) => part.startsWith(`${name}=`));\n\n return match ? decodeURIComponent(match.slice(name.length + 1)) : "";\n}\n\n/** @param {string} region */\nexport function hubspotHost(region) {\n return !region || region === "na1" ? "https://api.hsforms.com" : `https://api-${region}.hsforms.com`;\n}\n\n/** @type {import("../types").Submitter} */\nexport async function submit(_values, destination, context) {\n const settings = destination.settings;\n const portalId = String(settings.portalId ?? "");\n const formId = String(settings.formId ?? "");\n\n if (!portalId || !formId) return { ok: false, notConnected: true, detail: "HubSpot needs settings.portalId and settings.formId." };\n /** @type {{ objectTypeId: string; name: string; value: string }[]} */\n const fields = [];\n /** @type {{ consentToProcess: boolean; text: string; communications: { value: boolean; subscriptionTypeId: number; text: string }[] } | null} */\n let consent = null;\n const consentBlock = () => (consent ??= { consentToProcess: false, text: "", communications: [] });\n\n for (const item of context.items) {\n const value = Array.isArray(item.value) ? item.value.join(";") : item.value;\n\n if (item.field.type === "consent") {\n const text = plainText(item.field.text ?? item.field.label ?? "");\n const agreed = value === "true";\n const communication = /^consent:communication:(\\d+)$/.exec(item.name);\n\n if (communication) consentBlock().communications.push({ value: agreed, subscriptionTypeId: Number(communication[1]), text });\n else if (item.name === "consent:process" || !destination.mapping?.[item.field.id]) Object.assign(consentBlock(), { consentToProcess: agreed, text });\n else fields.push({ objectTypeId: "0-1", name: item.name, value });\n continue;\n }\n const [, objectTypeId = "0-1", name = item.name] = /^(\\d+-\\d+)\\/(.+)$/.exec(item.name) ?? [];\n\n fields.push({ objectTypeId, name, value });\n }\n for (const [name, value] of Object.entries(destination.constants ?? {})) {\n const [, objectTypeId = "0-1", property = name] = /^(\\d+-\\d+)\\/(.+)$/.exec(name) ?? [];\n\n fields.push({ objectTypeId, name: property, value });\n }\n const hutk = cookie("hubspotutk");\n /** @type {Record<string, unknown>} */\n const body = {\n submittedAt: String(Date.now()),\n fields,\n context: { ...(hutk ? { hutk } : {}), pageUri: context.page.url, pageName: context.page.title },\n };\n\n if (consent) body.legalConsentOptions = { consent };\n const region = typeof settings.region === "string" ? settings.region : "";\n let response;\n\n try {\n response = await fetch(`${hubspotHost(region)}/submissions/v3/integration/submit/${encodeURIComponent(portalId)}/${encodeURIComponent(formId)}`, {\n method: "POST",\n headers: { "content-type": "application/json" },\n body: JSON.stringify(body),\n });\n } catch (error) {\n return { ok: false, detail: `HubSpot couldn\'t be reached: ${error instanceof Error ? error.message : String(error)}` };\n }\n /** @type {any} */\n const answer = await response.json().catch(() => ({}));\n\n if (response.ok) return { ok: true, redirect: answer.redirectUri, detail: "HubSpot accepted the submission." };\n if (response.status === 429) return { ok: false, retry: true, detail: "HubSpot asked to slow down (429)." };\n /** @type {Record<string, string>} */\n const errors = {};\n\n for (const error of Array.isArray(answer.errors) ? answer.errors : []) {\n // e.g. "Error in \'fields.email\'. Invalid email address"\n const field = /fields\\.([\\w-]+)/.exec(String(error.message ?? ""))?.[1];\n const item = field ? context.items.find((entry) => entry.name === field || entry.name.endsWith(`/${field}`)) : undefined;\n\n if (item) errors[item.field.id] = error.errorType === "INVALID_EMAIL" ? context.messages.email ?? String(error.message) : String(error.message).replace(/^Error in \'[^\']*\'\\.\\s*/, "");\n }\n return {\n ok: false,\n errors,\n detail: `HubSpot refused the submission (${response.status}): ${(Array.isArray(answer.errors) ? answer.errors : []).map((/** @type {any} */ error) => error.errorType ?? error.message).join(", ") || answer.message || "no reason given"}`,\n };\n}\n', "client/providers/mailto.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The last resort: opens the visitor\'s own mail program with the answers in a\n// new message. Nothing is stored and the page can\'t know whether the message\n// was sent \u2014 only that the mail program was asked to open.\n\n/** @type {import("../types").Submitter} */\nexport function submit(_values, destination, context) {\n const to = typeof destination.settings.to === "string" ? destination.settings.to : "";\n\n if (!to) return { ok: false, notConnected: true, detail: "The mail destination needs settings.to." };\n const subject = typeof destination.settings.subject === "string" ? destination.settings.subject : "";\n const lines = context.items.map(({ field, value }) => `${field.label ?? field.id}: ${Array.isArray(value) ? value.join(", ") : value}`);\n\n for (const [name, value] of Object.entries(destination.constants ?? {})) lines.push(`${name}: ${value}`);\n const query = [subject ? `subject=${encodeURIComponent(subject)}` : "", `body=${encodeURIComponent(lines.join("\\n"))}`].filter(Boolean).join("&");\n\n location.href = `mailto:${to}?${query}`;\n return { ok: true, detail: "Asked the mail program to open." };\n}\n', "client/providers/marketo.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Marketo, through Marketo\'s own Forms 2.0 library and a hidden Marketo form,\n// as Adobe documents it: load {host}/js/forms2/js/forms2.min.js, call\n// MktoForms2.loadForm(host, munchkinId, formId), put the answers on the\n// Marketo form (setValues for fields the form has, addHiddenFields for the\n// rest \u2014 the only way values reach a known-visitor form), then submit() with\n// an onSuccess that returns false so the page stays put.\n//\n// Posting straight to Marketo\'s endpoint is not a supported API; going\n// through the library keeps Marketo\'s own validation, its anti-spam checks\n// and the Munchkin cookie association (the library sends _mkto_trk itself).\n// When Marketo refuses a value, its message is shown on our field.\n\n/** @type {Map<string, Promise<void>>} */\nconst libraries = new Map();\n/** @type {Map<string, Promise<any>>} */\nconst loaded = new Map();\n\n/** @param {string} host */\nfunction library(host) {\n if (window.MktoForms2) return Promise.resolve();\n const known = libraries.get(host);\n\n if (known) return known;\n const promise = new Promise((resolve, reject) => {\n const script = document.createElement("script");\n\n script.src = `${host}/js/forms2/js/forms2.min.js`;\n script.async = true;\n script.onload = () => (window.MktoForms2 ? resolve(undefined) : reject(new Error("Marketo\'s forms library loaded but did not start.")));\n script.onerror = () => reject(new Error(`Marketo\'s forms library couldn\'t load from ${host}.`));\n document.head.append(script);\n });\n\n libraries.set(host, /** @type {Promise<void>} */ (promise));\n return /** @type {Promise<void>} */ (promise);\n}\n\n/** @param {string} host @param {string} munchkinId @param {string} formId */\nfunction marketoForm(host, munchkinId, formId) {\n const key = `${host}|${munchkinId}|${formId}`;\n const known = loaded.get(key);\n\n if (known) return known;\n const promise = library(host).then(\n () =>\n new Promise((resolve, reject) => {\n let element = document.getElementById(`mktoForm_${formId}`);\n\n if (!element) {\n element = document.createElement("form");\n element.id = `mktoForm_${formId}`;\n element.hidden = true;\n element.setAttribute("aria-hidden", "true");\n element.style.display = "none";\n document.body.append(element);\n }\n const timer = setTimeout(() => reject(new Error("Marketo\'s form didn\'t load in time.")), 15000);\n\n window.MktoForms2.loadForm(host, munchkinId, Number(formId), (/** @type {any} */ form) => {\n clearTimeout(timer);\n resolve(form);\n });\n }),\n );\n\n loaded.set(key, promise);\n promise.catch(() => loaded.delete(key));\n return promise;\n}\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination) {\n const settings = destination.settings;\n const host = String(settings.host ?? "").replace(/\\/+$/, "");\n const munchkinId = String(settings.munchkinId ?? "");\n const formId = String(settings.formId ?? "");\n\n if (!host || !munchkinId || !formId) return { ok: false, notConnected: true, detail: "Marketo needs settings.host, settings.munchkinId and settings.formId." };\n let form;\n\n try {\n form = await marketoForm(host, munchkinId, formId);\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n /** @type {Record<string, string>} */\n const flat = {};\n\n for (const [name, value] of Object.entries(values)) flat[name] = Array.isArray(value) ? value.join(";") : value;\n const onForm = Object.keys(form.getValues?.() ?? {});\n /** @type {Record<string, string>} */\n const present = {};\n /** @type {Record<string, string>} */\n const extra = {};\n\n for (const [name, value] of Object.entries(flat)) (onForm.includes(name) ? present : extra)[name] = value;\n form.setValues(present);\n if (Object.keys(extra).length > 0) form.addHiddenFields(extra);\n\n // Marketo\'s callbacks can\'t be removed, so each form gets them once and\n // they answer whichever submission is in flight.\n if (!form.__galley) {\n form.__galley = { end: null };\n form.onValidate((/** @type {boolean} */ valid) => {\n if (valid) return;\n // Marketo marks the refused field and writes its message into its own DOM.\n const element = form.getFormElem?.()?.[0];\n const invalid = element?.querySelector(".mktoInvalid");\n const message = element?.querySelector(".mktoErrorMsg")?.textContent?.trim() || "Marketo refused this answer.";\n const name = invalid?.getAttribute("name");\n\n form.__galley.end?.({ ok: false, errors: name ? { [name]: message } : {}, detail: `Marketo refused the submission: ${message}` });\n });\n form.onSuccess((/** @type {unknown} */ _values, /** @type {string} */ followUpUrl) => {\n form.__galley.end?.({ ok: true, redirect: followUpUrl || undefined, detail: "Marketo accepted the submission." });\n return false;\n });\n }\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => end({ ok: false, detail: "Marketo didn\'t confirm the submission in time." }), 20000);\n const end = (/** @type {import("../types").SubmitResult} */ result) => {\n clearTimeout(timer);\n form.__galley.end = null;\n resolve(result);\n };\n\n form.__galley.end = end;\n form.submit();\n });\n}\n', "client/providers/pardot.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Account Engagement (Pardot) form handler: a form post to the handler\'s\n// address with fields under the handler\'s external field names (`mapping`).\n// Handlers don\'t accept fetch/XHR posts (no CORS), so the post goes through a\n// hidden frame \u2014 or, with `mode: "navigate"`, as a normal navigation, which\n// is the better choice when visitor tracking matters (the handler\'s cookie is\n// set in a top-level page, not a third-party frame).\n//\n// Telling success from failure: point the handler\'s Success Location and\n// Error Location at two pages on this site and copy them into\n// `successLocation` / `errorLocation`. The frame then lands on one of them\n// (same origin, so the page can read where) and the runtime knows which.\n// Without them, a completed post counts as success.\n\nimport { framePost } from "./frame-post.js";\n\n/** @param {string} a @param {string} b */\nconst samePage = (a, b) => {\n try {\n const x = new URL(a);\n const y = new URL(b, location.href);\n\n return x.origin === y.origin && x.pathname.replace(/\\/+$/, "") === y.pathname.replace(/\\/+$/, "");\n } catch {\n return false;\n }\n};\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination) {\n const settings = destination.settings;\n const handler = typeof settings.handlerUrl === "string" ? settings.handlerUrl : "";\n\n if (!handler) return { ok: false, notConnected: true, detail: "Account Engagement needs settings.handlerUrl." };\n const navigate = settings.mode === "navigate";\n const result = await framePost(handler, values, { navigate });\n\n if (navigate) return { ok: true };\n if (!result.loaded) return { ok: false, detail: "The form handler didn\'t answer in time." };\n const errorLocation = typeof settings.errorLocation === "string" ? settings.errorLocation : "";\n const successLocation = typeof settings.successLocation === "string" ? settings.successLocation : "";\n\n if (result.location && errorLocation && samePage(result.location, errorLocation)) {\n const message = new URL(result.location).searchParams.get("errorMessage");\n\n return { ok: false, detail: message ? `The form handler refused the submission: ${message}` : "The form handler sent the visitor to its error location." };\n }\n if (result.location && successLocation && !samePage(result.location, successLocation) && errorLocation) {\n return { ok: false, detail: `The form handler finished on ${result.location}, which is neither its success nor its error location.` };\n }\n return { ok: true, detail: result.location ? "The form handler reached its success location." : "Posted to the form handler; it does not tell the page more." };\n}\n', "client/providers/salesforce.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Salesforce Web-to-Lead. A form post to the Web-to-Lead servlet with the\n// org\'s `oid`, standard lead fields by their Salesforce names (first_name,\n// last_name, email, company, phone, lead_source, \u2026) and custom fields by\n// their field ids (00N\u2026), mapped in the destination\'s `mapping`. Fixed\n// values (lead_source, Campaign_ID, recordType, debug, debugEmail) go in\n// `constants`.\n//\n// What the browser cannot know: Salesforce answers with a redirect to\n// `retURL` and no CORS headers, so the page never learns whether the lead was\n// accepted (duplicate rules, bad picklist values, the daily limit all look\n// the same). A completed post counts as success; docs/forms.md says so.\n\nimport { framePost } from "./frame-post.js";\n\nexport const SERVLET = "https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const settings = destination.settings;\n const orgId = typeof settings.orgId === "string" ? settings.orgId : "";\n\n if (!orgId) return { ok: false, notConnected: true, detail: "Salesforce needs settings.orgId." };\n /** @type {{ [name: string]: string | string[] }} */\n const fields = {};\n\n for (const [name, value] of Object.entries(values)) {\n // Checkboxes: Salesforce reads "1" as ticked; an unticked box is left out.\n if (value === "true" || value === "false") {\n const field = context.items.find((item) => item.name === name)?.field;\n\n if (field && (field.type === "checkbox" || field.type === "consent")) {\n if (value === "true") fields[name] = "1";\n continue;\n }\n }\n fields[name] = value;\n }\n const navigate = settings.mode === "navigate";\n const returnUrl = typeof settings.returnUrl === "string" ? settings.returnUrl : "";\n // In a frame, no retURL means Salesforce answers with an empty page \u2014 the\n // lightest possible end to the post. (A page of this site loaded in the\n // frame skips its third-party scripts: see scripts/runtime.js.)\n const target = navigate ? returnUrl || location.href : returnUrl;\n const result = await framePost(SERVLET, { oid: orgId, ...(target ? { retURL: target } : {}), ...fields }, { navigate });\n\n if (navigate) return { ok: true, detail: "Sent to Salesforce; the visitor is on their way to the return address." };\n return result.loaded ? { ok: true, detail: "Posted to Web-to-Lead. Salesforce does not tell the page whether it created the lead." } : { ok: false, detail: "Web-to-Lead didn\'t answer in time." };\n}\n', "client/providers/webhook.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// Any address that accepts a POST: an automation tool, a serverless\n// function, the site owner\'s own service. `format: "json"` (default) sends\n// { form, values, page, at }; `format: "form"` sends the values\n// form-encoded. The receiving server must allow this site\'s origin (CORS):\n// a JSON post is preceded by an OPTIONS preflight; a form-encoded one is not,\n// but its answer is still only readable with Access-Control-Allow-Origin.\n// An answer of { errors: { name: message } } puts messages on the fields.\n\n/** @type {import("../types").Submitter} */\nexport async function submit(values, destination, context) {\n const url = typeof destination.settings.url === "string" ? destination.settings.url : "";\n\n if (!url) return { ok: false, notConnected: true, detail: "The webhook needs settings.url." };\n const form = destination.settings.format === "form";\n let body;\n\n if (form) {\n const params = new URLSearchParams();\n\n for (const [name, value] of Object.entries(values)) for (const item of Array.isArray(value) ? value : [value]) params.append(name, item);\n body = params;\n } else {\n body = JSON.stringify({ form: context.formId, values, page: context.page, at: new Date().toISOString() });\n }\n let response;\n\n try {\n response = await fetch(url, { method: "POST", body, ...(form ? {} : { headers: { "content-type": "application/json" } }) });\n } catch (error) {\n return { ok: false, detail: `The webhook couldn\'t be reached (or doesn\'t allow this site\'s origin): ${error instanceof Error ? error.message : String(error)}` };\n }\n if (response.status === 429) return { ok: false, retry: true, detail: "The webhook asked to slow down (429)." };\n if (response.ok) return { ok: true, detail: `The webhook answered ${response.status}.` };\n /** @type {any} */\n const answer = await response.json().catch(() => null);\n\n return { ok: false, errors: answer?.errors && typeof answer.errors === "object" ? answer.errors : {}, detail: `The webhook answered ${response.status}.` };\n}\n', "runtime/site-config.js": '// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don\'t edit: run the script again to update.\n// @ts-check\n// The site\'s kit settings, read from files (a vendored kit has no\n// integration to pass them): src/galley/settings.json for the forms,\n// src/data/scripts.json for the managed scripts, src/content/forms/ for the\n// site-wide UTM memory, and the email-link dialog\'s settings.\nimport settings from "../settings.json";\nimport { resolveMailto } from "../mailto/config.js";\nimport { describeIssues, scriptsSchema } from "../schema.js";\nimport { resolveEntries } from "../scripts/plan.js";\n\n/** @typedef {import("../kit").ScriptsConfig} ScriptsConfig */\n\nconst scriptFiles = import.meta.glob("/src/data/scripts.json", { eager: true, import: "default" });\nconst formFiles = import.meta.glob("/src/content/forms/*.json", { eager: true, import: "default" });\n\nexport const scriptsFile = "src/data/scripts.json";\n\n/** @returns {ScriptsConfig | null} */\nfunction readScripts() {\n const raw = scriptFiles["/src/data/scripts.json"];\n\n if (raw === undefined) return null;\n const parsed = scriptsSchema.safeParse(raw);\n\n if (!parsed.success) throw new Error(`src/data/scripts.json has problems:\\n${describeIssues(parsed.error).map((line) => ` - ${line}`).join("\\n")}`);\n const config = /** @type {ScriptsConfig} */ (parsed.data);\n\n resolveEntries(config);\n return config;\n}\n\nexport const scripts = readScripts();\n\nconst forms = /** @type {Record<string, unknown>} */ (settings.forms ?? {});\n\nexport const options = {\n collection: typeof forms.collection === "string" ? forms.collection : "forms",\n endpoint: typeof forms.endpoint === "string" ? forms.endpoint : "",\n allowFormScripts: forms.allowFormScripts === true,\n messages: /** @type {Record<string, string>} */ (forms.messages ?? {}),\n freeEmailDomains: /** @type {string[]} */ (forms.freeEmailDomains ?? []),\n};\n\n/** The email-link dialog: on unless settings.json says "mailto": false. */\nexport const mailto = resolveMailto(/** @type {any} */ (settings).mailto);\n\nexport const utm = Object.values(formFiles).some(\n (form) => Array.isArray(/** @type {any} */ (form)?.fields) && /** @type {any} */ (form).fields.some((/** @type {any} */ field) => field?.autofill?.from === "utm"),\n);\n', "integration.js": `// Vendored from @galley/astro 0.1.1 by scripts/vendor.mjs. Don't edit: run the script again to update.
|
|
163238
163566
|
// @ts-check
|
|
163239
163567
|
// The site kit's build step for a vendored kit: the agent-readable version of
|
|
163240
163568
|
// the site (markdown twins, llms.txt, llms-full.txt, agent.md, structured
|
|
@@ -165164,14 +165492,14 @@ function createApp(services2, options2) {
|
|
|
165164
165492
|
limiter: new LoginLimiter(),
|
|
165165
165493
|
streams: options2.streams ?? createStreamRegistry()
|
|
165166
165494
|
};
|
|
165167
|
-
const allowedHosts = options2.allowedHosts ? new Set([...options2.allowedHosts, ...loopbackHostnames()].map(
|
|
165495
|
+
const allowedHosts = options2.allowedHosts ? new Set([...options2.allowedHosts, ...loopbackHostnames()].map(normalizeHostname2)) : null;
|
|
165168
165496
|
const csp = uiContentSecurityPolicy(options2.frameSources);
|
|
165169
165497
|
const app = new Hono3();
|
|
165170
165498
|
app.onError((error63, c) => errorResponse(c, error63, log2));
|
|
165171
165499
|
app.notFound((c) => c.json(errorBody("not-found", "There's nothing at this address."), 404));
|
|
165172
165500
|
app.use("*", async (c, next) => {
|
|
165173
165501
|
const url2 = new URL(c.req.url);
|
|
165174
|
-
if (allowedHosts && !allowedHosts.has(
|
|
165502
|
+
if (allowedHosts && !allowedHosts.has(normalizeHostname2(url2.hostname))) {
|
|
165175
165503
|
return c.json(errorBody("forbidden", "This address isn't one this app answers to."), 403);
|
|
165176
165504
|
}
|
|
165177
165505
|
await next();
|
|
@@ -165712,7 +166040,7 @@ var readBodyDirect = (request) => {
|
|
|
165712
166040
|
request[bodyBufferKey] = buffered;
|
|
165713
166041
|
return Promise.resolve(buffered);
|
|
165714
166042
|
}
|
|
165715
|
-
const promise3 = new Promise((
|
|
166043
|
+
const promise3 = new Promise((resolve25, reject) => {
|
|
165716
166044
|
const chunks = [];
|
|
165717
166045
|
let settled = false;
|
|
165718
166046
|
const finish3 = (callback2) => {
|
|
@@ -165730,7 +166058,7 @@ var readBodyDirect = (request) => {
|
|
|
165730
166058
|
else if (recovered === void 0) reject(error63 ?? normalizeAbortError(request, incoming));
|
|
165731
166059
|
else {
|
|
165732
166060
|
request[bodyBufferKey] = recovered;
|
|
165733
|
-
|
|
166061
|
+
resolve25(recovered);
|
|
165734
166062
|
}
|
|
165735
166063
|
});
|
|
165736
166064
|
return true;
|
|
@@ -165742,7 +166070,7 @@ var readBodyDirect = (request) => {
|
|
|
165742
166070
|
finish3(() => {
|
|
165743
166071
|
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
|
165744
166072
|
request[bodyBufferKey] = buffer;
|
|
165745
|
-
|
|
166073
|
+
resolve25(buffer);
|
|
165746
166074
|
});
|
|
165747
166075
|
};
|
|
165748
166076
|
const onError = (error63) => {
|
|
@@ -166305,7 +166633,7 @@ var responseViaResponseObject = async (res, outgoing, options2 = {}) => {
|
|
|
166305
166633
|
const chunk2 = await readWithoutBlocking(currentReadPromise);
|
|
166306
166634
|
if (!chunk2) {
|
|
166307
166635
|
if (i === 1) {
|
|
166308
|
-
await new Promise((
|
|
166636
|
+
await new Promise((resolve25) => setTimeout(resolve25));
|
|
166309
166637
|
maxReadCount = 3;
|
|
166310
166638
|
continue;
|
|
166311
166639
|
}
|
|
@@ -166497,9 +166825,9 @@ var setupWebSocket = (options2) => {
|
|
|
166497
166825
|
}
|
|
166498
166826
|
};
|
|
166499
166827
|
const waitForWebSocket = (request, connectionSymbol) => {
|
|
166500
|
-
return new Promise((
|
|
166828
|
+
return new Promise((resolve25, reject) => {
|
|
166501
166829
|
waiterMap.set(request, {
|
|
166502
|
-
resolve:
|
|
166830
|
+
resolve: resolve25,
|
|
166503
166831
|
reject,
|
|
166504
166832
|
connectionSymbol
|
|
166505
166833
|
});
|
|
@@ -166938,7 +167266,7 @@ async function startServer(options2 = {}) {
|
|
|
166938
167266
|
version: VERSION,
|
|
166939
167267
|
...options2.log ? { log: options2.log } : {}
|
|
166940
167268
|
}) : null;
|
|
166941
|
-
const frameHost = publicHost ? formatHost2(
|
|
167269
|
+
const frameHost = publicHost ? formatHost2(normalizeHostname2(publicHost)) : null;
|
|
166942
167270
|
const app = createApp(services2, {
|
|
166943
167271
|
mode: config2.mode,
|
|
166944
167272
|
token: config2.token,
|
|
@@ -167048,7 +167376,132 @@ function plural8(count7, one, many = `${one}s`) {
|
|
|
167048
167376
|
init_brand();
|
|
167049
167377
|
init_deploy();
|
|
167050
167378
|
import { createInterface as createInterface2 } from "node:readline";
|
|
167379
|
+
import { resolve as resolve16 } from "node:path";
|
|
167380
|
+
|
|
167381
|
+
// src/commands/domain.ts
|
|
167382
|
+
init_brand();
|
|
167383
|
+
init_deploy();
|
|
167051
167384
|
import { resolve as resolve15 } from "node:path";
|
|
167385
|
+
var DOMAIN_HELP = `Usage: ${PRODUCT.slug} domain [path] [hostname] [options]
|
|
167386
|
+
|
|
167387
|
+
Use your own domain for the site in [path] (default: this folder), which must
|
|
167388
|
+
already be online. With a hostname: show what will change, attach it on yes,
|
|
167389
|
+
and wait until it answers over HTTPS \u2014 it then becomes the site's live
|
|
167390
|
+
address. Without one: show the address in use.
|
|
167391
|
+
|
|
167392
|
+
Options
|
|
167393
|
+
--check Look again at an address that isn't answering yet
|
|
167394
|
+
--remove Stop using the address (it is detached only if ${PRODUCT.name} attached it)
|
|
167395
|
+
-y, --yes Don't ask before attaching or removing
|
|
167396
|
+
--json Print the result as JSON
|
|
167397
|
+
-h, --help Show this help
|
|
167398
|
+
|
|
167399
|
+
Examples
|
|
167400
|
+
${PRODUCT.slug} domain www.example.com
|
|
167401
|
+
${PRODUCT.slug} domain ./site --remove --yes`;
|
|
167402
|
+
function follow(events, deploy, job, onStep) {
|
|
167403
|
+
return new Promise((done) => {
|
|
167404
|
+
let last = "";
|
|
167405
|
+
const settle2 = (next) => {
|
|
167406
|
+
if (next.detail && next.detail !== last) {
|
|
167407
|
+
last = next.detail;
|
|
167408
|
+
if (next.state === "running") onStep(next.detail);
|
|
167409
|
+
}
|
|
167410
|
+
if (next.state !== "running") {
|
|
167411
|
+
unsubscribe();
|
|
167412
|
+
done(next);
|
|
167413
|
+
}
|
|
167414
|
+
};
|
|
167415
|
+
const unsubscribe = events.subscribe((event) => {
|
|
167416
|
+
if (event.type === "job" && event.job.id === job.id) settle2(event.job);
|
|
167417
|
+
});
|
|
167418
|
+
settle2(deploy.job(job.id) ?? job);
|
|
167419
|
+
});
|
|
167420
|
+
}
|
|
167421
|
+
async function useDomain(io, deploy, events, site, hostname3, options2) {
|
|
167422
|
+
const plan2 = await deploy.planDomain(site, hostname3);
|
|
167423
|
+
if (!options2.json) {
|
|
167424
|
+
io.err(plan2.summary);
|
|
167425
|
+
for (const record3 of plan2.records ?? []) io.err(` ${record3.type} ${record3.name} ${record3.value}`);
|
|
167426
|
+
if (plan2.helpUrl) io.err(` ${plan2.helpUrl}`);
|
|
167427
|
+
}
|
|
167428
|
+
if (!plan2.canAttach && plan2.status !== "already") {
|
|
167429
|
+
if (options2.json) io.out(JSON.stringify({ ok: false, plan: plan2 }));
|
|
167430
|
+
return 1;
|
|
167431
|
+
}
|
|
167432
|
+
if (!options2.yes) {
|
|
167433
|
+
if (!io.prompt) throw new UsageError(`Nothing was changed. Run it again with --yes to use ${plan2.hostname}.`);
|
|
167434
|
+
const answer2 = await io.prompt(`Use ${plan2.hostname}? [y/N] `);
|
|
167435
|
+
if (!/^y(es)?$/i.test(answer2)) {
|
|
167436
|
+
io.err("Nothing was changed.");
|
|
167437
|
+
return 1;
|
|
167438
|
+
}
|
|
167439
|
+
}
|
|
167440
|
+
const job = await follow(events, deploy, await deploy.attachDomain(site, plan2.hostname), (detail) => !options2.json && io.err(detail));
|
|
167441
|
+
return report2(io, deploy, site, job, options2.json);
|
|
167442
|
+
}
|
|
167443
|
+
async function report2(io, deploy, site, job, json10) {
|
|
167444
|
+
const status2 = await deploy.status(site);
|
|
167445
|
+
if (json10) io.out(JSON.stringify({ ok: job.state === "done", job, address: status2.config?.productionUrl ?? null, records: status2.domainRecords ?? [] }));
|
|
167446
|
+
else if (job.state === "done" && job.url) io.out(`\u2713 ${job.url} answers \u2014 it's the site's live address now.`);
|
|
167447
|
+
else if (job.state === "done") {
|
|
167448
|
+
io.out(`! ${job.detail}`);
|
|
167449
|
+
for (const record3 of status2.domainRecords ?? []) io.out(` ${record3.type} ${record3.name} ${record3.value}`);
|
|
167450
|
+
io.out(` Then run \`${PRODUCT.slug} domain --check\`.`);
|
|
167451
|
+
} else io.err(`! ${job.detail}`);
|
|
167452
|
+
return job.state === "done" && job.url ? 0 : 1;
|
|
167453
|
+
}
|
|
167454
|
+
async function domainCommand(argv, io) {
|
|
167455
|
+
const { values, positionals } = parse9("domain", argv, { check: { type: "boolean" }, remove: { type: "boolean" }, yes: { type: "boolean", short: "y" }, json: { type: "boolean" } }, 2);
|
|
167456
|
+
if (values.help) {
|
|
167457
|
+
io.out(DOMAIN_HELP);
|
|
167458
|
+
return 0;
|
|
167459
|
+
}
|
|
167460
|
+
const lone = positionals.length === 1 && /\./.test(positionals[0]) && !/[/\\]/.test(positionals[0]) && !positionals[0].startsWith(".");
|
|
167461
|
+
const path6 = lone ? "." : positionals[0] ?? ".";
|
|
167462
|
+
const hostname3 = lone ? positionals[0] : positionals[1];
|
|
167463
|
+
if (values.check && values.remove) throw new UsageError("Use either --check or --remove, not both.");
|
|
167464
|
+
if (hostname3 && (values.check || values.remove)) throw new UsageError("Give a hostname to use it, or --check / --remove for the one in use \u2014 not both.");
|
|
167465
|
+
const home = defaultHome(io.env);
|
|
167466
|
+
const engine = await (io.openSite ?? openSingleSite2)({ root: resolve15(io.cwd, path6), home, env: io.env, watch: false });
|
|
167467
|
+
const deploy = createDeployService({ home, settings: engine.settings, events: engine.events, env: io.env });
|
|
167468
|
+
const json10 = Boolean(values.json);
|
|
167469
|
+
try {
|
|
167470
|
+
const status2 = await deploy.status(engine.site);
|
|
167471
|
+
const domain2 = status2.config?.domain;
|
|
167472
|
+
if (hostname3) return await useDomain(io, deploy, engine.events, engine.site, hostname3, { yes: Boolean(values.yes), json: json10 });
|
|
167473
|
+
if (values.check) {
|
|
167474
|
+
if (!domain2) throw new UsageError("This site isn't using an address of its own.");
|
|
167475
|
+
return await report2(io, deploy, engine.site, await follow(engine.events, deploy, await deploy.checkDomain(engine.site), (detail) => !json10 && io.err(detail)), json10);
|
|
167476
|
+
}
|
|
167477
|
+
if (values.remove) {
|
|
167478
|
+
if (!domain2) throw new UsageError("This site isn't using an address of its own.");
|
|
167479
|
+
if (!values.yes) {
|
|
167480
|
+
if (!io.prompt) throw new UsageError(`Nothing was changed. Run it again with --yes to stop using ${domain2.hostname}.`);
|
|
167481
|
+
if (!/^y(es)?$/i.test(await io.prompt(`Stop using ${domain2.hostname}? [y/N] `))) return 1;
|
|
167482
|
+
}
|
|
167483
|
+
const after = await deploy.detachDomain(engine.site);
|
|
167484
|
+
if (json10) io.out(JSON.stringify({ ok: true, address: after.config?.productionUrl ?? null }));
|
|
167485
|
+
else io.out(`\u2713 Stopped using ${domain2.hostname}.${after.config?.productionUrl ? ` The live address is ${after.config.productionUrl} again.` : ""}${domain2.attached ? "" : ` It was set up outside ${PRODUCT.name}, so it stays as it is on the host.`}`);
|
|
167486
|
+
return 0;
|
|
167487
|
+
}
|
|
167488
|
+
if (json10) io.out(JSON.stringify({ address: status2.config?.productionUrl ?? null, domain: domain2 ?? null, hostAddress: status2.config?.defaultUrl ?? null }));
|
|
167489
|
+
else if (domain2) io.out(`${domain2.hostname}${domain2.pending ? " \u2014 attached, not answering yet" : ""}`);
|
|
167490
|
+
else io.out(`No address of its own.${status2.config?.productionUrl ? ` Live at ${status2.config.productionUrl}.` : ""}`);
|
|
167491
|
+
return 0;
|
|
167492
|
+
} catch (error63) {
|
|
167493
|
+
if (error63 instanceof UsageError) throw error63;
|
|
167494
|
+
const message2 = deployMessage(error63);
|
|
167495
|
+
if (json10) io.out(JSON.stringify({ ok: false, error: message2 }));
|
|
167496
|
+
else io.err(`! ${message2}`);
|
|
167497
|
+
return 1;
|
|
167498
|
+
} finally {
|
|
167499
|
+
deploy.dispose();
|
|
167500
|
+
await engine.dispose();
|
|
167501
|
+
}
|
|
167502
|
+
}
|
|
167503
|
+
|
|
167504
|
+
// src/commands/deploy.ts
|
|
167052
167505
|
var DEPLOY_HELP = `Usage: ${PRODUCT.slug} deploy [path] [options]
|
|
167053
167506
|
|
|
167054
167507
|
Put the site in [path] (default: this folder) online with Cloudflare or
|
|
@@ -167063,6 +167516,8 @@ Options
|
|
|
167063
167516
|
--target <host> cloudflare (default) or vercel
|
|
167064
167517
|
--project <name> The project on the host (default: from the site's name)
|
|
167065
167518
|
--account <id> The Cloudflare account or Vercel team
|
|
167519
|
+
--domain <host> Afterwards, use your own address for the live site
|
|
167520
|
+
(see \`${PRODUCT.slug} domain --help\`)
|
|
167066
167521
|
-y, --yes Don't ask: take the defaults (and an existing project)
|
|
167067
167522
|
--json Print the result as JSON
|
|
167068
167523
|
-h, --help Show this help
|
|
@@ -167163,6 +167618,7 @@ async function deployCommand(argv, io) {
|
|
|
167163
167618
|
target: { type: "string" },
|
|
167164
167619
|
project: { type: "string" },
|
|
167165
167620
|
account: { type: "string" },
|
|
167621
|
+
domain: { type: "string" },
|
|
167166
167622
|
yes: { type: "boolean", short: "y" },
|
|
167167
167623
|
json: { type: "boolean" }
|
|
167168
167624
|
},
|
|
@@ -167174,7 +167630,7 @@ async function deployCommand(argv, io) {
|
|
|
167174
167630
|
}
|
|
167175
167631
|
const json10 = Boolean(values.json);
|
|
167176
167632
|
const ioWithPrompt = { ...io, ...io.prompt === void 0 && !json10 ? { prompt: terminalPrompt() ?? void 0 } : {} };
|
|
167177
|
-
const root =
|
|
167633
|
+
const root = resolve16(io.cwd, positionals[0] ?? ".");
|
|
167178
167634
|
const home = defaultHome(io.env);
|
|
167179
167635
|
const engine = await (io.openSite ?? openSingleSite2)({ root, home, env: io.env, watch: false });
|
|
167180
167636
|
const deploy = createDeployService({ home, settings: engine.settings, events: engine.events, env: io.env });
|
|
@@ -167200,6 +167656,10 @@ async function deployCommand(argv, io) {
|
|
|
167200
167656
|
io.out(`\u2713 Preview at ${deployment.url}`);
|
|
167201
167657
|
io.err(` It shows unpublished changes. ${chosen.target.previewNote}`);
|
|
167202
167658
|
}
|
|
167659
|
+
if (values.domain) {
|
|
167660
|
+
if (kind !== "production") throw new UsageError("--domain goes with a live deploy, not --preview.");
|
|
167661
|
+
return await useDomain(ioWithPrompt, deploy, engine.events, engine.site, values.domain, { yes: Boolean(values.yes), json: json10 });
|
|
167662
|
+
}
|
|
167203
167663
|
return 0;
|
|
167204
167664
|
} catch (error63) {
|
|
167205
167665
|
if (error63 instanceof UsageError) throw error63;
|
|
@@ -167276,7 +167736,7 @@ init_brand();
|
|
|
167276
167736
|
init_content();
|
|
167277
167737
|
import { execFile as execFile4 } from "node:child_process";
|
|
167278
167738
|
import { existsSync as existsSync23, statSync as statSync16 } from "node:fs";
|
|
167279
|
-
import { join as join58, resolve as
|
|
167739
|
+
import { join as join58, resolve as resolve17 } from "node:path";
|
|
167280
167740
|
|
|
167281
167741
|
// src/summary.ts
|
|
167282
167742
|
function frameworkLine(model) {
|
|
@@ -167438,7 +167898,7 @@ async function doctorCommand(argv, io) {
|
|
|
167438
167898
|
io.out(DOCTOR_HELP);
|
|
167439
167899
|
return 0;
|
|
167440
167900
|
}
|
|
167441
|
-
const root =
|
|
167901
|
+
const root = resolve17(io.cwd, positionals[0] ?? ".");
|
|
167442
167902
|
const checks = await doctorChecks(root, io);
|
|
167443
167903
|
const failed = checks.some((check4) => check4.level === "fail");
|
|
167444
167904
|
if (values.json) io.out(JSON.stringify({ path: root, ok: !failed, checks }, null, 2));
|
|
@@ -167509,7 +167969,7 @@ init_brand();
|
|
|
167509
167969
|
init_content();
|
|
167510
167970
|
import { existsSync as existsSync24, statSync as statSync17 } from "node:fs";
|
|
167511
167971
|
import { writeFile as writeFile24 } from "node:fs/promises";
|
|
167512
|
-
import { join as join59, resolve as
|
|
167972
|
+
import { join as join59, resolve as resolve18 } from "node:path";
|
|
167513
167973
|
var INIT_HELP = `Usage: ${PRODUCT.slug} init [path] [options]
|
|
167514
167974
|
|
|
167515
167975
|
Write ${PRODUCT.configFile} in [path] (default: this folder) from what detection
|
|
@@ -167533,7 +167993,7 @@ async function initCommand(argv, io) {
|
|
|
167533
167993
|
io.out(INIT_HELP);
|
|
167534
167994
|
return 0;
|
|
167535
167995
|
}
|
|
167536
|
-
const root =
|
|
167996
|
+
const root = resolve18(io.cwd, positionals[0] ?? ".");
|
|
167537
167997
|
if (!statSync17(root, { throwIfNoEntry: false })?.isDirectory()) {
|
|
167538
167998
|
io.err(`There's no folder at ${root}.`);
|
|
167539
167999
|
return 1;
|
|
@@ -167560,12 +168020,12 @@ async function initCommand(argv, io) {
|
|
|
167560
168020
|
// src/commands/mcp.ts
|
|
167561
168021
|
init_brand();
|
|
167562
168022
|
import { realpathSync as realpathSync12, statSync as statSync19 } from "node:fs";
|
|
167563
|
-
import { resolve as
|
|
168023
|
+
import { resolve as resolve20 } from "node:path";
|
|
167564
168024
|
|
|
167565
168025
|
// src/commands/open.ts
|
|
167566
168026
|
init_brand();
|
|
167567
168027
|
import { statSync as statSync18 } from "node:fs";
|
|
167568
|
-
import { resolve as
|
|
168028
|
+
import { resolve as resolve19 } from "node:path";
|
|
167569
168029
|
var OPEN_HELP = `Usage: ${PRODUCT.slug} [path] [options]
|
|
167570
168030
|
|
|
167571
168031
|
Open the site in [path] (default: this folder) and the browser, signed in.
|
|
@@ -167583,7 +168043,7 @@ async function openCommand(argv, io, hooks = {}) {
|
|
|
167583
168043
|
return 0;
|
|
167584
168044
|
}
|
|
167585
168045
|
const port = portOption(values.port);
|
|
167586
|
-
const root =
|
|
168046
|
+
const root = resolve19(io.cwd, positionals[0] ?? ".");
|
|
167587
168047
|
const info = statSync18(root, { throwIfNoEntry: false });
|
|
167588
168048
|
if (!info) {
|
|
167589
168049
|
io.err(`There's no folder at ${root}.`);
|
|
@@ -167693,7 +168153,7 @@ async function tokenCommand(argv, io) {
|
|
|
167693
168153
|
}
|
|
167694
168154
|
function launcherOf(io) {
|
|
167695
168155
|
if (io.launcher) return io.launcher;
|
|
167696
|
-
const script = process.argv[1] ? realpathSync12(process.argv[1]) :
|
|
168156
|
+
const script = process.argv[1] ? realpathSync12(process.argv[1]) : resolve20(io.cwd, "galley");
|
|
167697
168157
|
return { command: process.execPath, args: [script] };
|
|
167698
168158
|
}
|
|
167699
168159
|
function printConfig(io, config2) {
|
|
@@ -167728,7 +168188,7 @@ async function configCommand(argv, io) {
|
|
|
167728
168188
|
throw new UsageError(`Choose a client with --client: ${MCP_CLIENTS.join(", ")}.`);
|
|
167729
168189
|
}
|
|
167730
168190
|
const transport = values.http ? "http" : "stdio";
|
|
167731
|
-
const root =
|
|
168191
|
+
const root = resolve20(io.cwd, positionals[0] ?? ".");
|
|
167732
168192
|
if (transport === "stdio" && !checkSite(io, root)) return 1;
|
|
167733
168193
|
if (transport === "http" && positionals[0]) throw new UsageError("Over HTTP the server already knows its sites, so leave out the path.");
|
|
167734
168194
|
const publicUrl = io.env.GALLEY_PUBLIC_URL?.trim();
|
|
@@ -167768,7 +168228,7 @@ async function serveCommand(argv, io) {
|
|
|
167768
168228
|
io.out(MCP_HELP);
|
|
167769
168229
|
return 0;
|
|
167770
168230
|
}
|
|
167771
|
-
const root =
|
|
168231
|
+
const root = resolve20(io.cwd, positionals[0] ?? ".");
|
|
167772
168232
|
if (!checkSite(io, root)) return 1;
|
|
167773
168233
|
const mode = values.build ? "build" : "content";
|
|
167774
168234
|
const readOnly2 = Boolean(values["read-only"]);
|
|
@@ -167813,9 +168273,9 @@ async function serveCommand(argv, io) {
|
|
|
167813
168273
|
return 0;
|
|
167814
168274
|
}
|
|
167815
168275
|
async function mcpCommand(argv, io) {
|
|
167816
|
-
const [
|
|
167817
|
-
if (
|
|
167818
|
-
if (
|
|
168276
|
+
const [first3, ...rest] = argv;
|
|
168277
|
+
if (first3 === "token") return tokenCommand(rest, io);
|
|
168278
|
+
if (first3 === "config") return configCommand(rest, io);
|
|
167819
168279
|
return serveCommand(argv, io);
|
|
167820
168280
|
}
|
|
167821
168281
|
|
|
@@ -167828,7 +168288,7 @@ init_content();
|
|
|
167828
168288
|
import { execFile as execFile5 } from "node:child_process";
|
|
167829
168289
|
import { accessSync as accessSync2, constants as constants3, readdirSync as readdirSync6, realpathSync as realpathSync13, statSync as statSync20 } from "node:fs";
|
|
167830
168290
|
import { homedir as homedir8 } from "node:os";
|
|
167831
|
-
import { basename as basename8, delimiter as delimiter3, dirname as dirname10, isAbsolute as isAbsolute15, join as join61, relative as relative12, resolve as
|
|
168291
|
+
import { basename as basename8, delimiter as delimiter3, dirname as dirname10, isAbsolute as isAbsolute15, join as join61, relative as relative12, resolve as resolve22 } from "node:path";
|
|
167832
168292
|
|
|
167833
168293
|
// src/package-manager.ts
|
|
167834
168294
|
var MANAGERS = ["npm", "pnpm", "yarn", "bun"];
|
|
@@ -167995,7 +168455,7 @@ function displayName(choice) {
|
|
|
167995
168455
|
|
|
167996
168456
|
// src/commands/starters.ts
|
|
167997
168457
|
init_brand();
|
|
167998
|
-
import { resolve as
|
|
168458
|
+
import { resolve as resolve21 } from "node:path";
|
|
167999
168459
|
var STARTERS_HELP = `Usage: ${PRODUCT.slug} starters [--json]
|
|
168000
168460
|
|
|
168001
168461
|
List the starters \`${PRODUCT.slug} new\` can copy: what each one is, what is
|
|
@@ -168005,7 +168465,7 @@ Options
|
|
|
168005
168465
|
--json Print them as JSON
|
|
168006
168466
|
-h, --help Show this help`;
|
|
168007
168467
|
function startersDir(env) {
|
|
168008
|
-
return
|
|
168468
|
+
return resolve21(env.GALLEY_STARTERS_DIR?.trim() || defaultStartersDir());
|
|
168009
168469
|
}
|
|
168010
168470
|
function looksLine(choice) {
|
|
168011
168471
|
const looks = choice.info.looks ?? [];
|
|
@@ -168102,11 +168562,11 @@ function siteName2(input2) {
|
|
|
168102
168562
|
return words3.charAt(0).toUpperCase() + words3.slice(1);
|
|
168103
168563
|
}
|
|
168104
168564
|
function placeSite(cwd, dir, input2) {
|
|
168105
|
-
const parent =
|
|
168565
|
+
const parent = resolve22(cwd, dir ?? ".");
|
|
168106
168566
|
const text7 = input2.trim();
|
|
168107
168567
|
if (text7 === "." || text7 === ".." || /[\\/]/.test(text7) || text7.startsWith("~")) {
|
|
168108
168568
|
const expanded = text7 === "~" || text7.startsWith("~/") ? join61(homedir8(), text7.slice(1)) : text7;
|
|
168109
|
-
const target =
|
|
168569
|
+
const target = resolve22(parent, expanded);
|
|
168110
168570
|
return { name: siteName2(basename8(target)), target };
|
|
168111
168571
|
}
|
|
168112
168572
|
return { name: siteName2(text7), target: join61(parent, packageName(text7)) };
|
|
@@ -168239,7 +168699,7 @@ async function newCommand(argv, io) {
|
|
|
168239
168699
|
io.err(gitMissing(io.platform ?? process.platform));
|
|
168240
168700
|
return 1;
|
|
168241
168701
|
}
|
|
168242
|
-
const parent =
|
|
168702
|
+
const parent = resolve22(io.cwd, values.dir ?? ".");
|
|
168243
168703
|
let input2 = positionals[0]?.trim() ?? "";
|
|
168244
168704
|
if (!input2) {
|
|
168245
168705
|
const fallback3 = freeName(parent, DEFAULT_NAME);
|
|
@@ -168480,7 +168940,7 @@ init_brand();
|
|
|
168480
168940
|
init_content();
|
|
168481
168941
|
init_sitebrand();
|
|
168482
168942
|
import { mkdir as mkdir26, writeFile as writeFile25 } from "node:fs/promises";
|
|
168483
|
-
import { join as join62, resolve as
|
|
168943
|
+
import { join as join62, resolve as resolve23 } from "node:path";
|
|
168484
168944
|
var SCHEMAS = [
|
|
168485
168945
|
{ url: CONFIG_SCHEMA_URL, describe: `${PRODUCT.configFile} \u2014 a site's configuration`, make: configJsonSchema },
|
|
168486
168946
|
{ url: BRAND_SCHEMA_URL, describe: "brand.json \u2014 a site's brand (galley/brand/brand.json)", make: brandJsonSchema }
|
|
@@ -168510,7 +168970,7 @@ async function schemaCommand(argv, io) {
|
|
|
168510
168970
|
io.out(JSON.stringify(configJsonSchema(), null, 2));
|
|
168511
168971
|
return 0;
|
|
168512
168972
|
}
|
|
168513
|
-
const folder =
|
|
168973
|
+
const folder = resolve23(io.cwd, values.out);
|
|
168514
168974
|
await mkdir26(folder, { recursive: true });
|
|
168515
168975
|
io.out(`Wrote ${SCHEMAS.length} schemas. Serve each file at its address, as application/json (or application/schema+json):`);
|
|
168516
168976
|
for (const schema of SCHEMAS) {
|
|
@@ -168525,7 +168985,7 @@ async function schemaCommand(argv, io) {
|
|
|
168525
168985
|
|
|
168526
168986
|
// src/commands/serve.ts
|
|
168527
168987
|
init_brand();
|
|
168528
|
-
import { resolve as
|
|
168988
|
+
import { resolve as resolve24 } from "node:path";
|
|
168529
168989
|
var SERVE_HELP = `Usage: ${PRODUCT.slug} serve [options]
|
|
168530
168990
|
|
|
168531
168991
|
Run ${PRODUCT.name} for other computers (hosted mode), behind a password.
|
|
@@ -168555,7 +169015,7 @@ async function serveCommand2(argv, io) {
|
|
|
168555
169015
|
return 0;
|
|
168556
169016
|
}
|
|
168557
169017
|
const host3 = values.host ?? io.env.GALLEY_HOST ?? "0.0.0.0";
|
|
168558
|
-
const sitesDir = values["sites-dir"] ?
|
|
169018
|
+
const sitesDir = values["sites-dir"] ? resolve24(io.cwd, values["sites-dir"]) : void 0;
|
|
168559
169019
|
let server;
|
|
168560
169020
|
try {
|
|
168561
169021
|
server = await io.startServer({ mode: "hosted", host: host3, port: portOption(values.port), sitesDir, env: io.env, notice: (line) => io.err(`! ${line}`) });
|
|
@@ -168636,7 +169096,7 @@ function terminalPrompter(stdin = process.stdin, stdout = process.stdout, env =
|
|
|
168636
169096
|
const color2 = !env.NO_COLOR && env.TERM !== "dumb";
|
|
168637
169097
|
return {
|
|
168638
169098
|
choose(title, items, initial = 0) {
|
|
168639
|
-
return new Promise((
|
|
169099
|
+
return new Promise((resolve25) => {
|
|
168640
169100
|
let index = Math.min(Math.max(initial, 0), items.length - 1);
|
|
168641
169101
|
let drawn = 0;
|
|
168642
169102
|
const draw = () => {
|
|
@@ -168653,7 +169113,7 @@ function terminalPrompter(stdin = process.stdin, stdout = process.stdout, env =
|
|
|
168653
169113
|
stdout.write(`${ESC}${drawn}A${ESC}0J${ESC}?25h`);
|
|
168654
169114
|
stdout.write(result === null ? "" : `${title} ${style(color2).bold(items[result].label)}
|
|
168655
169115
|
`);
|
|
168656
|
-
|
|
169116
|
+
resolve25(result);
|
|
168657
169117
|
};
|
|
168658
169118
|
const onKey = (_text, key) => {
|
|
168659
169119
|
const step = pickerKey(index, items.length, key ?? {});
|
|
@@ -168694,8 +169154,8 @@ var ORPHAN_EXIT_MS = 8e3;
|
|
|
168694
169154
|
function watchStdin(stdin = process.stdin) {
|
|
168695
169155
|
let done = false;
|
|
168696
169156
|
let resolveGone;
|
|
168697
|
-
const gone = new Promise((
|
|
168698
|
-
resolveGone =
|
|
169157
|
+
const gone = new Promise((resolve25) => {
|
|
169158
|
+
resolveGone = resolve25;
|
|
168699
169159
|
});
|
|
168700
169160
|
const onGone = () => {
|
|
168701
169161
|
if (done) return;
|
|
@@ -168729,26 +169189,26 @@ function watchStdin(stdin = process.stdin) {
|
|
|
168729
169189
|
}
|
|
168730
169190
|
function openInBrowser(url2) {
|
|
168731
169191
|
const [command, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url2.replace(/&/g, "^&")]] : ["xdg-open", [url2]];
|
|
168732
|
-
return new Promise((
|
|
169192
|
+
return new Promise((resolve25) => {
|
|
168733
169193
|
try {
|
|
168734
169194
|
const child2 = spawn5(command, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
168735
|
-
child2.once("error", () =>
|
|
169195
|
+
child2.once("error", () => resolve25(false));
|
|
168736
169196
|
child2.once("spawn", () => {
|
|
168737
169197
|
child2.unref();
|
|
168738
|
-
|
|
169198
|
+
resolve25(true);
|
|
168739
169199
|
});
|
|
168740
169200
|
} catch {
|
|
168741
|
-
|
|
169201
|
+
resolve25(false);
|
|
168742
169202
|
}
|
|
168743
169203
|
});
|
|
168744
169204
|
}
|
|
168745
169205
|
function waitForSignal() {
|
|
168746
|
-
return new Promise((
|
|
169206
|
+
return new Promise((resolve25) => {
|
|
168747
169207
|
const stop = () => {
|
|
168748
169208
|
process.off("SIGINT", stop);
|
|
168749
169209
|
process.off("SIGTERM", stop);
|
|
168750
169210
|
process.once("SIGINT", () => process.exit(130));
|
|
168751
|
-
|
|
169211
|
+
resolve25();
|
|
168752
169212
|
};
|
|
168753
169213
|
process.on("SIGINT", stop);
|
|
168754
169214
|
process.on("SIGTERM", stop);
|
|
@@ -168789,6 +169249,7 @@ Usage
|
|
|
168789
169249
|
${PRODUCT.slug} init [path] Write ${PRODUCT.configFile} from what detection finds
|
|
168790
169250
|
${PRODUCT.slug} doctor [path] Check that a site and this computer are ready
|
|
168791
169251
|
${PRODUCT.slug} deploy [path] Put the site online with Cloudflare or Vercel (--preview: unpublished changes)
|
|
169252
|
+
${PRODUCT.slug} domain [path] Use your own domain for a site that is online
|
|
168792
169253
|
${PRODUCT.slug} new <name> Start a new site from a starter
|
|
168793
169254
|
${PRODUCT.slug} import \u2026 Bring a WordPress site (or another importer's) into a site
|
|
168794
169255
|
${PRODUCT.slug} starters List the starters and their looks
|
|
@@ -168821,17 +169282,18 @@ var COMMANDS = {
|
|
|
168821
169282
|
plugin: pluginCommand,
|
|
168822
169283
|
import: importCommand2,
|
|
168823
169284
|
deploy: deployCommand,
|
|
169285
|
+
domain: domainCommand,
|
|
168824
169286
|
schema: schemaCommand,
|
|
168825
169287
|
version: versionCommand,
|
|
168826
169288
|
// Started by the desktop app, not typed by people, so it isn't in HELP.
|
|
168827
169289
|
desktop: desktopCommand
|
|
168828
169290
|
};
|
|
168829
169291
|
function route(argv) {
|
|
168830
|
-
const [
|
|
168831
|
-
if (
|
|
168832
|
-
if (
|
|
168833
|
-
if (
|
|
168834
|
-
if (
|
|
169292
|
+
const [first3, ...rest] = argv;
|
|
169293
|
+
if (first3 === void 0) return { name: "open", args: [] };
|
|
169294
|
+
if (first3 === "help" || (first3 === "--help" || first3 === "-h") && rest.length === 0) return { name: "help", args: [] };
|
|
169295
|
+
if (first3 === "--version" || first3 === "-v") return { name: "version", args: rest };
|
|
169296
|
+
if (first3 in COMMANDS) return { name: first3, args: rest };
|
|
168835
169297
|
return { name: "open", args: argv };
|
|
168836
169298
|
}
|
|
168837
169299
|
async function main(argv, io = processIo()) {
|