sst 2.24.14 → 2.24.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/bootstrap.js +1 -0
  2. package/cli/commands/bind.js +302 -293
  3. package/cli/commands/bootstrap.js +8 -2
  4. package/cli/commands/build.js +16 -10
  5. package/cli/commands/connect.js +41 -34
  6. package/cli/commands/console.js +17 -11
  7. package/cli/commands/deploy.js +83 -72
  8. package/cli/commands/dev.js +294 -277
  9. package/cli/commands/diff.js +64 -58
  10. package/cli/commands/remove.js +46 -36
  11. package/cli/commands/secrets/get.d.ts +1 -1
  12. package/cli/commands/secrets/get.js +4 -1
  13. package/cli/commands/secrets/list.js +58 -51
  14. package/cli/commands/secrets/load.js +34 -28
  15. package/cli/commands/secrets/remove.js +4 -0
  16. package/cli/commands/secrets/secrets.d.ts +1 -1
  17. package/cli/commands/secrets/secrets.js +5 -5
  18. package/cli/commands/secrets/set.js +32 -26
  19. package/cli/commands/telemetry.js +13 -6
  20. package/cli/commands/transform.js +12 -5
  21. package/cli/commands/types.js +18 -12
  22. package/cli/commands/update.js +94 -88
  23. package/cli/commands/version.js +12 -5
  24. package/cli/program.d.ts +4 -0
  25. package/cli/program.js +36 -1
  26. package/cli/sst.js +8 -7
  27. package/cli/telemetry/telemetry.d.ts +16 -1
  28. package/cli/telemetry/telemetry.js +13 -3
  29. package/constructs/App.js +2 -5
  30. package/constructs/Function.js +1 -1
  31. package/constructs/SsrSite.js +1 -1
  32. package/constructs/deprecated/NextjsSite.js +3 -4
  33. package/error.d.ts +3 -0
  34. package/error.js +5 -0
  35. package/node/future/auth/handler.d.ts +9 -18
  36. package/node/future/auth/handler.js +14 -29
  37. package/node/future/auth/session.d.ts +31 -0
  38. package/node/future/auth/session.js +39 -0
  39. package/package.json +2 -2
  40. package/support/signing-function/index.mjs +3 -3
@@ -1,19 +1,25 @@
1
1
  import path from "path";
2
2
  export const types = (program) => program.command("types", "Generate resource types in .sst/types", (yargs) => yargs, async () => {
3
+ const { exit, exitWithError } = await import("../program.js");
3
4
  const { useProject } = await import("../../project.js");
4
5
  const { Stacks } = await import("../../stacks/index.js");
5
6
  const { App } = await import("../../constructs/App.js");
6
7
  const { Colors } = await import("../colors.js");
7
- const project = useProject();
8
- const [_metafile, sstConfig] = await Stacks.load(project.paths.config);
9
- const app = new App({
10
- mode: "deploy",
11
- stage: project.config.stage,
12
- name: project.config.name,
13
- region: project.config.region,
14
- });
15
- sstConfig.stacks(app);
16
- app.codegenTypes();
17
- Colors.line(Colors.success(`✔ `), `Types generated in ${path.resolve(project.paths.out, "types")}`);
18
- process.exit(0);
8
+ try {
9
+ const project = useProject();
10
+ const [_metafile, sstConfig] = await Stacks.load(project.paths.config);
11
+ const app = new App({
12
+ mode: "deploy",
13
+ stage: project.config.stage,
14
+ name: project.config.name,
15
+ region: project.config.region,
16
+ });
17
+ sstConfig.stacks(app);
18
+ app.codegenTypes();
19
+ Colors.line(Colors.success(`✔ `), `Types generated in ${path.resolve(project.paths.out, "types")}`);
20
+ await exit();
21
+ }
22
+ catch (e) {
23
+ await exitWithError(e);
24
+ }
19
25
  });
@@ -1,4 +1,3 @@
1
- import { VisibleError } from "../../error.js";
2
1
  const FIELDS = ["dependencies", "devDependencies"];
3
2
  const SST_PKGS = ["sst", "astro-sst", "svelte-kit-sst", "solid-start-sst"];
