gemi 0.190.0 → 0.192.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +28 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +143 -3
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/client/index.d.ts +1 -1
- package/dist/ai/client/index.d.ts.map +1 -1
- package/dist/ai/client/index.js +59 -1
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/index.d.ts +3 -3
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +91 -68
- package/dist/ai/index.js.map +5 -5
- package/dist/ai/jobs/AgentJob.d.ts +32 -0
- package/dist/ai/jobs/AgentJob.d.ts.map +1 -1
- package/dist/ai/jobs/index.d.ts +1 -1
- package/dist/ai/jobs/index.d.ts.map +1 -1
- package/dist/ai/store/DatabaseAgentStore.d.ts +66 -3
- package/dist/ai/store/DatabaseAgentStore.d.ts.map +1 -1
- package/dist/ai/store/MemoryAgentStore.d.ts +12 -0
- package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -1
- package/dist/ai/types.d.ts +18 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +15 -0
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-6z3wv71t.js → chunk-0m1a636t.js} +2 -2
- package/dist/{chunk-6z3wv71t.js.map → chunk-0m1a636t.js.map} +1 -1
- package/dist/{chunk-00g20rfa.js → chunk-0mb77yd2.js} +2 -2
- package/dist/{chunk-00g20rfa.js.map → chunk-0mb77yd2.js.map} +1 -1
- package/dist/{chunk-qz6grt61.js → chunk-0p76bhy2.js} +2 -2
- package/dist/{chunk-qz6grt61.js.map → chunk-0p76bhy2.js.map} +1 -1
- package/dist/{chunk-zwj4w4zt.js → chunk-17mdszc3.js} +2 -2
- package/dist/{chunk-zwj4w4zt.js.map → chunk-17mdszc3.js.map} +1 -1
- package/dist/{chunk-yt5n62nj.js → chunk-199nvtrj.js} +2 -2
- package/dist/{chunk-yt5n62nj.js.map → chunk-199nvtrj.js.map} +1 -1
- package/dist/{chunk-w2z4jc4v.js → chunk-1mpwzjxa.js} +3 -3
- package/dist/{chunk-w2z4jc4v.js.map → chunk-1mpwzjxa.js.map} +1 -1
- package/dist/{chunk-dsgjdk94.js → chunk-24jgzc8y.js} +2 -2
- package/dist/{chunk-dsgjdk94.js.map → chunk-24jgzc8y.js.map} +1 -1
- package/dist/{chunk-fgk1e5xe.js → chunk-4s7st9y4.js} +3 -3
- package/dist/{chunk-fgk1e5xe.js.map → chunk-4s7st9y4.js.map} +1 -1
- package/dist/{chunk-epb0qfce.js → chunk-5zx4e2wa.js} +3 -3
- package/dist/{chunk-epb0qfce.js.map → chunk-5zx4e2wa.js.map} +1 -1
- package/dist/{chunk-s5z8qcdv.js → chunk-67ex6nem.js} +3 -3
- package/dist/{chunk-s5z8qcdv.js.map → chunk-67ex6nem.js.map} +1 -1
- package/dist/{chunk-790dx3s7.js → chunk-67zz58cw.js} +2 -2
- package/dist/{chunk-790dx3s7.js.map → chunk-67zz58cw.js.map} +1 -1
- package/dist/{chunk-kcg2znz2.js → chunk-6frbegay.js} +2 -2
- package/dist/{chunk-kcg2znz2.js.map → chunk-6frbegay.js.map} +1 -1
- package/dist/{chunk-0gvw46j0.js → chunk-6n44t4hn.js} +2 -2
- package/dist/{chunk-0gvw46j0.js.map → chunk-6n44t4hn.js.map} +1 -1
- package/dist/{chunk-baknm4tn.js → chunk-6rmz0mkm.js} +2 -2
- package/dist/{chunk-baknm4tn.js.map → chunk-6rmz0mkm.js.map} +1 -1
- package/dist/{chunk-k9f7gww2.js → chunk-6wsmdf51.js} +2 -2
- package/dist/{chunk-k9f7gww2.js.map → chunk-6wsmdf51.js.map} +1 -1
- package/dist/{chunk-2v7a5wv6.js → chunk-7k43y71n.js} +2 -2
- package/dist/{chunk-2v7a5wv6.js.map → chunk-7k43y71n.js.map} +1 -1
- package/dist/{chunk-er7xemh2.js → chunk-7ynahcy6.js} +2 -2
- package/dist/{chunk-er7xemh2.js.map → chunk-7ynahcy6.js.map} +1 -1
- package/dist/{chunk-7des5zys.js → chunk-7zpjdwfq.js} +3 -3
- package/dist/{chunk-7des5zys.js.map → chunk-7zpjdwfq.js.map} +1 -1
- package/dist/{chunk-yn2av14e.js → chunk-8em2ebj1.js} +2 -2
- package/dist/{chunk-yn2av14e.js.map → chunk-8em2ebj1.js.map} +1 -1
- package/dist/{chunk-nc37phkt.js → chunk-8pfy75y6.js} +3 -3
- package/dist/{chunk-nc37phkt.js.map → chunk-8pfy75y6.js.map} +1 -1
- package/dist/{chunk-8f8bp75w.js → chunk-8zeky0fj.js} +5 -5
- package/dist/{chunk-8f8bp75w.js.map → chunk-8zeky0fj.js.map} +3 -3
- package/dist/{chunk-khzss89b.js → chunk-9dfrsj4m.js} +2 -2
- package/dist/{chunk-khzss89b.js.map → chunk-9dfrsj4m.js.map} +1 -1
- package/dist/{chunk-fcj0e64h.js → chunk-9hmm8acy.js} +1 -1
- package/dist/{chunk-rp2h86ph.js → chunk-9m04tdzh.js} +1 -1
- package/dist/{chunk-71jcjnwk.js → chunk-bd14zwmj.js} +25 -21
- package/dist/{chunk-71jcjnwk.js.map → chunk-bd14zwmj.js.map} +4 -4
- package/dist/{chunk-g52hvs5q.js → chunk-bhfwp3gz.js} +2 -2
- package/dist/{chunk-g52hvs5q.js.map → chunk-bhfwp3gz.js.map} +1 -1
- package/dist/{chunk-2adfcfdw.js → chunk-bm7z4vj9.js} +2 -2
- package/dist/{chunk-2adfcfdw.js.map → chunk-bm7z4vj9.js.map} +1 -1
- package/dist/{chunk-e9nmsgnd.js → chunk-c36sbvnz.js} +2 -2
- package/dist/{chunk-e9nmsgnd.js.map → chunk-c36sbvnz.js.map} +1 -1
- package/dist/{chunk-x1ng1dnx.js → chunk-ccx7rt7y.js} +2 -2
- package/dist/{chunk-x1ng1dnx.js.map → chunk-ccx7rt7y.js.map} +1 -1
- package/dist/{chunk-xqzrd7st.js → chunk-ce73s4kh.js} +2 -2
- package/dist/{chunk-xqzrd7st.js.map → chunk-ce73s4kh.js.map} +1 -1
- package/dist/{chunk-3z55zyfe.js → chunk-cx3n8qyr.js} +2 -2
- package/dist/{chunk-3z55zyfe.js.map → chunk-cx3n8qyr.js.map} +1 -1
- package/dist/{chunk-xwa8vtg5.js → chunk-d0khszc9.js} +2 -2
- package/dist/{chunk-xwa8vtg5.js.map → chunk-d0khszc9.js.map} +1 -1
- package/dist/{chunk-frvca65w.js → chunk-efgemgbe.js} +2 -2
- package/dist/{chunk-frvca65w.js.map → chunk-efgemgbe.js.map} +1 -1
- package/dist/{chunk-6tsyk2mr.js → chunk-ejc0mbe3.js} +2 -2
- package/dist/{chunk-6tsyk2mr.js.map → chunk-ejc0mbe3.js.map} +1 -1
- package/dist/{chunk-hv6nbbty.js → chunk-etzd00a8.js} +2 -2
- package/dist/{chunk-hv6nbbty.js.map → chunk-etzd00a8.js.map} +1 -1
- package/dist/{chunk-6a3t825g.js → chunk-f02anz24.js} +2 -2
- package/dist/{chunk-6a3t825g.js.map → chunk-f02anz24.js.map} +1 -1
- package/dist/{chunk-qy678j5z.js → chunk-fbxnxze2.js} +1 -1
- package/dist/{chunk-j16ekp16.js → chunk-freerpzc.js} +1 -1
- package/dist/{chunk-h8knqrc5.js → chunk-fryj3asn.js} +2 -2
- package/dist/{chunk-h8knqrc5.js.map → chunk-fryj3asn.js.map} +1 -1
- package/dist/{chunk-vzzt4kpk.js → chunk-h688s2ba.js} +2 -2
- package/dist/{chunk-vzzt4kpk.js.map → chunk-h688s2ba.js.map} +1 -1
- package/dist/{chunk-bc1k2206.js → chunk-hwq0kk1d.js} +1 -1
- package/dist/{chunk-mvs6brkk.js → chunk-j34ektzj.js} +2 -2
- package/dist/{chunk-mvs6brkk.js.map → chunk-j34ektzj.js.map} +1 -1
- package/dist/{chunk-ds684s0w.js → chunk-jbee3n3p.js} +2 -2
- package/dist/{chunk-ds684s0w.js.map → chunk-jbee3n3p.js.map} +1 -1
- package/dist/{chunk-80kpxp4m.js → chunk-k1c0xd8r.js} +2 -2
- package/dist/{chunk-80kpxp4m.js.map → chunk-k1c0xd8r.js.map} +1 -1
- package/dist/{chunk-tmz3gf96.js → chunk-k8gn0q91.js} +1 -1
- package/dist/{chunk-8p7a2ctj.js → chunk-m3180wkp.js} +2 -2
- package/dist/{chunk-8p7a2ctj.js.map → chunk-m3180wkp.js.map} +1 -1
- package/dist/{chunk-s1wj0ff8.js → chunk-m37vvh99.js} +2 -2
- package/dist/{chunk-s1wj0ff8.js.map → chunk-m37vvh99.js.map} +1 -1
- package/dist/{chunk-mmzf9c2e.js → chunk-m4r8btey.js} +2 -2
- package/dist/{chunk-mmzf9c2e.js.map → chunk-m4r8btey.js.map} +1 -1
- package/dist/{chunk-8mgz2na4.js → chunk-mdrsec0r.js} +2 -2
- package/dist/{chunk-8mgz2na4.js.map → chunk-mdrsec0r.js.map} +1 -1
- package/dist/{chunk-nbhxm3sz.js → chunk-mx9zcq7w.js} +2 -2
- package/dist/{chunk-nbhxm3sz.js.map → chunk-mx9zcq7w.js.map} +1 -1
- package/dist/{chunk-t6ng9yxp.js → chunk-p00rd4ja.js} +2 -2
- package/dist/{chunk-t6ng9yxp.js.map → chunk-p00rd4ja.js.map} +1 -1
- package/dist/{chunk-rf4a3tnm.js → chunk-qfb6r3cq.js} +3 -3
- package/dist/{chunk-rf4a3tnm.js.map → chunk-qfb6r3cq.js.map} +1 -1
- package/dist/{chunk-352y2y3z.js → chunk-qg60pgve.js} +2 -2
- package/dist/{chunk-352y2y3z.js.map → chunk-qg60pgve.js.map} +1 -1
- package/dist/{chunk-2qqm3482.js → chunk-qnc840pb.js} +2 -2
- package/dist/{chunk-2qqm3482.js.map → chunk-qnc840pb.js.map} +1 -1
- package/dist/{chunk-mqvyhqa6.js → chunk-r7vnxqck.js} +2 -2
- package/dist/{chunk-mqvyhqa6.js.map → chunk-r7vnxqck.js.map} +1 -1
- package/dist/{chunk-bwmyd47e.js → chunk-rf9c6e49.js} +2 -2
- package/dist/{chunk-bwmyd47e.js.map → chunk-rf9c6e49.js.map} +1 -1
- package/dist/{chunk-1987f978.js → chunk-ryfty6mj.js} +3 -3
- package/dist/{chunk-1987f978.js.map → chunk-ryfty6mj.js.map} +1 -1
- package/dist/{chunk-6bhscseq.js → chunk-sqev442x.js} +4 -4
- package/dist/{chunk-6bhscseq.js.map → chunk-sqev442x.js.map} +1 -1
- package/dist/{chunk-npd1501w.js → chunk-t86nc1jd.js} +2 -2
- package/dist/{chunk-npd1501w.js.map → chunk-t86nc1jd.js.map} +1 -1
- package/dist/{chunk-qp1nzdjc.js → chunk-thq8tc9x.js} +3 -3
- package/dist/{chunk-qp1nzdjc.js.map → chunk-thq8tc9x.js.map} +1 -1
- package/dist/{chunk-cbw4676x.js → chunk-tngf3h1g.js} +2 -2
- package/dist/{chunk-cbw4676x.js.map → chunk-tngf3h1g.js.map} +1 -1
- package/dist/{chunk-n415vvxw.js → chunk-tt5qk0xt.js} +2 -2
- package/dist/{chunk-n415vvxw.js.map → chunk-tt5qk0xt.js.map} +1 -1
- package/dist/{chunk-b35mk5rd.js → chunk-tvsjq0my.js} +2 -2
- package/dist/{chunk-b35mk5rd.js.map → chunk-tvsjq0my.js.map} +1 -1
- package/dist/{chunk-2k948anx.js → chunk-vr48swd0.js} +2 -2
- package/dist/{chunk-2k948anx.js.map → chunk-vr48swd0.js.map} +1 -1
- package/dist/{chunk-sz0avnch.js → chunk-wa1xmvgr.js} +2 -2
- package/dist/{chunk-sz0avnch.js.map → chunk-wa1xmvgr.js.map} +1 -1
- package/dist/chunk-waq4kj7n.js +5 -0
- package/dist/{chunk-qv3y19h5.js.map → chunk-waq4kj7n.js.map} +1 -1
- package/dist/{chunk-8b897pc1.js → chunk-xsx69765.js} +2 -2
- package/dist/{chunk-8b897pc1.js.map → chunk-xsx69765.js.map} +1 -1
- package/dist/{chunk-eqnrk0p8.js → chunk-xwz5fmwy.js} +2 -2
- package/dist/{chunk-eqnrk0p8.js.map → chunk-xwz5fmwy.js.map} +1 -1
- package/dist/{chunk-ct2kqpv5.js → chunk-xzz6ps4z.js} +2 -2
- package/dist/{chunk-ct2kqpv5.js.map → chunk-xzz6ps4z.js.map} +1 -1
- package/dist/{chunk-s91xa67z.js → chunk-y67rmd3y.js} +2 -2
- package/dist/{chunk-s91xa67z.js.map → chunk-y67rmd3y.js.map} +1 -1
- package/dist/{chunk-1e7pnsx2.js → chunk-z1aeh05w.js} +3 -3
- package/dist/{chunk-1e7pnsx2.js.map → chunk-z1aeh05w.js.map} +1 -1
- package/dist/{chunk-070cacy8.js → chunk-z7mbhc68.js} +2 -2
- package/dist/{chunk-070cacy8.js.map → chunk-z7mbhc68.js.map} +1 -1
- package/dist/{chunk-pjjwbs2f.js → chunk-z8dxdqzm.js} +2 -2
- package/dist/{chunk-pjjwbs2f.js.map → chunk-z8dxdqzm.js.map} +1 -1
- package/dist/{chunk-9q5g3a9t.js → chunk-z9pq557m.js} +2 -2
- package/dist/{chunk-9q5g3a9t.js.map → chunk-z9pq557m.js.map} +1 -1
- package/dist/{chunk-dhwxcedm.js → chunk-zcrhagx5.js} +2 -2
- package/dist/{chunk-dhwxcedm.js.map → chunk-zcrhagx5.js.map} +1 -1
- package/dist/client/Head.d.ts +26 -1
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +17 -2
- package/dist/client/index.js.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +1 -0
- package/dist/http/ApiRouter.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-qv3y19h5.js +0 -5
- /package/dist/{chunk-fcj0e64h.js.map → chunk-9hmm8acy.js.map} +0 -0
- /package/dist/{chunk-rp2h86ph.js.map → chunk-9m04tdzh.js.map} +0 -0
- /package/dist/{chunk-qy678j5z.js.map → chunk-fbxnxze2.js.map} +0 -0
- /package/dist/{chunk-j16ekp16.js.map → chunk-freerpzc.js.map} +0 -0
- /package/dist/{chunk-bc1k2206.js.map → chunk-hwq0kk1d.js.map} +0 -0
- /package/dist/{chunk-tmz3gf96.js.map → chunk-k8gn0q91.js.map} +0 -0
package/dist/probe/index.js.map
CHANGED
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { projectRoot } from \"../support/discover\";\n\n/**\n * Browser probes (#1020): code an app runs in a headless browser's page with\n * `page.evaluate`, written as a normal module.\n *\n * `page.evaluate` sends one function's source to the browser, so it may use\n * nothing from outside itself. A probe is a module under `app/` named\n * `*.probe.ts` (or `.js`) whose default export is the function to run; it can\n * import helpers like any module. gemi bundles it into one self-contained,\n * minified IIFE for the browser and hands it to `page.evaluate` as an\n * expression that calls the default export with the given arguments.\n *\n * `gemi build` bundles every probe into `dist/server/probes.json` (name →\n * source), which `gemi start` reads. Anywhere else (dev, tests) a probe is\n * bundled on first use and kept until it, or a file it imports, changes.\n *\n * A probe is named by its path under `app/` without the suffix:\n * `app/utils/layout.probe.ts` is `\"utils/layout\"`.\n */\n\n/** The suffix that marks a file under `app` as a probe. */\nexport const PROBE_SUFFIX = \".probe\";\nconst EXTENSIONS = [\".ts\", \".js\"];\n/** Under `dist/server`. */\nexport const PROBES_MANIFEST = \"probes.json\";\n\n/** The free name the bundled IIFE hands the default export to. */\nconst DEFINE = \"__gemiProbe__\";\n/** The bundle's entry: imports the probe and hands its default export over. */\nconst ENTRY = \"/__gemi_probe_entry__.ts\";\n\n/** A name as `probe` takes it: a path under `app`, without the suffix. */\nconst NAME = /^[A-Za-z0-9_-]+(\\/[A-Za-z0-9_-]+)*$/;\n\nfunction assertName(name: string) {\n if (typeof name !== \"string\" || !NAME.test(name)) {\n throw new Error(\n `A probe is named by its path under app/ without the \".probe.ts\" suffix, e.g. \"utils/layout\". Got ${JSON.stringify(name)}.`,\n );\n }\n}\n\n/** The source file of the probe `name` under `appDir`, or `null` when there is none. */\nexport function probeFile(appDir: string, name: string): string | null {\n for (const extension of EXTENSIONS) {\n const file = join(appDir, `${name}${PROBE_SUFFIX}${extension}`);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\ntype Bundled = {\n /** The IIFE: hands the probe's default export to `__gemiProbe__`. */\n source: string;\n /** Every file the bundle read, absolute, for the dev cache. */\n inputs: string[];\n};\n\n/**\n * Bundles one probe for the browser: imports inlined, minified, wrapped in an\n * IIFE that hands the default export to `__gemiProbe__`. Throws when it does\n * not bundle.\n */\nasync function bundle(file: string): Promise<Bundled> {\n const result = await Bun.build({\n entrypoints: [ENTRY],\n files: {\n [ENTRY]: `import probe from ${JSON.stringify(file)};\\n${DEFINE}(probe);\\n`,\n },\n target: \"browser\",\n format: \"iife\",\n minify: true,\n metafile: true,\n throw: false,\n });\n if (!result.success || !result.outputs[0]) {\n const logs = result.logs.map((log) => String(log)).join(\"\\n\");\n throw new Error(`The probe ${file} does not bundle.\\n${logs}`);\n }\n const inputs = Object.keys(result.metafile?.inputs ?? {})\n .map((input) => resolve(input))\n .filter((input) => input !== ENTRY && existsSync(input));\n return { source: (await result.outputs[0].text()).trim(), inputs };\n}\n\n/** One probe's bundled source (the IIFE). Throws when it does not bundle. */\nexport async function bundleProbe(file: string): Promise<string> {\n return (await bundle(file)).source;\n}\n\n/** Every probe under `appDir`, bundled: what `gemi build` writes. */\nexport async function bundleProbes(appDir: string): Promise<Record<string, string>> {\n const probes: Record<string, string> = {};\n if (!existsSync(appDir)) return probes;\n const glob = new Bun.Glob(`**/*${PROBE_SUFFIX}.{ts,js}`);\n const files = [...glob.scanSync({ cwd: appDir })].sort();\n for (const file of files) {\n if (file.split(\"/\").includes(\"node_modules\")) continue;\n const name = file.replace(/\\.probe\\.[tj]s$/, \"\");\n if (!NAME.test(name) || name in probes) continue;\n probes[name] = await bundleProbe(join(appDir, file));\n }\n return probes;\n}\n\n// `gemi start`'s manifest, read once. `undefined`: not read yet; `null`: none.\nlet built: Record<string, string> | null | undefined;\n// Bundled from source: in production once, elsewhere until an input changes.\ntype Cached = { pending: Promise<Bundled>; stamps: Map<string, number> | null };\nconst cache = new Map<string, Cached>();\n\nfunction builtProbes(): Record<string, string> | null {\n if (built === undefined) {\n const file = join(projectRoot(), \"dist\", \"server\", PROBES_MANIFEST);\n built = existsSync(file) ? JSON.parse(readFileSync(file, \"utf8\")) : null;\n }\n return built ?? null;\n}\n\nfunction mtimeOf(file: string): number {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return -1;\n }\n}\n\nfunction stale(stamps: Map<string, number>): boolean {\n for (const [file, mtime] of stamps) {\n if (mtimeOf(file) !== mtime) return true;\n }\n return false;\n}\n\n/** Forgets the manifest and every bundled probe (tests). @internal */\nexport function resetProbes() {\n built = undefined;\n cache.clear();\n}\n\n/**\n * The bundled source (an IIFE) of the probe `name`.\n *\n * In production, from `dist/server/probes.json`; a name the manifest lacks\n * (or no manifest) is bundled from source once. Elsewhere it is bundled on\n * first use and again only once the probe or a file it imports has changed.\n * Throws when there is no such file or it does not bundle.\n */\nexport async function probeSource(name: string): Promise<string> {\n assertName(name);\n const production = process.env.NODE_ENV === \"production\";\n if (production) {\n const fromBuild = builtProbes()?.[name];\n if (fromBuild !== undefined) return fromBuild;\n }\n const cached = cache.get(name);\n if (cached && (cached.stamps === null || !stale(cached.stamps))) {\n return (await cached.pending).source;\n }\n const file = probeFile(join(projectRoot(), \"app\"), name);\n if (!file) {\n throw new Error(\n `The probe \"${name}\" was not found. It is a file at app/${name}${PROBE_SUFFIX}.ts (or .js).`,\n );\n }\n const startedAt = Date.now();\n const entry: Cached = { pending: bundle(file), stamps: null };\n cache.set(name, entry);\n try {\n const bundled = await entry.pending;\n if (!production) {\n // A file changed while it bundled may not be in the bundle: such a\n // stamp never matches, so the next use bundles again.\n entry.stamps = new Map(\n bundled.inputs.map((input) => {\n const mtime = mtimeOf(input);\n return [input, mtime >= startedAt ? -2 : mtime];\n }),\n );\n }\n return bundled.source;\n } catch (error) {\n if (cache.get(name) === entry) cache.delete(name);\n throw error;\n }\n}\n\n/**\n * A JavaScript expression that runs the bundled probe `source` with `args`\n * and evaluates to what it returns (a promise, for an async probe).\n */\nexport function probeExpression(source: string, args: readonly unknown[]): string {\n const json = JSON.stringify(args);\n if (json === undefined) throw new Error(\"A probe's arguments must be JSON values.\");\n // The local names start with `__gemi` so they shadow none of the page's globals the bundle may use.\n return `(() => { let __gemiProbeFn__; const ${DEFINE} = (fn) => { __gemiProbeFn__ = fn; }; ${source}; return __gemiProbeFn__(...${json}); })()`;\n}\n\n/** Anything that evaluates an expression in a page: a puppeteer or playwright `Page`. */\nexport interface ProbePage {\n evaluate(expression: string): Promise<unknown>;\n}\n\n/** The probe function, from its module's type or its own. */\ntype ProbeFunctionOf<M> = M extends { default: infer F } ? F : M;\ntype AnyFunction = (...args: any[]) => unknown;\ntype ArgsOf<F> = F extends AnyFunction ? Parameters<F> : never;\ntype ResultOf<F> = F extends AnyFunction ? Awaited<ReturnType<F>> : never;\n\nexport class Probe<M = AnyFunction> {\n constructor(readonly name: string) {\n assertName(name);\n }\n\n /** The bundled IIFE. */\n source(): Promise<string> {\n return probeSource(this.name);\n }\n\n /**\n * An expression that runs the probe with `args`, for a driver that takes a\n * script string. The arguments must be JSON values.\n */\n async expression(...args: ArgsOf<ProbeFunctionOf<M>>): Promise<string> {\n return probeExpression(await this.source(), args);\n }\n\n /** Runs the probe in `page` with `args` and returns its (awaited) result. */\n async run(page: ProbePage, ...args: ArgsOf<ProbeFunctionOf<M>>): Promise<ResultOf<ProbeFunctionOf<M>>> {\n return (await page.evaluate(await this.expression(...args))) as ResultOf<ProbeFunctionOf<M>>;\n }\n}\n\n/**\n * The probe at `app/<name>.probe.ts`, typed by its module:\n *\n * ```ts\n * const readLayout = probe<typeof import(\"@/app/utils/layout.probe\")>(\"utils/layout\");\n * const reading = await readLayout.run(page, sections);\n * ```\n */\nexport function probe<M = AnyFunction>(name: string): Probe<M> {\n return new Probe<M>(name);\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";4EAAA,gBAAS,kBAAY,cAAc,WACnC,eAAS,aAAM,aAuBR,IAAM,EAAe,SACtB,EAAa,CAAC,MAAO,KAAK,EAEnB,EAAkB,cAGzB,EAAS,gBAET,EAAQ,2BAGR,EAAO,sCAEb,SAAS,CAAU,CAAC,EAAc,CAChC,GAAI,OAAO,IAAS,UAAY,CAAC,EAAK,KAAK,CAAI,EAC7C,MAAU,MACR,oGAAoG,KAAK,UAAU,CAAI,IACzH,EAKG,SAAS,CAAS,CAAC,EAAgB,EAA6B,C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AAI,CAAC,IAAU,CAC5B,IAAM,EAAQ,EAAQ,CAAK,EAC3B,MAAO,CAAC,EAAO,GAAS,EAAY,GAAK,CAAK,EAC/C,CACH,EAEF,OAAO,EAAQ,OACf,MAAO,EAAO,CACd,GAAI,EAAM,IAAI,CAAI,IAAM,EAAO,EAAM,OAAO,CAAI,EAChD,MAAM,GAQH,SAAS,CAAe,CAAC,EAAgB,EAAkC,CAChF,IAAM,EAAO,KAAK,UAAU,CAAI,EAChC,GAAI,IAAS,OAAW,MAAU,MAAM,0CAA0C,EAElF,MAAO,uCAAuC,0CAA+C,gCAAqC,WAc7H,MAAM,CAAuB,CACb,KAArB,WAAW,CAAU,EAAc,CAAd,YACnB,EAAW,CAAI,EAIjB,MAAM,EAAoB,CACxB,OAAO,EAAY,KAAK,IAAI,OAOxB,WAAU,IAAI,EAAmD,CACrE,OAAO,EAAgB,MAAM,KAAK,OAAO,EAAG,CAAI,OAI5C,IAAG,CAAC,KAAoB,EAAyE,CACrG,OAAQ,MAAM,EAAK,SAAS,MAAM,KAAK,WAAW,GAAG,CAAI,CAAC,EAE9D,CAUO,SAAS,CAAsB,CAAC,EAAwB,CAC7D,OAAO,IAAI,EAAS,CAAI",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "3F9AB2E4A4EFF40364756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Da as f}from"../chunk-s0z61m9j.js";import{Ea as S}from"../chunk-
|
|
2
|
+
import{Da as f}from"../chunk-s0z61m9j.js";import{Ea as S}from"../chunk-m4r8btey.js";import{Bl as Z,Cl as P,Dl as y,El as U,Fl as A,zl as Q}from"../chunk-f02anz24.js";import{Jl as H}from"../chunk-fryj3asn.js";import"../chunk-y67rmd3y.js";import{Rl as F}from"../chunk-k1c0xd8r.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new S({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=U(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)A(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-mx9zcq7w.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-qg60pgve.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{W as liveness,Q as isShuttingDown,k as Server};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=7228D9637EA357D964756E2164756E21
|
package/dist/server/index.js.map
CHANGED
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import { App } from \"../app\";\nimport { Kernel } from \"../kernel\";\nimport { projectRoot } from \"../support/discover\";\nimport { healthSettings, serveHealth, startLivenessSampler } from \"./health\";\nimport { DevGeneration, devRetireDefaults, replaceDevGeneration } from \"./devReload\";\nimport {\n drain,\n installShutdownSignals,\n serveForShutdown,\n shutdownSettings,\n type ShutdownSettings,\n} from \"./shutdown\";\nimport { Instrumentation } from \"./types\";\nimport { watchEnv } from \"./watchEnv\";\n\nexport class Server {\n private app: App;\n private instrumentation: Instrumentation;\n private handleSignals: boolean;\n private server: Bun.Server<unknown> | undefined;\n private stopping: Promise<number> | undefined;\n private settings: ShutdownSettings | undefined;\n\n constructor(params: {\n kernel: new () => Kernel;\n instrumentation?: Instrumentation;\n /**\n * Drain on `SIGTERM`/`SIGINT` and exit — production only. `false` leaves\n * the signals to the app, which can call `stop()` itself.\n */\n handleSignals?: boolean;\n }) {\n this.app = new App({ kernel: params.kernel });\n this.handleSignals = params.handleSignals ?? true;\n this.instrumentation = serveForShutdown(\n params.instrumentation ??\n ((req: Request, next: (req: Request) => Promise<Response>) => next(req)),\n );\n }\n\n /**\n * Boots the application and starts listening. Resolves with the `Bun.Server`\n * once it is accepting requests.\n */\n async start(): Promise<Bun.Server<unknown>> {\n // Before the boot, not after: `httpDev`/`httpProd` set this too, but they\n // are imported below — after every provider's `boot()` has run — so a\n // service that resolves a path during boot used to read `undefined`\n // (`services/logging`, #423). Same rule `httpProd` computes it with, so\n // the assignment it makes a moment later is the same value.\n //\n // It doubles as the marker for \"this process is serving\": nothing else\n // sets `ROOT_DIR`, so a console command or a migration — which boot the\n // same providers through `runConsole` — can tell that it is not one, and\n // skip work that only a server should do at boot.\n process.env.ROOT_DIR = projectRoot();\n\n // Read once, ahead of the boot, so the signal handling below and the mode\n // that starts after the boot cannot disagree: whatever a provider's\n // `boot()` does to the environment, this process is the server it was\n // started as.\n const production = process.env.NODE_ENV === \"production\";\n\n // Read before the boot, so a bad `GEMI_HEALTH_PATH` fails the deploy at\n // once. The route is served in both modes; the lag sampler runs only in\n // production, where a `bun --hot` reload or a Vite compile cannot stall\n // the loop and read as an outage.\n const health = healthSettings();\n if (production) startLivenessSampler(health);\n // The outermost layer: a probe is answered ahead of the app's\n // instrumentation and the shutdown refusal (#48).\n const instrumentation = serveHealth(this.instrumentation, health.paths);\n\n if (production) {\n // Before the boot, not just before listening: the whole start-up is a\n // window in which a signal can arrive, and the slow part of it is the\n // boot — a connection pool, the config, the dictionaries. A rolling\n // update that `SIGTERM`s a pod two seconds in finds no listener\n // installed, and the default action for both signals is to kill the\n // process on the spot: no provider's `shutdown()`, no pool closed,\n // nothing flushed. Installing here makes that a drain like any other.\n // `stop()` handles a server that does not exist yet (nothing to close,\n // requests cannot be in flight) and `Application.shutdown` calls the\n // hooks of providers that registered but never booted, swallowing\n // whatever they throw — half a boot is exactly when a hook is most\n // likely to trip over something it expected `boot()` to have made.\n if (this.handleSignals) installShutdownSignals(() => this.stop());\n // Read now, so a bad value is warned about while the operator is\n // watching the deploy, not first at the shutdown it spoils — and so a\n // signal during the boot drains on the configured budget rather than on\n // whatever `stop()` reads at the time.\n this.settings = shutdownSettings();\n }\n\n // Phase two of the boot. `new App({ kernel })` already ran every provider's\n // synchronous `register()`; this awaits their `boot()` before the first\n // request is served.\n try {\n await this.app.waitForBoot();\n } catch (error) {\n // A `bun --hot` reload whose boot threw: the previous application keeps\n // serving, and this one never will, so whatever its providers opened\n // before the throw (the feature flags' warm-up, when they are on, has\n // opened the database pool by then) is closed now rather than left open\n // for good (#652). Production exits on a failed boot, which closes\n // everything anyway.\n if (!production) void this.app.shutdown({ timeoutMs: devRetireDefaults.providerTimeoutMs });\n throw error;\n }\n\n // Dynamic import so each mode only pulls in its own code: `httpDev` drags in\n // Vite (dev-only) and `httpProd` reads the built `dist/` manifests — neither\n // should load in the other environment.\n if (production) {\n const { httpProd } = await import(\"./httpProd.js\");\n this.server = await httpProd(this.app, instrumentation);\n } else {\n // Dev only: reload `.env` into process.env on change so config edits take\n // effect without restarting the dev server (Bun reads `.env` only at\n // startup, even under `--hot`). No signal handling here: `bun --hot`\n // re-runs this on every reload, and a Ctrl+C in development should stop\n // the server now, not after a drain.\n watchEnv();\n const { httpDev } = await import(\"./httpDev.js\");\n const generation = new DevGeneration(this.app);\n this.server = await httpDev(this.app, generation.track(instrumentation));\n // Only now, with the new fetch handler live, has the application this\n // reload replaced stopped receiving requests; it is shut down once the\n // ones it is serving finish (#652). Not awaited, so the reload is not\n // held up by it.\n void replaceDevGeneration(generation);\n }\n return this.server;\n }\n\n /**\n * Stops the server gracefully and resolves with the exit code it earned: 0\n * when the in-flight requests drained and every provider shut down in time,\n * 1 otherwise. Does not exit the process — the signal handler does that.\n *\n * The order is `drain` in `./shutdown`: `isShuttingDown()` turns true, the\n * listener closes, in-flight requests finish under the grace period, then\n * every provider's `shutdown()` runs in reverse registration order.\n * Idempotent: a second call returns the first call's promise. Settings\n * default to the `GEMI_SHUTDOWN_*` environment variables.\n */\n stop(settings: Partial<ShutdownSettings> = {}): Promise<number> {\n const sockets = this.app.sockets();\n this.stopping ??= drain({\n server: this.server,\n // Once the listener is closed: `bye` to every broadcast socket, which\n // the graceful stop would otherwise wait on for good.\n closeSockets: sockets ? () => sockets.shutdown() : undefined,\n shutdownProviders: (options) => this.app.shutdown(options),\n settings: { ...(this.settings ?? shutdownSettings()), ...settings },\n });\n return this.stopping;\n }\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";gTAiCO,DAAM,HAAsB,cAK7B,HAAQ,EAAO,IAAI,oBAAoB,EAS7C,SA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EASjC,OARA,KAAK,WAAa,EAAM,CACtB,OAAQ,KAAK,OAGb,aAAc,EAAU,IAAM,EAAQ,SAAS,EAAI,OACnD,kBAAmB,CAAC,IAAY,KAAK,IAAI,SAAS,CAAO,EACzD,SAAU,IAAM,KAAK,UAAY,EAAiB,KAAO,CAAS,CACpE,CAAC,EACM,KAAK,SAEhB",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "7228D9637EA357D964756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{db as k9}from"../chunk-8m9kgynj.js";import{Ab as J9,Bb as Q9,Cb as Y9,Db as K9,Eb as z9,Fb as y4,Gb as O6,Hb as w,Ib as G9,Jb as X9,Kb as B9,Lb as j9,Mb as F9,Nb as M9,Ob as L9,Pb as N9,Qb as D9,Rb as H9,Sb as U9,Tb as x9,Ub as O9,Vb as S9,Wb as R9,Xb as _9,eb as _Z,fb as kZ,gb as fZ,hb as CZ,ib as VZ,jb as w4,kb as TZ,lb as V4,mb as T4,nb as g1,ob as PZ,pb as bZ,qb as sZ,ub as oZ,vb as aZ,wb as tZ,xb as rZ,yb as Z9,zb as $9}from"../chunk-2v7a5wv6.js";import{_b as v4}from"../chunk-71jcjnwk.js";import{Bd as wZ,Cd as qZ,Dd as vZ,Ed as IZ,Fd as yZ,Gd as hZ,Hd as gZ,Id as EZ,Jd as mZ,Kd as cZ,Ld as uZ,Md as pZ,Nd as dZ,Od as lZ,Pd as nZ,Qd as iZ}from"../chunk-790dx3s7.js";import{Rd as AZ}from"../chunk-495k9h6p.js";import{$d as NZ,Sd as KZ,Td as zZ,Ud as GZ,Vd as XZ,Wd as BZ,Xd as jZ,Yd as FZ,Zd as MZ,_d as LZ,ae as DZ,be as HZ,ce as UZ,de as xZ,ee as OZ,fe as SZ,ke as RZ}from"../chunk-baknm4tn.js";import{le as eZ,me as W9}from"../chunk-dsgjdk94.js";import"../chunk-xpkpz4g6.js";import{$e as h5,$f as b8,Af as B8,Ag as s8,Be as _5,Bf as j8,Bg as o8,Cf as F8,Cg as a8,Df as M8,Ef as L8,Fe as M6,Ff as N8,Ge as H4,Gf as D8,He as r0,Hf as H8,Ie as U4,Je as x4,Jf as U8,Jg as t8,Kf as x6,Lf as x8,Ne as k5,Ng as r8,Oe as f5,Pe as C5,Pf as O8,Qe as V5,Qf as S8,Re as T5,Rf as _8,Rg as A4,Se as P5,Sg as E1,Te as b5,Ue as w5,Uf as k8,Ve as q5,Vf as f8,We as l0,Wf as C8,Xe as v5,Xf as V8,Ye as I5,Ze as y5,Zf as T8,_e as A5,_f as P8,ag as w8,bg as q8,bh as e8,cg as v8,ch as WZ,dg as I8,eg as y8,fg as A8,gg as h8,lg as U,mg as m,ng as g8,of as n5,og as E8,pf as i5,pg as m8,qf as s5,qg as c8,rf as o5,rg as u8,sf as a5,tf as t5,tg as p8,ug as d8,vg as l8,we as F6,wg as n8,xe as O5,xg as i8,ye as S5,ze as R5,zf as X8}from"../chunk-8f8bp75w.js";import"../chunk-yt5n62nj.js";import"../chunk-eqnrk0p8.js";import{Ai as u5,Mi as jW,Ni as FW,Qi as p5,Ri as d5,Ti as l5,Vi as I1,Wh as D4,Xh as M4,Yh as D1,ji as C4,ni as $1,pi as a,ti as L4,ui as H1,vi as v1,wi as g5,xi as E5,yi as m5,zi as c5}from"../chunk-1987f978.js";import"../chunk-8b897pc1.js";import{dj as V}from"../chunk-bwmyd47e.js";import{lj as Q8,mj as Y8,nj as w1,oj as K8,pj as m0,qj as z8,rj as G8}from"../chunk-7des5zys.js";import{xj as Z8,yj as $8,zj as J8}from"../chunk-epb0qfce.js";import"../chunk-2k948anx.js";import{gk as R8}from"../chunk-cbw4676x.js";import{ik as r5,jk as e5,kk as W8}from"../chunk-khzss89b.js";import"../chunk-xqzrd7st.js";import"../chunk-fgk1e5xe.js";import"../chunk-yn2av14e.js";import"../chunk-vzzt4kpk.js";import{al as ZZ,bl as $Z,cl as JZ,dl as QZ,fl as YZ}from"../chunk-s5z8qcdv.js";import"../chunk-x1ng1dnx.js";import{pl as C}from"../chunk-nc37phkt.js";import"../chunk-6tsyk2mr.js";import"../chunk-0gvw46j0.js";import"../chunk-6a3t825g.js";import"../chunk-h8knqrc5.js";import"../chunk-s91xa67z.js";import{Ql as i0}from"../chunk-80kpxp4m.js";import{Buffer as n0}from"buffer";class s0 extends H1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-6bhscseq.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof n0?$:$ instanceof Blob||$ instanceof File?n0.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){L4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let G=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),z=v1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),z;try{z=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?M4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new $1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new a(J);throw j}let G=D1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new a(Z);throw Y}}}import{Buffer as o0}from"buffer";import{Readable as NW}from"stream";function N4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function DW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class a0 extends H1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof o0?$:o0.from(await $.arrayBuffer()),z=await this.blob(Q,Y);return Z?.throwIfAborted(),await z.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,z,G=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&G){let S=await this.size({name:$,bucket:J}),o=D4(Q,S);if(!o)throw new $1(S);K=o.start,z=o.length}else if(Q?.kind==="offset")K=Q.start,z=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,z,Z?{abortSignal:Z}:void 0)}catch(S){if(DW(S))throw new $1(await this.size({name:$,bucket:J}));if(N4(S))throw new a($);throw S}let B=D1(X.contentRange),j=Boolean(B),L=B?.total??X.contentLength??0,H=await HW(X);if(H instanceof ReadableStream)H=v1(H,Z);return Z?.throwIfAborted(),{body:H,start:B?.start??0,end:B?.end??L-1,total:L,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(N4(Q))throw new a(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(N4(Q))return;throw Q}}}async function HW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return NW.toWeb(W.readableStreamBody);return null}function UW(W){return W}class O4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class y1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var t0=1000,xW=60000,OW=`
|
|
2
|
+
import{db as k9}from"../chunk-8m9kgynj.js";import{Ab as J9,Bb as Q9,Cb as Y9,Db as K9,Eb as z9,Fb as y4,Gb as O6,Hb as w,Ib as G9,Jb as X9,Kb as B9,Lb as j9,Mb as F9,Nb as M9,Ob as L9,Pb as N9,Qb as D9,Rb as H9,Sb as U9,Tb as x9,Ub as O9,Vb as S9,Wb as R9,Xb as _9,eb as _Z,fb as kZ,gb as fZ,hb as CZ,ib as VZ,jb as w4,kb as TZ,lb as V4,mb as T4,nb as g1,ob as PZ,pb as bZ,qb as sZ,ub as oZ,vb as aZ,wb as tZ,xb as rZ,yb as Z9,zb as $9}from"../chunk-7k43y71n.js";import{_b as v4}from"../chunk-bd14zwmj.js";import{Bd as wZ,Cd as qZ,Dd as vZ,Ed as IZ,Fd as yZ,Gd as hZ,Hd as gZ,Id as EZ,Jd as mZ,Kd as cZ,Ld as uZ,Md as pZ,Nd as dZ,Od as lZ,Pd as nZ,Qd as iZ}from"../chunk-67zz58cw.js";import{Rd as AZ}from"../chunk-495k9h6p.js";import{$d as NZ,Sd as KZ,Td as zZ,Ud as GZ,Vd as XZ,Wd as BZ,Xd as jZ,Yd as FZ,Zd as MZ,_d as LZ,ae as DZ,be as HZ,ce as UZ,de as xZ,ee as OZ,fe as SZ,ke as RZ}from"../chunk-6rmz0mkm.js";import{le as eZ,me as W9}from"../chunk-24jgzc8y.js";import"../chunk-xpkpz4g6.js";import{$e as h5,$f as b8,Af as B8,Ag as s8,Be as _5,Bf as j8,Bg as o8,Cf as F8,Cg as a8,Df as M8,Ef as L8,Fe as M6,Ff as N8,Ge as H4,Gf as D8,He as r0,Hf as H8,Ie as U4,Je as x4,Jf as U8,Jg as t8,Kf as x6,Lf as x8,Ne as k5,Ng as r8,Oe as f5,Pe as C5,Pf as O8,Qe as V5,Qf as S8,Re as T5,Rf as _8,Rg as A4,Se as P5,Sg as E1,Te as b5,Ue as w5,Uf as k8,Ve as q5,Vf as f8,We as l0,Wf as C8,Xe as v5,Xf as V8,Ye as I5,Ze as y5,Zf as T8,_e as A5,_f as P8,ag as w8,bg as q8,bh as e8,cg as v8,ch as WZ,dg as I8,eg as y8,fg as A8,gg as h8,lg as U,mg as m,ng as g8,of as n5,og as E8,pf as i5,pg as m8,qf as s5,qg as c8,rf as o5,rg as u8,sf as a5,tf as t5,tg as p8,ug as d8,vg as l8,we as F6,wg as n8,xe as O5,xg as i8,ye as S5,ze as R5,zf as X8}from"../chunk-8zeky0fj.js";import"../chunk-199nvtrj.js";import"../chunk-xwz5fmwy.js";import{Ai as u5,Mi as jW,Ni as FW,Qi as p5,Ri as d5,Ti as l5,Vi as I1,Wh as D4,Xh as M4,Yh as D1,ji as C4,ni as $1,pi as a,ti as L4,ui as H1,vi as v1,wi as g5,xi as E5,yi as m5,zi as c5}from"../chunk-ryfty6mj.js";import"../chunk-xsx69765.js";import{ej as V}from"../chunk-rf9c6e49.js";import{mj as Q8,nj as Y8,oj as w1,pj as K8,qj as m0,rj as z8,sj as G8}from"../chunk-7zpjdwfq.js";import{Aj as J8,yj as Z8,zj as $8}from"../chunk-5zx4e2wa.js";import"../chunk-vr48swd0.js";import{hk as R8}from"../chunk-tngf3h1g.js";import{jk as r5,kk as e5,lk as W8}from"../chunk-9dfrsj4m.js";import"../chunk-ce73s4kh.js";import"../chunk-4s7st9y4.js";import"../chunk-8em2ebj1.js";import"../chunk-h688s2ba.js";import{bl as ZZ,cl as $Z,dl as JZ,el as QZ,gl as YZ}from"../chunk-67ex6nem.js";import"../chunk-ccx7rt7y.js";import{ql as C}from"../chunk-8pfy75y6.js";import"../chunk-ejc0mbe3.js";import"../chunk-6n44t4hn.js";import"../chunk-f02anz24.js";import"../chunk-fryj3asn.js";import"../chunk-y67rmd3y.js";import{Rl as i0}from"../chunk-k1c0xd8r.js";import{Buffer as n0}from"buffer";class s0 extends H1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-sqev442x.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof n0?$:$ instanceof Blob||$ instanceof File?n0.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){L4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let G=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),z=v1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),z;try{z=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?M4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new $1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new a(J);throw j}let G=D1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new a(Z);throw Y}}}import{Buffer as o0}from"buffer";import{Readable as NW}from"stream";function N4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function DW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class a0 extends H1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof o0?$:o0.from(await $.arrayBuffer()),z=await this.blob(Q,Y);return Z?.throwIfAborted(),await z.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,z,G=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&G){let S=await this.size({name:$,bucket:J}),o=D4(Q,S);if(!o)throw new $1(S);K=o.start,z=o.length}else if(Q?.kind==="offset")K=Q.start,z=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,z,Z?{abortSignal:Z}:void 0)}catch(S){if(DW(S))throw new $1(await this.size({name:$,bucket:J}));if(N4(S))throw new a($);throw S}let B=D1(X.contentRange),j=Boolean(B),L=B?.total??X.contentLength??0,H=await HW(X);if(H instanceof ReadableStream)H=v1(H,Z);return Z?.throwIfAborted(),{body:H,start:B?.start??0,end:B?.end??L-1,total:L,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(N4(Q))throw new a(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(N4(Q))return;throw Q}}}async function HW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return NW.toWeb(W.readableStreamBody);return null}function UW(W){return W}class O4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class y1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var t0=1000,xW=60000,OW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -69,4 +69,4 @@ ${W.resolution}.`;console.warn($),console.warn("To disable this message, import
|
|
|
69
69
|
`));return await this.put(Z.data.upload_url,$,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),Z}async complianceJobResult(W){let Z=W;while(Z.status!=="complete"){if(Z.status==="expired"||Z.status==="failed")throw Error("Job failed to be completed.");await new Promise((J)=>setTimeout(J,3500)),Z=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
|
|
70
70
|
`).filter((J)=>J).map((J)=>JSON.parse(J))}async usage(W={}){return this.get("usage/tweets",W)}community(W,Z={}){return this.get("communities/:id",Z,{params:{id:W}})}searchCommunities(W,Z={}){return this.get("communities/search",{query:W,...Z})}}class L1 extends F1{constructor(){super(...arguments);this._prefix=J1}get readOnly(){return this}}class N1 extends M1{constructor(){super(...arguments);this._prefix=d}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new L1(this)}hideReply(W,Z){return this.put("tweets/:id/hidden",{hidden:Z},{params:{id:W}})}like(W,Z){return this.post("users/:id/likes",{tweet_id:Z},{params:{id:W}})}unlike(W,Z){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}retweet(W,Z){return this.post("users/:id/retweets",{tweet_id:Z},{params:{id:W}})}unretweet(W,Z){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}tweet(W,Z={}){if(typeof W==="object")Z=W;else Z={text:W,...Z};return this.post("tweets",Z)}async uploadMedia(W,Z,$=1048576){let J=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))J="tweet_gif";else if(Z.media_type.includes("image"))J="tweet_image";else if(Z.media_type.includes("video"))J="tweet_video"}let Q={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:J},K=(await this.post("media/upload/initialize",Q)).data.id,z=Math.ceil(W.length/$),G=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,L=Math.min(j+$,W.length),H=G.slice(j,L),S=Buffer.from(H),o={segment_index:B,media:S};await this.post(`media/upload/${K}/append`,o,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${K}/finalize`)).data.processing_info)await this.waitForMediaProcessing(K);return K}async waitForMediaProcessing(W){var Z;let J=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!J)return;switch(J.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=J.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Q=J===null||J===void 0?void 0:J.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var J;let Q={in_reply_to_tweet_id:Z,...(J=$.reply)!==null&&J!==void 0?J:{}};return this.post("tweets",{text:W,...$,reply:Q})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let J=[];for(let Q of W){let Y=J.length?J[J.length-1]:null,K={...typeof Q==="string"?{text:Q}:Q},z=Y?Y.data.id:(Z=K.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,G=($=K.text)!==null&&$!==void 0?$:"";if(z)J.push(await this.reply(G,z,K));else J.push(await this.tweet(G,K))}return J}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let Z=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:Z.data.id}})}async deleteBookmark(W){let Z=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:Z.data.id,tweet_id:W}})}follow(W,Z){return this.post("users/:id/following",{target_user_id:Z},{params:{id:W}})}unfollow(W,Z){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}block(W,Z){return this.post("users/:id/blocking",{target_user_id:Z},{params:{id:W}})}unblock(W,Z){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}mute(W,Z){return this.post("users/:id/muting",{target_user_id:Z},{params:{id:W}})}unmute(W,Z){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}createList(W){return this.post("lists",W)}updateList(W,Z={}){return this.put("lists/:id",Z,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,Z){return this.post("lists/:id/members",{user_id:Z},{params:{id:W}})}removeListMember(W,Z){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:Z}})}subscribeToList(W,Z){return this.post("users/:id/followed_lists",{list_id:Z},{params:{id:W}})}unsubscribeOfList(W,Z){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}pinList(W,Z){return this.post("users/:id/pinned_lists",{list_id:Z},{params:{id:W}})}unpinList(W,Z){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}sendDmInConversation(W,Z){return this.post("dm_conversations/:dm_conversation_id/messages",Z,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,Z){return this.post("dm_conversations/with/:participant_id/messages",Z,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class l6 extends L1{constructor(){super(...arguments);this._prefix=J1}get readWrite(){return this}}var n6=l6;class i6 extends N1{constructor(){super(...arguments);this._prefix=d}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new n6(this)}}var s6=i6;class P1 extends i{get v1(){if(this._v1)return this._v1;return this._v1=new X1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new M1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,Z){return this.v2.search(W,Z)}async generateAuthLink(W="oob",{authAccessType:Z,linkMode:$="authenticate",forceLogin:J,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),K=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if(J!==void 0)K+=`&force_login=${encodeURIComponent(J)}`;if(Q!==void 0)K+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:K,oauthResult:Y});return{url:K,...Y}}async login(W){let Z=this.getActiveTokens();if(Z.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let $=await this.post("https://api.x.com/oauth/access_token",{oauth_token:Z.accessToken,oauth_verifier:W}),J=new this.constructor({appKey:Z.appKey,appSecret:Z.appSecret,accessToken:$.oauth_token,accessSecret:$.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:$.oauth_token,accessSecret:$.oauth_token_secret,userId:$.user_id,screenName:$.screen_name,client:J}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let $=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor($.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,Z={}){var $,J;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Q=($=Z.state)!==null&&$!==void 0?$:Z1.generateRandomString(32),Y=Z1.getCodeVerifier(),K=Z1.getCodeChallengeFromVerifier(Y),z=(J=Z.scope)!==null&&J!==void 0?J:"",G=Array.isArray(z)?z.join(" "):z,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Q,code_challenge:K,code_challenge_method:"s256",scope:G};T.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Q,codeVerifier:Y,codeChallenge:K};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:j,redirectUri:W});return j}async loginWithOAuth2({code:W,codeVerifier:Z,redirectUri:$}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let J=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:Z,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(J)}async refreshOAuth2Token(W){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Z=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Z)}async revokeOAuth2Token(W,Z="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:W,token_type_hint:Z})}parseOAuth2AccessTokenResult(W){let Z=new this.constructor(W.access_token,this._requestMaker.clientSettings),$=W.scope.split(" ").filter((J)=>J);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class b1 extends P1{get v1(){if(this._v1)return this._v1;return this._v1=new B1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new N1(this)}get readOnly(){return this}}class J4 extends P{constructor(){super(...arguments);this._prefix=Q1}}class Q4 extends J4{constructor(){super(...arguments);this._prefix=Q1}get readOnly(){return this}}class Y4 extends P{constructor(){super(...arguments);this._prefix=Y1}}class K4 extends Y4{constructor(){super(...arguments);this._prefix=Y1}get readOnly(){return this}}class o6 extends K4{constructor(){super(...arguments);this._prefix=Y1}get readWrite(){return this}}var a6=o6;class t6 extends Q4{constructor(){super(...arguments);this._prefix=Q1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new a6(this)}}var r6=t6;class z4 extends b1{get v1(){if(this._v1)return this._v1;return this._v1=new e1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new s6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new r6(this)}static getErrors(W){var Z;if(typeof W!=="object")return[];if(!("data"in W))return[];return(Z=W.data.errors)!==null&&Z!==void 0?Z:[]}static getProfileImageInSize(W,Z){let $=W.split("/").pop(),J=["normal","bigger","mini"],Q=W;for(let K of J)if($.includes(`_${K}`)){Q=W.replace(`_${K}`,"");break}if(Z==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let K=Q.slice(Y+1);return Q.slice(0,Y)+"_"+Z+"."+K}else return Q+"_"+Z}}var W5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class e6 extends m{config;client;constructor(W={}){super();this.config={...W5,...W},this.client=new z4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("XOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL("https://x.com/i/oauth2/authorize"),J={response_type:"code",client_id:W.clientId,redirect_uri:W.redirectUri,state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");if(!Z?.codeVerifier)throw new U("invalid_state");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=this.config.resolve?new z4({clientId:J.clientId,clientSecret:J.clientSecret}):this.client,Y;try{Y=await Q.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:J.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new U("exchange_failed")}let{data:K}=await Y.client.v2.me({"user.fields":["name","username","entities"]}),{name:z,email:G,id:X="",username:B}=K??{};return{name:z,email:G,username:B,providerId:X}}}var ZW=["instagram_business_basic"],g={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class I extends Error{status;type;code;constructor(W,Z,$,J,Q){super(W,Q);this.status=Z;this.type=$;this.code=J;this.name="InstagramApiError"}}async function G4(W){let Z=new URLSearchParams({client_id:W.clientId,client_secret:W.clientSecret,grant_type:"authorization_code",redirect_uri:W.redirectUri,code:W.code.replace(/#_$/,"")}),$=await B4(W.tokenUrl??g.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),J=Array.isArray($.data)?$.data[0]:$,Q=J?.access_token;if(typeof Q!=="string"||Q==="")throw new I("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:g0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function $W(W){let Z=new URL("/access_token",W.graphUrl??g.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),QW(await B4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function JW(W){let Z=new URL("/refresh_access_token",W.graphUrl??g.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),QW(await B4(Z.toString(),"token refresh",{method:"GET"}))}async function X4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??g.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let J=await B4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=g0(Q?.user_id);if(!Y)throw new I("Instagram's /me answered without a user_id.",200);let K={user_id:Y},z=g0(Q?.id);if(z)K.id=z;for(let G of["username","name","account_type","profile_picture_url"]){let X=Q?.[G];if(typeof X==="string"&&X!=="")K[G]=X}return K}function QW(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new I("Instagram answered without an access token.",200);let Z=Number(W.expires_in);return{accessToken:W.access_token,tokenType:typeof W.token_type==="string"?W.token_type:null,expiresIn:Number.isFinite(Z)&&Z>0?Z:null}}async function B4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new I(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=E0(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=WW(Q.error_type)??WW(Y.type),z=Number(Q.code??Y.code);throw new I(`Instagram refused the ${Z} (HTTP ${J.status}${K?`, ${K}`:""}${Number.isFinite(z)?` ${z}`:""}).`,J.status,K,Number.isFinite(z)?z:void 0)}return Q}function E0(W){try{let Z=JSON.parse(W.replace(/("(?:user_id|id)"\s*:\s*)(-?\d+)(?=\s*[,}\]])/g,'$1"$2"'));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}function g0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function WW(W){return typeof W==="string"&&W!==""?W:void 0}class YW extends m{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:ZW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("InstagramOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(this.config.authorizeUrl??g.authorizeUrl),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)J.state=Z.state;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new U("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new U("unknown_provider");let J;try{let Q=await G4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});J=await X4({accessToken:Q.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Q){if(Q instanceof I)throw console.error(`Instagram OAuth error: ${Q.message}`),new U("exchange_failed");throw Q}return{providerId:J.user_id,username:J.username,name:J.name||J.username}}}import{createHmac as Z5,timingSafeEqual as $5}from"crypto";class y extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function J5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new y("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new y("malformed","A signed_request is <signature>.<payload>.");let Q=W.slice(0,J),Y=W.slice(J+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Q)||!/^[A-Za-z0-9_-]+={0,2}$/.test(Y))throw new y("malformed","A signed_request is base64url.");let K=Z5("sha256",Z).update(Y).digest(),z=Buffer.from(Q,"base64url");if(z.length!==K.length||!$5(z,K))throw new y("bad_signature","The signed_request's signature does not match the app secret.");let G;try{let L=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');G=JSON.parse(L)}catch{throw new y("malformed","The signed_request's payload is not JSON.")}if(!G||typeof G!=="object")throw new y("malformed","The signed_request's payload is not an object.");if(String(G.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new y("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(G.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new y("expired","The signed_request has expired.");let j=G.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new y("missing_user","The signed_request names no user.");return{...G,algorithm:String(G.algorithm),user_id:String(j)}}var Q5=86400000;class F4 extends m0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??g.authorizeUrl,tokenUrl:W.tokenUrl??g.tokenUrl,graphUrl:W.graphUrl??g.graphUrl,graphApiVersion:W.graphApiVersion};super({authorizeUrl:Z.authorizeUrl,tokenUrl:Z.tokenUrl,clientId:W.clientId??process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:W.scopes??["instagram_business_basic","instagram_business_content_publish"],scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,apiBaseUrl:Z.graphUrl,refreshLeewaySeconds:W.refreshLeewaySeconds??864000,multiple:W.multiple??!1,tokenPlacement:"query",isTokenRejected:Y5,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<Q5){if($.reason==="rejected")throw new w1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await j4("refresh_failed",()=>JW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:J.accessToken,refreshToken:null,tokenType:J.tokenType,expiresAt:J.expiresIn===null?null:new Date(Date.now()+J.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await j4("exchange_failed",()=>G4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await j4("exchange_failed",()=>$W({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await j4("exchange_failed",()=>X4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new w1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function Y5(W){if(W.status===401)return!0;if(W.status!==400)return!1;let Z=await W.clone().json().catch(()=>null);return Number(Z?.error?.code)===190}async function j4(W,Z){try{return await Z()}catch($){if($ instanceof I)throw new w1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class O extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var f={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},KW="instagram_business_content_publish",K5={for(W,Z={}){return new p0(W,Z)}};class p0{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof F4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let J=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=J?`/${J.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(q1("imageUrl",W.imageUrl),u0(W.caption),W.altText!==void 0&&typeof W.altText!=="string")_("altText must be a string.");if(W.userTags!==void 0)U5(W.userTags);let $=this.start(Z),J=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(J,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<f.carouselMin||$.length>f.carouselMax)_(`A carousel takes ${f.carouselMin} to ${f.carouselMax} items.`);$.forEach((z,G)=>BW(`items[${G}]`,z)),u0(W.caption);let J=this.start(Z),Q=[];for(let z of $)Q.push(await this.createContainer(z.videoUrl!==void 0?{media_type:"VIDEO",video_url:z.videoUrl,is_carousel_item:"true"}:{image_url:z.imageUrl,is_carousel_item:"true"},J));for(let[z,G]of $.entries())if(G.videoUrl!==void 0)await this.waitUntilFinished(Q[z],J);let Y=$.some((z)=>z.videoUrl!==void 0),K=await this.createContainer({media_type:"CAROUSEL",children:Q.join(","),caption:W.caption},J);return this.publishContainer(K,Y,J)}async publishReel(W,Z={}){if(q1("videoUrl",W.videoUrl),W.coverUrl!==void 0)q1("coverUrl",W.coverUrl);if(u0(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))_("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),J=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(J,!0,$)}async publishStory(W,Z={}){BW("story",W);let $=this.start(Z),J=W.videoUrl!==void 0,Q=await this.createContainer(J?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Q,J,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),J=Array.isArray($.data)?$.data[0]:$,Q=J?.config??{},Y=c0(J?.quota_usage,0),K=c0(Q.quota_total,100);return{quotaUsage:Y,quotaTotal:K,quotaDurationSeconds:c0(Q.quota_duration,86400),remaining:Math.max(0,K-Y)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(KW))throw new O("permission_denied",`The Instagram connection was not granted ${KW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new O("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return GW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let J=await this.publishOnce(W,Z,$);return{mediaId:J,permalink:await this.permalink(J,$)}}catch(J){throw J instanceof O?D5(J,W):J}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(J){if(!(J instanceof O))throw J;if(J.code==="transient"){let{statusCode:Q}=await this.readStatus(W,$);if(Q==="PUBLISHED")throw new O("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:J.status,graphCode:J.graphCode,graphSubcode:J.graphSubcode});if(Q!=="FINISHED")throw J;return this.mediaPublish(W,$)}if(N5(J)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw J}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return GW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))_("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),J=$.status_code;if(typeof J!=="string"||!z5.has(J))throw new O("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Q={id:W,statusCode:J};if(typeof $.status==="string"&&$.status!=="")Q.status=MW($.status);return Q}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:J,status:Q}=await this.readStatus(W,Z);if(J==="FINISHED")return;if(J==="PUBLISHED")throw new O("invalid_input","That media container has been published already.",{containerId:W});if(J==="ERROR")throw new O("invalid_media",`Instagram could not process the media${Q?` (${Q})`:""}.`,{containerId:W});if(J==="EXPIRED")throw new O("expired","The media container expired before it was published.",{containerId:W});let Y=Z.deadline-Date.now();if(Y<=0)throw new O("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await H5(Math.min($,Y),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,J,{retry:Q=!0}={}){try{return await this.callOnce(W,Z,$,J)}catch(Y){if(!Q||!(Y instanceof O)||Y.code!=="transient")throw Y;return this.callOnce(W,Z,$,J)}}async callOnce(W,Z,$,J){J.signal?.throwIfAborted();let Q={method:$?"POST":"GET",signal:J.signal};if($){let z=new URLSearchParams;for(let[G,X]of Object.entries($))if(X!==void 0)z.set(G,X);Q.body=z}let Y;try{Y=await this.connection.fetch(`${this.version}${Z}`,Q)}catch(z){if(J.signal?.aborted)throw J.signal.reason;if(z instanceof TypeError)throw new O("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let K=E0(await Y.text().catch(()=>""));if(Y.ok)return K;throw L5(W,Y.status,K)}}var z5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),G5=new Set([4,17,32,613,80002]),X5=new Set([3,10]),B5=new Set([9004,352,36000,36001,36002,36003,36004]),j5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),F5=new Set([102,190,463,467]),M5=new Set([2207001,2207003,2207053]),zW={code:9007,subcode:2207027};function L5(W,Z,$){let J=$.error??{},Q=XW(J.code),Y=XW(J.error_subcode),K=typeof J.type==="string"&&J.type!==""?J.type:void 0,z=typeof J.message==="string"&&J.message!==""?`: ${MW(J.message)}`:"",G=[Q,Y].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${K?`, ${K}`:""}${G?` ${G}`:""})${z}`,B="graph_error";if(Y===2207042)B="quota_exceeded";else if(Y===2207010)B="invalid_input";else if(Q!==void 0&&G5.has(Q))B="rate_limited";else if(Q!==void 0&&F5.has(Q))B="reconnect_required";else if(Q!==void 0&&(X5.has(Q)||Q>=200&&Q<=299))B="permission_denied";else if(Q!==void 0&&B5.has(Q)||Y!==void 0&&j5.has(Y))B="invalid_media";else if(J.is_transient===!0||Q===1||Q===2||Y!==void 0&&M5.has(Y)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new O(B,X,{status:Z,graphCode:Q,graphSubcode:Y})}function N5(W){return W.graphCode===zW.code||W.graphSubcode===zW.subcode}function D5(W,Z){if(W.containerId)return W;return new O(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function MW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function GW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new O("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function XW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function c0(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function H5(W,Z){return new Promise(($,J)=>{if(Z?.aborted)return J(Z.reason);let Q=()=>{clearTimeout(Y),J(Z?.reason)},Y=setTimeout(()=>{Z?.removeEventListener("abort",Q),$()},W);Z?.addEventListener("abort",Q,{once:!0})})}function _(W){throw new O("invalid_input",W)}function u0(W){if(W===void 0)return;if(typeof W!=="string")_("caption must be a string.");if([...W].length>f.captionLength)_(`A caption takes at most ${f.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>f.hashtags)_(`A caption takes at most ${f.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>f.mentions)_(`A caption takes at most ${f.mentions} @mentions.`)}function U5(W){if(!Array.isArray(W)||W.length>f.userTags)_(`userTags takes at most ${f.userTags} tags.`);for(let Z of W){let $=(J)=>typeof J==="number"&&J>=0&&J<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))_("Each user tag needs a username, and x and y between 0 and 1.")}}function BW(W,Z){let $=Z?.imageUrl!==void 0,J=Z?.videoUrl!==void 0;if($===J)_(`${W} takes exactly one of imageUrl and videoUrl.`);if($)q1(`${W}.imageUrl`,Z.imageUrl);else q1(`${W}.videoUrl`,Z.videoUrl)}function q1(W,Z){let $;try{$=new URL(Z)}catch{_(`${W} is not an absolute URL.`)}if($.protocol!=="https:")_(`${W} must be an https URL: Instagram fetches the media from it.`);let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=jW(J);if(Q?FW(Q)!==null:!J.includes(".")||/(^|\.)(localhost|local|internal)$/.test(J))_(`${W} must be a public URL: Instagram fetches the media from it.`)}class d0{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:Z}=W;if(!Number.isFinite(Z)||Z<0||Z>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(Z)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function x5(W={}){return new d0(W)}class LW extends l0{rows=new Map;constructor(W={}){super();for(let[Z,$]of Object.entries(W))this.rows.set(Z,{key:Z,active:$})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,Z,$){return this.rows.set(W,{key:W,active:Z,updatedBy:$.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{n8 as viewRouteConfigDefaults,W9 as translationConfigDefaults,M4 as toRangeHeaderValue,b5 as subjectFor,p5 as sniffContentType,gZ as scheduleConfigDefaults,D4 as resolveRange,O9 as redisConfigDefaults,H9 as rateLimiterConfigDefaults,FZ as queueConfigDefaults,J5 as parseMetaSignedRequest,D1 as parseContentRange,R5 as mintSessionToken,WZ as middlewareConfigDefaults,CZ as mcpCallOf,QZ as mailConfigDefaults,M9 as logConfigDefaults,S5 as isSessionToken,w8 as isFinalRunStatus,O6 as isBroadcastEvent,d5 as isActiveContentType,T5 as inRollout,c8 as imageConfigDefaults,m5 as filesystemConfigDefaults,Q9 as featuresConfigDefaults,mZ as eventConfigDefaults,P5 as evaluateFeature,j8 as encodeCursor,s8 as documentScriptCspHash,dZ as discoverWorkflows,iZ as discoverListeners,pZ as discoverJobs,lZ as discoverCronJobs,nZ as discoverCommands,eZ as defineTranslationConfig,hZ as defineScheduleConfig,T8 as defineRunsConfig,d8 as defineRouteConfig,x9 as defineRedisConfig,D9 as defineRateLimiterConfig,jZ as defineQueueConfig,e8 as defineMiddlewareConfig,JZ as defineMailConfig,F9 as defineLogConfig,m8 as defineImageConfig,E5 as defineFilesystemConfig,J9 as defineFeaturesConfig,x5 as defineFeature,EZ as defineEventConfig,UW as defineEncryptionConfig,vZ as defineCommandConfig,yZ as defineCommand,X8 as defineChangeFeedConfig,n5 as defineCacheConfig,O8 as defineBroadcastConfig,k5 as defineAuthConfig,F8 as decodeCursor,XZ as createWorkflowTableStatements,I8 as createRunsTableStatements,IZ as commandConfigDefaults,B8 as changeFeedConfigDefaults,i5 as cacheConfigDefaults,V5 as bucketOf,C5 as bucketKey,S8 as broadcastConfigDefaults,w4 as bearerToken,f5 as authConfigDefaults,L4 as assertDeletablePrefix,l8 as apiRouteConfigDefaults,e6 as XOAuthProvider,OZ as WorkflowRuntime,UZ as WorkflowCancelledError,uZ as Workflow,DZ as WaitTimeoutError,t8 as ViewRouteDispatcher,y5 as UndeclaredFeatureError,t5 as TaggedCache,u5 as StorageFetchTimeoutError,HZ as StepTimeoutError,NZ as StepFailedError,xZ as Step,LW as StaticFeatureFlagSource,E8 as Sharp,bZ as Scheduler,Z9 as ScheduleServiceProvider,a8 as STATIC_NAVIGATION_CSP_HASH,x8 as SOCKET_ID_HEADER,O5 as SESSION_TOKEN_PREFIX,s0 as S3Driver,_9 as RunsServiceProvider,y8 as RunNotFoundError,h8 as RunManager,A8 as RunFailure,R9 as RouteServiceProvider,$Z as ResendDriver,S9 as RedisServiceProvider,O4 as RedisRateLimiterTimeoutError,y1 as RedisRateLimiterDisconnectedError,e0 as RedisRateLimiter,I1 as RedisManager,o5 as RedisCacheStore,_8 as RedisBroadcastDriver,U9 as RateLimiterServiceProvider,U4 as RateLimiterDriver,_5 as RateLimiter,$1 as RangeNotSatisfiableError,sZ as QueueServiceProvider,SZ as QueueManager,G8 as ProviderConnection,H6 as PrismaMcpOAuthStore,C8 as PendingBroadcast,b8 as OPEN_RUN_STATUSES,K8 as OAuthReconnectRequiredError,m as OAuthProvider,m0 as OAuthConnectionProvider,w1 as OAuthConnectionError,U as OAuthCallbackError,N9 as MiddlewareServiceProvider,p8 as MiddlewareRegistry,y as MetaSignedRequestError,MZ as MemoryWorkflowStore,q8 as MemoryRunStore,LZ as MemoryQueueDriver,D6 as MemoryMcpOAuthStore,zZ as MemoryLockStore,Q8 as MemoryConnectionStore,L8 as MemoryChangeFeedDriver,s5 as MemoryCacheStore,R8 as MemoryBroadcastDriver,kZ as McpToolError,VZ as McpRegistry,L6 as McpOAuthServer,PZ as McpHttpServer,fZ as McpCallRefusedError,TZ as McpApiKeyResolver,K9 as MailServiceProvider,YZ as MailManager,L9 as LogServiceProvider,l5 as LogManager,W8 as LockManager,r5 as LockLostError,cZ as Listener,j9 as KernelIdServiceProvider,i8 as KernelId,RZ as Job,U8 as InvalidChannelError,p0 as InstagramPublisher,O as InstagramPublishError,YW as InstagramOAuthProvider,F4 as InstagramConnectionProvider,I as InstagramApiError,K5 as Instagram,x4 as InMemoryRateLimiter,B9 as ImageServiceProvider,g8 as ImageOptimizationDriver,u8 as ImageManager,o8 as ISLAND_LOADER_CSP_HASH,f as INSTAGRAM_LIMITS,e5 as HeldLock,_6 as GoogleOAuthProvider,f6 as GitHubOAuthProvider,X9 as FilesystemServiceProvider,c5 as FilesystemManager,g5 as FileSystemDriver,H1 as FileStorageDriver,a as FileNotFoundError,Y9 as FeaturesServiceProvider,I5 as FeatureSourceReadOnlyError,A5 as FeatureScope,w5 as FeatureReloadError,v5 as FeatureModelMissingError,h5 as FeatureManager,q5 as FeatureFlagStore,l0 as FeatureFlagSource,d0 as Feature,P8 as FINAL_RUN_STATUSES,G9 as EventServiceProvider,w as EventManager,p1 as Event,z9 as EncryptionServiceProvider,$8 as EncryptionKeyError,Z8 as Encrypter,ZZ as EmailDriver,J8 as DecryptionError,GZ as DatabaseWorkflowStore,v8 as DatabaseRunStore,BZ as DatabaseQueueDriver,KZ as DatabaseLockStore,$9 as DatabaseFeatureFlagSource,Y8 as DatabaseConnectionStore,M8 as DatabaseChangeFeedDriver,_Z as DEFAULT_MCP_SCOPE,AZ as CronJob,z8 as ConnectionManager,k9 as CommandRegistry,wZ as CommandFailed,qZ as Command,H8 as ChangeFeedSubscription,tZ as ChangeFeedServiceProvider,D8 as ChangeFeedManager,N8 as ChangeFeedFullError,aZ as CacheServiceProvider,a5 as CacheManager,A1 as CONSENT_PAGE_HEADERS,oZ as BroadcastServiceProvider,V8 as BroadcastScope,k8 as BroadcastPayloadTooLargeError,f8 as BroadcastManager,S6 as BroadcastEvent,a0 as AzureBlobDriver,rZ as AuthServiceProvider,E1 as AuthManager,r8 as ApiRouteDispatcher};
|
|
71
71
|
|
|
72
|
-
//# debugId=
|
|
72
|
+
//# debugId=2EE802B81896970064756E2164756E21
|