4
3
  export const update = (program) => program.command("update [version]", "Update your SST and CDK packages", (yargs) => yargs.positional("version", {
@@ -8,103 +7,110 @@ export const update = (program) => program.command("update [version]", "Update y
8
7
  const fs = await import("fs/promises");
9
8
  const path = await import("path");
10
9
  const { fetch } = await import("undici");
10
+ const { exit, exitWithError } = await import("../program.js");
11
11
  const { useProject } = await import("../../project.js");
12
+ const { VisibleError } = await import("../../error.js");
12
13
  const { Colors } = await import("../colors.js");
13
- const project = useProject();
14
- const files = await findAllPackageJson(project.paths.root);
15
- const metadata = await fetch(`https://registry.npmjs.org/sst/${args.version || "latest"}`).then((resp) => resp.json());
16
- const allChanges = new Map();
17
- const allOldPackages = new Map();
18
- // Update all package.json files
19
- await Promise.all(files.map(updatePackageJson));
20
- // Print status
21
- if (allOldPackages.size > 0) {
22
- for (const [file, pkgs] of allOldPackages.entries()) {
23
- Colors.line(Colors.danger(`✖ `), Colors.bold.dim(path.relative(project.paths.root, file)));
14
+ try {
15
+ const project = useProject();
16
+ const files = await findAllPackageJson(project.paths.root);
17
+ const metadata = await fetch(`https://registry.npmjs.org/sst/${args.version || "latest"}`).then((resp) => resp.json());
18
+ const allChanges = new Map();
19
+ const allOldPackages = new Map();
20
+ // Update all package.json files
21
+ await Promise.all(files.map(updatePackageJson));
22
+ // Print status
23
+ if (allOldPackages.size > 0) {
24
+ for (const [file, pkgs] of allOldPackages.entries()) {
25
+ Colors.line(Colors.danger(`✖ `), Colors.bold.dim(path.relative(project.paths.root, file)));
26
+ for (const [pkg, version] of pkgs) {
27
+ Colors.line(Colors.dim(` ${pkg}@${version}`));
28
+ }
29
+ }
30
+ Colors.gap();
31
+ throw new VisibleError("We've detected AWS CDK v1 dependencies in your package.json. SST requires CDK v2. Please update to CDK v2 dependencies, and then execute `sst update`. Refer to the official AWS CDK migration documentation — https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html#migrating-v2-v1-upgrade");
32
+ }
33
+ // Print status
34
+ if (allChanges.size === 0) {
35
+ Colors.line(Colors.success(`✔ `), `Already using v${metadata.version}`);
36
+ return;
37
+ }
38
+ for (const [file, pkgs] of allChanges.entries()) {
39
+ Colors.line(Colors.success(`✔ `), Colors.bold.dim(path.relative(project.paths.root, file)));
24
40
  for (const [pkg, version] of pkgs) {
25
41
  Colors.line(Colors.dim(` ${pkg}@${version}`));
26
42
  }
27
43
  }
28
44
  Colors.gap();
29
- throw new VisibleError("We've detected AWS CDK v1 dependencies in your package.json. SST requires CDK v2. Please update to CDK v2 dependencies, and then execute `sst update`. Refer to the official AWS CDK migration documentation — https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html#migrating-v2-v1-upgrade");
30
- }
31
- // Print status
32
- if (allChanges.size === 0) {
33
- Colors.line(Colors.success(`✔ `), `Already using v${metadata.version}`);
34
- return;
35
- }
36
- for (const [file, pkgs] of allChanges.entries()) {
37
- Colors.line(Colors.success(`✔ `), Colors.bold.dim(path.relative(project.paths.root, file)));
38
- for (const [pkg, version] of pkgs) {
39
- Colors.line(Colors.dim(` ${pkg}@${version}`));
40
- }
41
- }
42
- Colors.gap();
43
- Colors.line(`${Colors.primary(`➜`)} ${Colors.warning("Make sure to run: npm install (or pnpm install, or yarn)")}`);
44
- process.exit(0);
45
- /////////////
46
- // Helpers
47
- /////////////
48
- async function findAllPackageJson(dir) {
49
- const children = await fs.readdir(dir);
50
- const tasks = children.map(async (item) => {
51
- if (item === "node_modules")
45
+ Colors.line(`${Colors.primary(`➜`)} ${Colors.warning("Make sure to run: npm install (or pnpm install, or yarn)")}`);
46
+ /////////////
47
+ // Helpers
48
+ /////////////
49
+ async function findAllPackageJson(dir) {
50
+ const children = await fs.readdir(dir);
51
+ const tasks = children.map(async (item) => {
52
+ if (item === "node_modules")
53
+ return [];
54
+ // Ignore hidden paths
55
+ if (/(^|\/)\.[^\/\.]/g.test(item))
56
+ return [];
57
+ const full = path.join(dir, item);
58
+ if (item === "package.json")
59
+ return [full];
60
+ const stat = await fs.stat(full);
61
+ if (stat.isDirectory())
62
+ return findAllPackageJson(full);
52
63
  return [];
53
- // Ignore hidden paths
54
- if (/(^|\/)\.[^\/\.]/g.test(item))
55
- return [];
56
- const full = path.join(dir, item);
57
- if (item === "package.json")
58
- return [full];
59
- const stat = await fs.stat(full);
60
- if (stat.isDirectory())
61
- return findAllPackageJson(full);
62
- return [];
63
- });
64
- return (await Promise.all(tasks)).flat();
65
- }
66
- async function updatePackageJson(file) {
67
- const changes = new Set();
68
- const oldPackages = new Set();
69
- const data = await fs.readFile(file).then((x) => x.toString());
70
- const json = JSON.parse(data);
71
- // Update versions
72
- for (const field of FIELDS) {
73
- const deps = json[field];
74
- for (const [pkg, existing] of Object.entries(deps || {})) {
75
- const desired = (() => {
76
- if (SST_PKGS.includes(pkg)) {
77
- return metadata.version;
78
- }
79
- else if (pkg === "constructs") {
80
- return metadata.dependencies.constructs;
81
- }
82
- else if (pkg === "aws-cdk-lib") {
83
- return metadata.dependencies["aws-cdk-lib"];
84
- }
85
- else if (pkg.startsWith("@aws-cdk/aws-")) {
86
- if (!pkg.endsWith("-alpha")) {
87
- oldPackages.add([pkg, existing]);
88
- return;
64
+ });
65
+ return (await Promise.all(tasks)).flat();
66
+ }
67
+ async function updatePackageJson(file) {
68
+ const changes = new Set();
69
+ const oldPackages = new Set();
70
+ const data = await fs.readFile(file).then((x) => x.toString());
71
+ const json = JSON.parse(data);
72
+ // Update versions
73
+ for (const field of FIELDS) {
74
+ const deps = json[field];
75
+ for (const [pkg, existing] of Object.entries(deps || {})) {
76
+ const desired = (() => {
77
+ if (SST_PKGS.includes(pkg)) {
78
+ return metadata.version;
79
+ }
80
+ else if (pkg === "constructs") {
81
+ return metadata.dependencies.constructs;
82
+ }
83
+ else if (pkg === "aws-cdk-lib") {
84
+ return metadata.dependencies["aws-cdk-lib"];
89
85
  }
90
- return metadata.dependencies["@aws-cdk/aws-apigatewayv2-alpha"];
91
- }
92
- })();
93
- if (!desired || existing === desired)
94
- continue;
95
- changes.add([pkg, desired]);
96
- deps[pkg] = desired;
86
+ else if (pkg.startsWith("@aws-cdk/aws-")) {
87
+ if (!pkg.endsWith("-alpha")) {
88
+ oldPackages.add([pkg, existing]);
89
+ return;
90
+ }
91
+ return metadata.dependencies["@aws-cdk/aws-apigatewayv2-alpha"];
92
+ }
93
+ })();
94
+ if (!desired || existing === desired)
95
+ continue;
96
+ changes.add([pkg, desired]);
97
+ deps[pkg] = desired;
98
+ }
99
+ }
100
+ // Write to package.json
101
+ if (changes.size > 0) {
102
+ // note: preserve ending new line characters in package.json
103
+ const tailingNewline = data.match(/\r?\n$/)?.[0];
104
+ await fs.writeFile(file, `${JSON.stringify(json, null, 2)}${tailingNewline ?? ""}`);
105
+ allChanges.set(file, changes);
106
+ }
107
+ if (oldPackages.size > 0) {
108
+ allOldPackages.set(file, oldPackages);
97
109
  }
98
110
  }
99
- // Write to package.json
100
- if (changes.size > 0) {
101
- // note: preserve ending new line characters in package.json
102
- const tailingNewline = data.match(/\r?\n$/)?.[0];
103
- await fs.writeFile(file, `${JSON.stringify(json, null, 2)}${tailingNewline ?? ""}`);
104
- allChanges.set(file, changes);
105
- }
106
- if (oldPackages.size > 0) {
107
- allOldPackages.set(file, oldPackages);
108
- }
111
+ await exit();
112
+ }
113
+ catch (e) {
114
+ await exitWithError(e);
109
115
  }
110
116
  });
@@ -1,8 +1,15 @@
1
- export const version = (program) => program.command("version", "Print SST and CDK version", (yargs) => yargs, async (args) => {
1
+ export const version = (program) => program.command("version", "Print SST and CDK version", (yargs) => yargs, async () => {
2
+ const { exit, exitWithError } = await import("../program.js");
2
3
  const { Colors } = await import("../colors.js");
3
4
  const { useProject } = await import("../../project.js");
4
- const project = useProject();
5
- Colors.line(Colors.bold(`SST:`), `v${project.version}`);
6
- Colors.line(Colors.bold(`CDK:`), `v${project.cdkVersion}`);
7
- Colors.line(Colors.bold(`Constructs:`), `v${project.constructsVersion}`);
5
+ try {
6
+ const project = useProject();
7
+ Colors.line(Colors.bold(`SST:`), `v${project.version}`);
8
+ Colors.line(Colors.bold(`CDK:`), `v${project.cdkVersion}`);
9
+ Colors.line(Colors.bold(`Constructs:`), `v${project.constructsVersion}`);
10
+ await exit();
11
+ }
12
+ catch (e) {
13
+ await exitWithError(e);
14
+ }
8
15
  });
package/cli/program.d.ts CHANGED
@@ -13,3 +13,7 @@ export declare const program: import("yargs").Argv<{
13
13
  future: boolean | undefined;
14
14
  }>;
15
15
  export type Program = typeof program;
16
+ export declare function exitWithError(error: Error): Promise<void>;
17
+ export declare function exit(code?: number): Promise<void>;
18
+ export declare function trackDevError(error: Error): Promise<void>;
19
+ export declare function trackDevRunning(): Promise<void>;
package/cli/program.js CHANGED
@@ -43,10 +43,45 @@ export const program = yargs(hideBin(process.argv))
43
43
  .recommendCommands()
44
44
  .demandCommand()
45
45
  .strict()
46
- .fail((_, error, yargs) => {
46
+ .fail(async (_, error, yargs) => {
47
47
  if (!error) {
48
48
  yargs.showHelp();
49
49
  process.exit(1);
50
50
  }
51
51
  throw error;
52
52
  });
53
+ const startAt = Date.now();
54
+ export async function exitWithError(error) {
55
+ const { trackCliFailed } = await import("./telemetry/telemetry.js");
56
+ await trackCliFailed({
57
+ rawCommand: process.argv.slice(2).join(" "),
58
+ duration: Date.now() - startAt,
59
+ errorName: error.name,
60
+ errorMessage: error.message,
61
+ });
62
+ throw error;
63
+ }
64
+ export async function exit(code) {
65
+ const { trackCliSucceeded } = await import("./telemetry/telemetry.js");
66
+ await trackCliSucceeded({
67
+ rawCommand: process.argv.slice(2).join(" "),
68
+ duration: Date.now() - startAt,
69
+ });
70
+ process.exit(code);
71
+ }
72
+ export async function trackDevError(error) {
73
+ const { trackCliDevError } = await import("./telemetry/telemetry.js");
74
+ await trackCliDevError({
75
+ rawCommand: process.argv.slice(2).join(" "),
76
+ duration: Date.now() - startAt,
77
+ errorName: error.name,
78
+ errorMessage: error.message,
79
+ });
80
+ }
81
+ export async function trackDevRunning() {
82
+ const { trackCliDevRunning } = await import("./telemetry/telemetry.js");
83
+ await trackCliDevRunning({
84
+ rawCommand: process.argv.slice(2).join(" "),
85
+ duration: Date.now() - startAt,
86
+ });
87
+ }
package/cli/sst.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { blue, red } from "colorette";
3
3
  import { program } from "./program.js";
4
- import { VisibleError } from "../error.js";
4
+ import { SilentError, VisibleError } from "../error.js";
5
5
  import { useSpinners } from "./spinner.js";
6
6
  import { Logger } from "../logger.js";
7
7
  import dotenv from "dotenv";
@@ -54,16 +54,17 @@ process.on("uncaughtException", (err) => {
54
54
  if (spinner.isSpinning)
55
55
  spinner.fail(spinner.text);
56
56
  }
57
- console.log(red("Error:"), err.message);
58
- if (!(err instanceof VisibleError)) {
57
+ if (!(err instanceof SilentError)) {
58
+ console.log(red("Error:"), err.message);
59
+ if (!(err instanceof VisibleError)) {
60
+ console.log();
61
+ console.trace(err.stack);
62
+ }
59
63
  console.log();
60
- console.trace(err.stack);
64
+ console.log(`Need help with this error? Post it in #help on the SST Discord ${blue(`https://sst.dev/discord`)}`);
61
65
  }
62
- console.log();
63
- console.log(`Need help with this error? Post it in #help on the SST Discord ${blue(`https://sst.dev/discord`)}`);
64
66
  process.exit(1);
65
67
  });
66
- process.on("beforeExit", () => { });
67
68
  // Check Node version
68
69
  const nodeVersion = process.versions.node;
69
70
  if (Number(nodeVersion.split(".")[0]) < 16) {
@@ -1,4 +1,19 @@
1
+ type CliFailedEvent = {
2
+ rawCommand: string;
3
+ duration: number;
4
+ errorName: string;
5
+ errorMessage: string;
6
+ };
7
+ type CliSucceededEvent = {
8
+ rawCommand: string;
9
+ duration: number;
10
+ };
1
11
  export declare function enable(): void;
2
12
  export declare function disable(): void;
3
13
  export declare function isEnabled(): boolean;
4
- export declare function trackCli(command: string): void;
14
+ export declare function trackCli(command: string): Promise<any>;
15
+ export declare function trackCliFailed(event: CliFailedEvent): Promise<any>;
16
+ export declare function trackCliSucceeded(event: CliSucceededEvent): Promise<any>;
17
+ export declare function trackCliDevError(event: CliFailedEvent): Promise<any>;
18
+ export declare function trackCliDevRunning(event: CliSucceededEvent): Promise<any>;
19
+ export {};
@@ -26,9 +26,19 @@ export function isEnabled() {
26
26
  return conf.get(TELEMETRY_KEY_ENABLED, true) !== false;
27
27
  }
28
28
  export function trackCli(command) {
29
- record("CLI_COMMAND", {
30
- command,
31
- });
29
+ return record("CLI_COMMAND", { command });
30
+ }
31
+ export function trackCliFailed(event) {
32
+ return record("CLI_COMMAND_FAILED", event);
33
+ }
34
+ export function trackCliSucceeded(event) {
35
+ return record("CLI_COMMAND_SUCCEEDED", event);
36
+ }
37
+ export function trackCliDevError(event) {
38
+ return record("CLI_COMMAND_DEV_ERROR", event);
39
+ }
40
+ export function trackCliDevRunning(event) {
41
+ return record("CLI_COMMAND_DEV_RUNNING", event);
32
42
  }
33
43
  function initializeConf() {
34
44
  try {
package/constructs/App.js CHANGED
@@ -9,6 +9,7 @@ import { Auth } from "./Auth.js";
9
9
  import { useDeferredTasks } from "./deferred_task.js";
10
10
  import { AppContext } from "./context.js";
11
11
  import { useProject } from "../project.js";
12
+ import { VisibleError } from "../error.js";
12
13
  import { Logger } from "../logger.js";
13
14
  import { App as CDKApp, Tags, CfnResource, RemovalPolicy, CustomResource, Aspects, } from "aws-cdk-lib/core";
14
15
  import { CfnFunction } from "aws-cdk-lib/aws-lambda";
@@ -16,10 +17,6 @@ import { Bucket } from "aws-cdk-lib/aws-s3";
16
17
  import { Effect, Policy, PolicyStatement } from "aws-cdk-lib/aws-iam";
17
18
  import { CfnLogGroup } from "aws-cdk-lib/aws-logs";
18
19
  import { useBootstrap } from "../bootstrap.js";
19
- function exitWithMessage(message) {
20
- console.error(message);
21
- process.exit(1);
22
- }
23
20
  /**
24
21
  * The App construct extends cdk.App and is used internally by SST.
25
22
  */
@@ -250,7 +247,7 @@ export class App extends CDKApp {
250
247
  metaJson = JSON.parse(fs.readFileSync(file).toString());
251
248
  }
252
249
  catch (e) {
253
- exitWithMessage("There was a problem reading the esbuild metafile.");
250
+ throw new VisibleError("There was a problem reading the esbuild metafile.");
254
251
  }
255
252
  return Object.keys(metaJson.inputs).map((input) => path.resolve(input));
256
253
  }
@@ -247,7 +247,7 @@ export class Function extends CDKFunction {
247
247
  if (result.sourcemap) {
248
248
  const data = await fs.readFile(result.sourcemap);
249
249
  await fs.writeFile(result.sourcemap, zlib.gzipSync(data));
250
- const asset = new Asset(stack, this.id + "-Sourcemap", {
250
+ const asset = new Asset(this, this.id + "-Sourcemap", {
251
251
  path: result.sourcemap,
252
252
  });
253
253
  await fs.rm(result.sourcemap);
@@ -272,7 +272,7 @@ export class SsrSite extends Construct {
272
272
  });
273
273
  }
274
274
  catch (e) {
275
- throw new Error(`There was a problem building the "${this.node.id}" site.`);
275
+ throw new Error(`There was a problem building the "${this.node.id}" ${this.getConstructMetadata().type}.`);
276
276
  }
277
277
  }
278
278
  /////////////////////
@@ -28,6 +28,7 @@ import { getParameterPath, } from "../util/functionBinding.js";
28
28
  import * as crossRegionHelper from "./cross-region-helper.js";
29
29
  import { gray, red } from "colorette";
30
30
  import { useProject } from "../../project.js";
31
+ import { VisibleError } from "../../error.js";
31
32
  import { createAppContext } from "../context.js";
32
33
  const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
33
34
  /////////////////////
@@ -284,8 +285,7 @@ export class NextjsSite extends Construct {
284
285
  stdio: "inherit",
285
286
  });
286
287
  if (result.status !== 0) {
287
- console.error(`There was a problem generating the "${this.node.id}" NextjsSite package.`);
288
- process.exit(1);
288
+ throw new VisibleError(`There was a problem generating the "${this.node.id}" NextjsSite package.`);
289
289
  }
290
290
  // create assets
291
291
  const assets = [];
@@ -641,8 +641,7 @@ export class NextjsSite extends Construct {
641
641
  },
642
642
  });
643
643
  if (result.status !== 0) {
644
- console.error(`There was a problem building the "${this.node.id}" NextjsSite.`);
645
- process.exit(1);
644
+ throw new VisibleError(`There was a problem building the "${this.node.id}" NextjsSite.`);
646
645
  }
647
646
  return buildOutput;
648
647
  }
package/error.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export declare class VisibleError extends Error {
2
2
  constructor(...message: string[]);
3
3
  }
4
+ export declare class SilentError extends Error {
5
+ constructor(...message: string[]);
6
+ }
package/error.js CHANGED
@@ -3,3 +3,8 @@ export class VisibleError extends Error {
3
3
  super(message.join("\n"));
4
4
  }
5
5
  }
6
+ export class SilentError extends Error {
7
+ constructor(...message) {
8
+ super(message.join("\n"));
9
+ }
10
+ }
@@ -1,27 +1,18 @@
1
1
  import { APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2 } from "aws-lambda";
2
2
  import { Adapter } from "./adapter/adapter.js";
3
3
  import { SignerOptions } from "fast-jwt";
4
- import { SessionValue } from "./session.js";
5
- declare const onSuccessResponse: {
6
- session(input: SessionCreateInput): {
4
+ import { SessionBuilder, SessionValue } from "./session.js";
5
+ interface OnSuccessResponder<T> {
6
+ session(input: T & Partial<SignerOptions>): {
7
7
  type: "session";
8
- properties: SessionCreateInput;
8
+ properties: T;
9
9
  };
10
10
  http(input: APIGatewayProxyStructuredResultV2): {
11
11
  type: "http";
12
- properties: APIGatewayProxyStructuredResultV2;
12
+ properties: typeof input;
13
13
  };
14
- provider(provider: string): {
15
- type: "http";
16
- properties: {
17
- statusCode: number;
18
- headers: {
19
- Location: string;
20
- };
21
- };
22
- };
23
- };
24
- export declare function AuthHandler<Providers extends Record<string, Adapter<any>>, Result = {
14
+ }
15
+ export declare function AuthHandler<Providers extends Record<string, Adapter<any>>, Sessions extends SessionBuilder, Result = {
25
16
  [key in keyof Providers]: {
26
17
  provider: key;
27
18
  } & Extract<Awaited<ReturnType<Providers[key]>>, {
@@ -29,11 +20,11 @@ export declare function AuthHandler<Providers extends Record<string, Adapter<any
29
20
  }>["properties"];
30
21
  }[keyof Providers]>(input: {
31
22
  providers: Providers;
23
+ sessions?: Sessions;
32
24
  clients: () => Promise<Record<string, string>>;
33
25
  onAuthorize?: (event: APIGatewayProxyEventV2) => Promise<void | keyof Providers>;
34
- onSuccess: (input: Result, response: typeof onSuccessResponse) => Promise<ReturnType<(typeof onSuccessResponse)[keyof typeof onSuccessResponse]>>;
26
+ onSuccess: (input: Result, response: OnSuccessResponder<SessionValue | Sessions["$type"]>) => Promise<ReturnType<OnSuccessResponder<SessionValue | Sessions["$type"]>[keyof OnSuccessResponder<any>]>>;
35
27
  onIndex?: (event: APIGatewayProxyEventV2) => Promise<APIGatewayProxyStructuredResultV2>;
36
28
  onError?: () => Promise<APIGatewayProxyStructuredResultV2>;
37
29
  }): (event: APIGatewayProxyEventV2, context: import("aws-lambda").Context) => Promise<APIGatewayProxyStructuredResultV2>;
38
- export type SessionCreateInput = SessionValue & Partial<SignerOptions>;
39
30
  export {};
@@ -1,34 +1,6 @@
1
1
  import { createSigner, createVerifier } from "fast-jwt";
2
2
  import { ApiHandler, useCookie, useCookies, useFormValue, usePathParam, useQueryParam, useQueryParams, useResponse, } from "../../api/index.js";
3
3
  import { Config } from "../../config/index.js";
4
- const onSuccessResponse = {
5
- session(input) {
6
- return {
7
- type: "session",
8
- properties: input,
9
- };
10
- },
11
- http(input) {
12
- return {
13
- type: "http",
14
- properties: input,
15
- };
16
- },
17
- provider(provider) {
18
- return {
19
- type: "http",
20
- properties: {
21
- statusCode: 302,
22
- headers: {
23
- Location: "/authorize?" +
24
- new URLSearchParams({
25
- provider,
26
- }).toString(),
27
- },
28
- },
29
- };
30
- },
31
- };
32
4
  export function AuthHandler(input) {
33
5
  return ApiHandler(async (evt) => {
34
6
  const step = usePathParam("step");
@@ -184,7 +156,20 @@ export function AuthHandler(input) {
184
156
  const onSuccess = await input.onSuccess({
185
157
  provider,
186
158
  ...result.properties,
187
- }, onSuccessResponse);
159
+ }, {
160
+ http(input) {
161
+ return {
162
+ type: "http",
163
+ properties: input,
164
+ };
165
+ },
166
+ session(input) {
167
+ return {
168
+ type: "session",
169
+ properties: input,
170
+ };
171
+ },
172
+ });
188
173
  console.log("onSuccess", onSuccess);
189
174
  if (onSuccess.type === "session") {
190
175
  const { type, properties, ...rest } = onSuccess.properties;
@@ -43,4 +43,35 @@ export declare const Session: {
43
43
  create: typeof create;
44
44
  verify: typeof verify;
45
45
  };
46
+ export type SessionBuilder = ReturnType<typeof createSessionBuilder>;
47
+ export declare function createSessionBuilder<SessionTypes extends Record<string, any> = {}>(): {
48
+ create<T extends ({ [type in keyof SessionTypes]: {
49
+ type: type;
50
+ properties: SessionTypes[type];
51
+ }; }[keyof SessionTypes] | {
52
+ type: "public";
53
+ properties: {};
54
+ })["type"]>(type: T, properties: SessionTypes[T], options?: Partial<SignerOptions>): string;
55
+ verify(token: string): { [type in keyof SessionTypes]: {
56
+ type: type;
57
+ properties: SessionTypes[type];
58
+ }; }[keyof SessionTypes] | {
59
+ type: "public";
60
+ properties: {};
61
+ };
62
+ use(): { [type in keyof SessionTypes]: {
63
+ type: type;
64
+ properties: SessionTypes[type];
65
+ }; }[keyof SessionTypes] | {
66
+ type: "public";
67
+ properties: {};
68
+ };
69
+ $type: { [type in keyof SessionTypes]: {
70
+ type: type;
71
+ properties: SessionTypes[type];
72
+ }; }[keyof SessionTypes] | {
73
+ type: "public";
74
+ properties: {};
75
+ };
76
+ };
46
77
  export {};