repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.addSuperTriangle | addSuperTriangle(): void {
// Add new points to the end of the points array
this.points[this.N] = new TriangulationPoint(
this.N,
new Vector2(-100, -100),
);
this.points[this.N + 1] = new TriangulationPoint(
this.N + 1,
new Vector2(0, 100),
);
this.points[this.N + 2] = new TriangulationPoint(
this.N + 2,
new Vector2(100, -100),
);
// Store supertriangle in the first column of the vertex and adjacency data
this.triangulation[SUPERTRIANGLE][V1] = this.N;
this.triangulation[SUPERTRIANGLE][V2] = this.N + 1;
this.triangulation[SUPERTRIANGLE][V3] = this.N + 2;
// Zeros signify boundary edges
this.triangulation[SUPERTRIANGLE][E12] = OUT_OF_BOUNDS;
this.triangulation[SUPERTRIANGLE][E23] = OUT_OF_BOUNDS;
this.triangulation[SUPERTRIANGLE][E31] = OUT_OF_BOUNDS;
} | /**
* Initializes the triangulation by inserting the super triangle
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L251-L275 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.insertPointIntoTriangle | insertPointIntoTriangle(
p: TriangulationPoint,
t: number,
triangleCount: number,
) {
// V1
// *
// /|\
// /3|2\
// / | \
// / | \
// / | \
// / | \
// / t1 | t3 \
// / | \
// / 1 * 1 \
// / __/1\__ \
// / __/ \__ \
// / 2__/ t2 \__3 \
// / _/3 2\_ \
// *---------------------------*
// V3 V2
const t1 = t;
const t2 = triangleCount + 1;
const t3 = triangleCount + 2;
// Add the vertex & adjacency information for the two new triangles
// New vertex is set to first vertex of each triangle to help with
// restoring the triangulation later on
this.triangulation[t2][V1] = p.index;
this.triangulation[t2][V2] = this.triangulation[t][V2];
this.triangulation[t2][V3] = this.triangulation[t][V3];
this.triangulation[t2][E12] = t3;
this.triangulation[t2][E23] = this.triangulation[t][E23];
this.triangulation[t2][E31] = t1;
this.triangulation[t3][V1] = p.index;
this.triangulation[t3][V2] = this.triangulation[t][V1];
this.triangulation[t3][V3] = this.triangulation[t][V2];
this.triangulation[t3][E12] = t1;
this.triangulation[t3][E23] = this.triangulation[t][E12];
this.triangulation[t3][E31] = t2;
// Triangle index remains the same for E12, no need to update adjacency
this.updateAdjacency(this.triangulation[t][E12], t, t3);
this.updateAdjacency(this.triangulation[t][E23], t, t2);
// Replace existing triangle `t` with `t1`
this.triangulation[t1][V2] = this.triangulation[t][V3];
this.triangulation[t1][V3] = this.triangulation[t][V1];
this.triangulation[t1][V1] = p.index;
this.triangulation[t1][E23] = this.triangulation[t][E31];
this.triangulation[t1][E12] = t2;
this.triangulation[t1][E31] = t3;
// After the triangles have been inserted, restore the Delauney triangulation
this.restoreDelauneyTriangulation(p, t1, t2, t3);
} | /**
* Inserts the point `p` into triangle `t`, replacing it with three new triangles
*
* @param p The index of the point to insert
* @param t The index of the triangle
* @param triangleCount Total number of triangles created so far
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L284-L345 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.restoreDelauneyTriangulation | restoreDelauneyTriangulation(
p: TriangulationPoint,
t1: number,
t2: number,
t3: number,
): void {
const s: [t1: number, t2: number][] = [];
s.push([t1, this.triangulation[t1][E23]]);
s.push([t2, this.triangulation[t2][E23]]);
s.push([t3, this.triangulation[t3][E23]]);
while (s.length > 0) {
// Pop next triangle and its adjacent triangle off the stack
// t1 contains the newly added vertex at V1
// t2 is adjacent to t1 along the opposite edge of V1
[t1, t2] = s.pop() ?? [OUT_OF_BOUNDS, OUT_OF_BOUNDS];
if (t2 == OUT_OF_BOUNDS) {
continue;
}
// If t2 circumscribes p, the quadrilateral formed by t1+t2 has the
// diagonal drawn in the wrong direction and needs to be swapped
else {
const swap = this.swapQuadDiagonalIfNeeded(p.index, t1, t2);
if (swap) {
// Push newly formed triangles onto the stack to see if their diagonals
// need to be swapped
s.push([t1, swap.t3]);
s.push([t2, swap.t4]);
}
}
}
} | /**
* Restores the triangulation to a Delauney triangulation after new triangles have been added.
*
* @param p Index of the inserted point
* @param t1 Index of first triangle to check
* @param t2 Index of second triangle to check
* @param t3 Index of third triangle to check
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L355-L388 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.swapQuadDiagonalIfNeeded | swapQuadDiagonalIfNeeded(
p: number,
t1: number,
t2: number,
): { t3: number; t4: number } | null {
// 1) Form quadrilateral from t1 + t2 (q0->q1->q2->q3)
// 2) Swap diagonal between q1->q3 to q0->q2
//
// BEFORE AFTER
//
// q3 q3
// *-------------*-------------* *-------------*-------------*
// \ / \ / \ /|\ /
// \ t3 / \ t4 / \ t3 /3|2\ t4 /
// \ / \ / \ / | \ /
// \ / \ / \ / | \ /
// \ / t2 \ / \ / | \ /
// \ / \ / \ / | \ /
// q1 *-------------* q2 q1 * 2 t1 | t2 3 * q2
// \2 3/ \ | /
// \ / \ | /
// \ t1 / \ | /
// \ / \ | /
// \ / \1|1/
// \1/ \|/
// * q4 == p * q4 == p
//
// Get the vertices of the quad. The new vertex is always located at V1 of the triangle
let q1 = 0;
let q2 = 0;
let q3 = 0;
let q4 = p;
let t3 = 0;
let t4 = 0;
// Since t2 might be oriented in any direction, find which edge is adjacent to `t`
// The 4th vertex of the quad will be opposite this edge. We also need the two triangles
// t3 and t3 that are adjacent to t2 along the other edges since the adjacency information
// needs to be updated for those triangles.
if (this.triangulation[t2][E12] === t1) {
q1 = this.triangulation[t2][V2];
q2 = this.triangulation[t2][V1];
q3 = this.triangulation[t2][V3];
t3 = this.triangulation[t2][E23];
t4 = this.triangulation[t2][E31];
} else if (this.triangulation[t2][E23] === t1) {
q1 = this.triangulation[t2][V3];
q2 = this.triangulation[t2][V2];
q3 = this.triangulation[t2][V1];
t3 = this.triangulation[t2][E31];
t4 = this.triangulation[t2][E12];
} // (this.triangulation[t2][E31] == t1)
else {
q1 = this.triangulation[t2][V1];
q2 = this.triangulation[t2][V3];
q3 = this.triangulation[t2][V2];
t3 = this.triangulation[t2][E12];
t4 = this.triangulation[t2][E23];
}
// Perform test to see if p lies in the circumcircle of t2
const swap = this.swapTest(
this.points[q1].coords,
this.points[q2].coords,
this.points[q3].coords,
this.points[q4].coords,
);
if (swap) {
// Update adjacency for triangles adjacent to t1 and t2
this.updateAdjacency(t3, t2, t1);
this.updateAdjacency(this.triangulation[t1][E31], t1, t2);
// Perform the swap. As always, put the new vertex as the first vertex of the triangle
this.triangulation[t1][V1] = q4;
this.triangulation[t1][V2] = q1;
this.triangulation[t1][V3] = q3;
this.triangulation[t2][V1] = q4;
this.triangulation[t2][V2] = q3;
this.triangulation[t2][V3] = q2;
// Update adjacency information (order of operations is important here since we
// are overwriting data).
this.triangulation[t2][E12] = t1;
this.triangulation[t2][E23] = t4;
this.triangulation[t2][E31] = this.triangulation[t1][E31];
// triangulation[t1][E12] = t2;
this.triangulation[t1][E23] = t3;
this.triangulation[t1][E31] = t2;
return { t3, t4 };
} else {
return null;
}
} | /**
* Swaps the diagonal of the quadrilateral formed by triangle `t` and the
* triangle adjacent to the edge that is opposite of the newly added point
*
* @param p The index of the inserted point
* @param t1 Index of the triangle containing p
* @param t2 Index of the triangle opposite t1 that shares edge E23 with t1
* @returns Returns an object containing
* - `t3`: Index of triangle adjacent to t1 after swap
* - `t4`: Index of triangle adjacent to t2 after swap
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L401-L501 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.discardTrianglesWithSuperTriangleVertices | discardTrianglesWithSuperTriangleVertices(): void {
for (let i = 0; i < this.triangleCount; i++) {
// Add all triangles that don't contain a super-triangle vertex
if (
this.triangleContainsVertex(i, this.N) ||
this.triangleContainsVertex(i, this.N + 1) ||
this.triangleContainsVertex(i, this.N + 2)
) {
this.skipTriangle[i] = true;
}
}
} | /**
* Marks any triangles that contain super-triangle vertices as discarded
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L506-L517 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.swapTest | swapTest(v1: Vector2, v2: Vector2, v3: Vector2, v4: Vector2): boolean {
const x13 = v1.x - v3.x;
const x23 = v2.x - v3.x;
const y13 = v1.y - v3.y;
const y23 = v2.y - v3.y;
const x14 = v1.x - v4.x;
const x24 = v2.x - v4.x;
const y14 = v1.y - v4.y;
const y24 = v2.y - v4.y;
const cosA = x13 * x23 + y13 * y23;
const cosB = x24 * x14 + y24 * y14;
if (cosA >= 0 && cosB >= 0) {
return false;
} else if (cosA < 0 && cosB < 0) {
return true;
} else {
const sinA = x13 * y23 - x23 * y13;
const sinB = x24 * y14 - x14 * y24;
const sinAB = sinA * cosB + sinB * cosA;
return sinAB < 0;
}
} | /**
* Checks to see if the triangle formed by points v1->v2->v3 circumscribes point v4.
*
* @param {Vector3} v1 - Coordinates of 1st vertex of triangle.
* @param {Vector3} v2 - Coordinates of 2nd vertex of triangle.
* @param {Vector3} v3 - Coordinates of 3rd vertex of triangle.
* @param {Vector3} v4 - Coordinates of test point.
* @returns {boolean} Returns true if the triangle formed by v1->v2->v3 circumscribes point v4.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L528-L551 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.triangleContainsVertex | triangleContainsVertex(t: number, v: number): boolean {
return (
this.triangulation[t][V1] === v ||
this.triangulation[t][V2] === v ||
this.triangulation[t][V3] === v
);
} | /**
* Checks if the triangle `t` contains the specified vertex `v`.
*
* @param {number} t - The index of the triangle.
* @param {number} v - The index of the vertex.
* @returns {boolean} Returns true if the triangle `t` contains the vertex `v`.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L560-L566 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.updateAdjacency | updateAdjacency(t: number, tOld: number, tNew: number) {
// Boundary edge, no triangle exists
if (t === OUT_OF_BOUNDS) {
return;
}
const sharedEdge = this.findSharedEdge(t, tOld);
if (sharedEdge) {
this.triangulation[t][sharedEdge] = tNew;
}
} | /**
* Updates the adjacency information in triangle `t`. Any references to `tOld` are
* replaced with `tNew`.
*
* @param {number} t - The index of the triangle to update.
* @param {number} tOld - The index to be replaced.
* @param {number} tNew - The new index to replace with.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L576-L586 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | Triangulator.findSharedEdge | findSharedEdge(tOrigin: number, tAdjacent: number): number | null {
if (tOrigin === OUT_OF_BOUNDS) {
return null;
} else if (this.triangulation[tOrigin][E12] === tAdjacent) {
return E12;
} else if (this.triangulation[tOrigin][E23] === tAdjacent) {
return E23;
} else if (this.triangulation[tOrigin][E31] === tAdjacent) {
return E31;
} else {
return null;
}
} | /**
* Finds the edge index for triangle `tOrigin` that is adjacent to triangle `tAdjacent`.
*
* @param {number} tOrigin - The origin triangle to search.
* @param {number} tAdjacent - The triangle index to search for.
* @param {number} edgeIndex - Edge index returned as an out parameter (by reference).
* @returns {boolean} True if `tOrigin` is adjacent to `tAdjacent` and supplies the
* shared edge index via the out parameter. False if `tOrigin` is an invalid index or
* `tAdjacent` is not adjacent to `tOrigin`.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/triangulators/Triangulator.ts#L598-L610 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | BinSort.getBinNumber | static getBinNumber(i: number, j: number, n: number): number {
return i % 2 === 0 ? i * n + j : (i + 1) * n - j - 1;
} | /**
* Computes the bin number for the set of grid coordinates.
*
* @param i - Grid row
* @param j - Grid column
* @param n - Grid size
* @returns The computed bin number based on row and column indices.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/utils/BinSort.ts#L23-L25 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | BinSort.sort | static sort<T extends IBinSortable>(
input: T[],
lastIndex: number,
binCount: number,
): T[] {
if (binCount <= 1) {
return input; // Need at least two bins to sort
}
if (lastIndex > input.length) {
lastIndex = input.length; // If lastIndex is out of range, sort the entire array
}
const count: number[] = new Array(binCount).fill(0);
const output: T[] = new Array(input.length) as T[];
for (let i = 0; i < lastIndex; i++) {
count[input[i].bin]++;
}
for (let i = 1; i < binCount; i++) {
count[i] += count[i - 1];
}
for (let i = lastIndex - 1; i >= 0; i--) {
const binIndex = input[i].bin;
count[binIndex]--;
output[count[binIndex]] = input[i];
}
// Copy over the rest of the unsorted points
for (let i = lastIndex; i < output.length; i++) {
output[i] = input[i];
}
return output;
} | /**
* Performs a counting sort of the input points based on their bin number. Only
* sorts the elements in the index range [0, count]. If binCount is <= 1, no sorting
* is performed. If lastIndex > input.length, the entire input array is sorted.
*
* @param input - The input array to sort
* @param lastIndex - The index of the last element in `input` to sort. Only the
* elements [0, lastIndex) are sorted.
* @param binCount - Number of bins
* @returns The sorted array of points based on their bin number.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/utils/BinSort.ts#L38-L74 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | linesIntersectInternal | function linesIntersectInternal(
a1: Vector2,
a2: Vector2,
b1: Vector2,
b2: Vector2,
includeSharedEndpoints: boolean,
): boolean {
let a12 = { x: a2.x - a1.x, y: a2.y - a1.y };
let b12 = { x: b2.x - b1.x, y: b2.y - b1.y };
// If any of the vertices are shared between the two diagonals,
// the quad collapses into a triangle and is convex by default.
const hashA1 = hash2(a1);
const hashB1 = hash2(b1);
// Return ASAP to avoid computing other hashes
if (hashA1 === hashB1) return includeSharedEndpoints;
const hashA2 = hash2(a2);
if (hashA2 === hashB1) return includeSharedEndpoints;
const hashB2 = hash2(b2);
if (hashA1 === hashB2) return includeSharedEndpoints;
if (hashA2 === hashB2) return includeSharedEndpoints;
// Compute cross product between each point and the opposite diagonal
// Look at sign of the Z component to see which side of line point is on
let a1xb = (a1.x - b1.x) * b12.y - (a1.y - b1.y) * b12.x;
let a2xb = (a2.x - b1.x) * b12.y - (a2.y - b1.y) * b12.x;
let b1xa = (b1.x - a1.x) * a12.y - (b1.y - a1.y) * a12.x;
let b2xa = (b2.x - a1.x) * a12.y - (b2.y - a1.y) * a12.x;
// Check that the points for each diagonal lie on opposite sides of the other
// diagonal. Quad is also convex if a1/a2 lie on b1->b2 (and vice versa) since
// the shape collapses into a triangle (hence >= instead of >)
const intersecting =
((a1xb >= 0 && a2xb <= 0) || (a1xb <= 0 && a2xb >= 0)) &&
((b1xa >= 0 && b2xa <= 0) || (b1xa <= 0 && b2xa >= 0));
return intersecting;
} | /**
* Returns true lines a1->a2 and b1->b2 is intersect
* @param a1 Start point of line A
* @param a2 End point of line A
* @param b1 Start point of line B
* @param b2 End point of line B
* @param includeSharedEndpoints If set to true, intersection test returns true if lines share endpoints
* @returns True if the two lines are intersecting
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/utils/MathUtils.ts#L48-L90 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | hash2 | function hash2(v: Vector2, tolerance: number = 1e6): number {
// Multiply by the inverse of the tolerance to avoid division
const x = Math.floor(v.x * tolerance);
const y = Math.floor(v.y * tolerance);
return 0.5 * ((x + y) * (x + y + 1)) + y; // Pairing x and y
} | /**
* Calculates hash value of Vector2 using Cantor pairing
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/utils/MathUtils.ts#L153-L158 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | hash3 | function hash3(v: Vector3, tolerance: number = 1e6): number {
// Multiply by the inverse of the tolerance to avoid division
const x = Math.floor(v.x * tolerance);
const y = Math.floor(v.y * tolerance);
const z = Math.floor(v.z * tolerance);
const xy = 0.5 * ((x + y) * (x + y + 1)) + y;
return 0.5 * ((xy + z) * (xy + z + 1)) + z;
} | /**
* Returns true if p1 and p2 are effectively equal.
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/fracture/utils/MathUtils.ts#L163-L170 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | BreakableObject.fracture | fracture(
RAPIER: RAPIER_API,
world: RAPIER.World,
options: FractureOptions,
): PhysicsObject[] {
// Call the fracture function to split the mesh into fragments
return fracture(this.geometry, options).map((fragment) => {
const obj = new PhysicsObject();
// Use the original object as a template
obj.name = `${this.name}_fragment`;
obj.geometry = fragment;
obj.material = this.material;
obj.castShadow = true;
// Copy the position/rotation from the original object
obj.position.copy(this.position);
obj.rotation.copy(this.rotation);
// Create a new rigid body using the position/orientation of the original object
obj.rigidBody = world.createRigidBody(
RAPIER.RigidBodyDesc.dynamic()
.setTranslation(obj.position.x, obj.position.y, obj.position.z)
.setRotation(new THREE.Quaternion().setFromEuler(obj.rotation)),
);
// Preserve the velocity of the original object
obj.rigidBody.setAngvel(this.rigidBody!.angvel(), true);
obj.rigidBody.setLinvel(this.rigidBody!.linvel(), true);
return obj;
});
} | /**
* Fractures this mesh into smaller pieces
* @param RAPIER The RAPIER physics API
* @param world The physics world object
* @param options Options controlling how to fracture this object
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/physics/BreakableObject.ts#L20-L52 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | PhysicsManager.addObject | addObject(obj: PhysicsObject, colliderDesc: RAPIER.ColliderDesc) {
if (obj.rigidBody) {
this.world.createCollider(colliderDesc, obj.rigidBody);
this.worldObjects.set(obj.rigidBody.handle, obj);
}
} | /**
* Adds an object to the world
* @param obj The physics object
* @param colliderDesc Collider description for the object
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/physics/PhysicsManager.ts#L45-L50 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | PhysicsManager.removeObject | removeObject(obj: PhysicsObject) {
if (obj.rigidBody) {
this.world.removeRigidBody(obj.rigidBody);
this.worldObjects.delete(obj.rigidBody.handle);
}
} | /**
* Removes an object from the world
* @param obj
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/physics/PhysicsManager.ts#L56-L61 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | PhysicsManager.handleFracture | async handleFracture(obj: BreakableObject, scene: THREE.Scene) {
const fragments = obj.fracture(
this.RAPIER,
this.world,
this.fractureOptions,
);
// Add the fragments to the scene and the physics world
scene.add(...fragments);
// Map the handle for each rigid body to the physics object so we can
// quickly perform a lookup when handling collision events
fragments.forEach((fragment) => {
// Approximate collider using a convex hull. While fragments may not
// be convex, non-convex colliders are extremely expensive
const vertices = fragment.geometry.getAttribute("position")
.array as Float32Array;
const colliderDesc =
RAPIER.ColliderDesc.convexHull(vertices)!.setRestitution(0.2);
// If unable to generate convex hull, ignore fragment
if (colliderDesc) {
this.addObject(fragment, colliderDesc);
} else {
console.warn("Failed to generate convex hull for fragment");
}
});
// Remove the original object from the scene and the physics world
obj.removeFromParent();
this.removeObject(obj);
} | /**
* Handles fracturing `obj` into fragments and adding those to the scene
* @param obj The object to fracture
* @param scene The scene to add the resultant fragments to
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/physics/PhysicsManager.ts#L68-L99 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
three-pinata | github_2023 | dgreenheck | typescript | PhysicsManager.update | update(scene: THREE.Scene) {
// Step the physics world
this.world.step(this.eventQueue);
// Handle collisions
this.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
if (!started) return;
// Using the handles from the collision event, find the object that needs to be updated
const obj1 = this.worldObjects.get(handle1);
if (obj1 instanceof BreakableObject) {
this.handleFracture(obj1, scene);
}
const obj2 = this.worldObjects.get(handle2);
if (obj2 instanceof BreakableObject) {
this.handleFracture(obj2, scene);
}
});
// Update the position and rotation of each object
this.worldObjects.forEach((obj) => {
obj.update();
});
} | /**
* Updates the physics state and handles any collisions
* @param scene
*/ | https://github.com/dgreenheck/three-pinata/blob/3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0/src/physics/PhysicsManager.ts#L105-L129 | 3d2f3acbfb4d237a2cee93f4118711aa7c5fa0b0 |
screenshot-to-code | github_2023 | abi | typescript | fileToDataURL | function fileToDataURL(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file);
});
} | // TODO: Move to a separate file | https://github.com/abi/screenshot-to-code/blob/a240914b93d35ce17bc2263e2f9924b473e8bfa5/frontend/src/components/ImageUpload.tsx#L41-L48 | a240914b93d35ce17bc2263e2f9924b473e8bfa5 |
screenshot-to-code | github_2023 | abi | typescript | App.uploadImage | async uploadImage(screenshotPath: string) {
// Upload file
const fileInput = (await this.page.$(
".file-input"
)) as ElementHandle<HTMLInputElement>;
if (!fileInput) {
throw new Error("File input element not found");
}
await fileInput.uploadFile(screenshotPath);
await this._screenshot("image_uploaded");
// Click the generate button and wait for the code to be generated
await this._waitUntilVersionIsReady("v1");
await this._screenshot("image_results");
} | // Uploads a screenshot and generates the image | https://github.com/abi/screenshot-to-code/blob/a240914b93d35ce17bc2263e2f9924b473e8bfa5/frontend/src/tests/qa.test.ts#L215-L229 | a240914b93d35ce17bc2263e2f9924b473e8bfa5 |
screenshot-to-code | github_2023 | abi | typescript | App.edit | async edit(edit: string, version: string) {
// Type in the edit
await this.page.type(
'textarea[placeholder="Tell the AI what to change..."]',
edit
);
await this._screenshot(`typed_${version}`);
// Click the update button and wait for the code to be generated
await this.page.click(".update-btn");
await this._waitUntilVersionIsReady(version);
await this._screenshot(`done_${version}`);
} | // Makes a text edit and waits for a new version | https://github.com/abi/screenshot-to-code/blob/a240914b93d35ce17bc2263e2f9924b473e8bfa5/frontend/src/tests/qa.test.ts#L232-L244 | a240914b93d35ce17bc2263e2f9924b473e8bfa5 |
screenshot-to-code | github_2023 | abi | typescript | App.importFromCode | async importFromCode() {
await this.page.click(".import-from-code-btn");
await this.page.type("textarea", "<html>hello world</html>");
await this.page.select("#output-settings-js", "HTML + Tailwind");
await this._screenshot("typed_code");
await this.page.click(".import-btn");
await this._waitUntilVersionIsReady("v1");
} | // Work in progress | https://github.com/abi/screenshot-to-code/blob/a240914b93d35ce17bc2263e2f9924b473e8bfa5/frontend/src/tests/qa.test.ts#L263-L275 | a240914b93d35ce17bc2263e2f9924b473e8bfa5 |
ion | github_2023 | sst | typescript | createContext | const createContext = async (req: NextRequest) => {
return createTRPCContext({
headers: req.headers,
});
}; | /**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a HTTP request (e.g. when you make requests from Client Components).
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/examples/aws-t3/src/app/api/trpc/[trpc]/route.ts#L12-L16 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Linkable.getSSTLink | public getSSTLink() {
return this._definition;
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/linkable.ts#L197-L199 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Linkable.wrap | public static wrap<Resource>(
cls: { new(...args: any[]): Resource },
cb: (resource: Resource) => Definition,
) {
// @ts-expect-error
this.wrappedResources.add(cls.__pulumiType);
cls.prototype.getSSTLink = function() {
return cb(this);
};
} | /**
* Wrap any resource class to make it linkable. Behind the scenes this modifies the
* prototype of the given class.
*
* :::tip
* Use `Linkable.wrap` to make any resource linkable.
* :::
*
* @param cls The resource class to wrap.
* @param cb A callback that returns the definition for the linkable resource.
*
* @example
*
* Here we are wrapping the [`aws.dynamodb.Table`](https://www.pulumi.com/registry/packages/aws/api-docs/dynamodb/table/)
* class to make it linkable.
*
* ```ts title="sst.config.ts"
* Linkable.wrap(aws.dynamodb.Table, (table) => ({
* properties: { tableName: table.name },
* include: [
* sst.aws.permission({
* actions: ["dynamodb:*"],
* resources: [table.arn]
* })
* ]
* }));
* ```
*
* It's defining the properties that we want made accessible at runtime and the permissions
* that the linked resource should have.
*
* Now you can link any `aws.dynamodb.Table` instances in your app just like any other SST
* component.
*
* ```ts title="sst.config.ts" {7}
* const table = new aws.dynamodb.Table("MyTable", {
* attributes: [{ name: "id", type: "S" }],
* hashKey: "id",
* });
*
* new sst.aws.Nextjs("MyWeb", {
* link: [table]
* });
* ```
*
* Since this applies to any resource, you can also use it to wrap SST components and modify
* how they are linked.
*
* ```ts title="sst.config.ts" "sst.aws.Bucket"
* sst.Linkable.wrap(sst.aws.Bucket, (bucket) => ({
* properties: { name: bucket.name },
* include: [
* sst.aws.permission({
* actions: ["s3:GetObject"],
* resources: [bucket.arn]
* })
* ]
* }));
* ```
*
* This overrides the built-in link and lets you create your own.
*
* :::tip
* You can modify the permissions granted by a linked resource.
* :::
*
* In the above example, we're modifying the permissions to access a linked `sst.aws.Bucket`
* in our app.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/linkable.ts#L270-L280 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Resource.getSSTLink | public getSSTLink() {
return {
properties: this._properties,
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/linkable.ts#L314-L318 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Secret.constructor | constructor(name: string, placeholder?: string) {
super(
"sst:sst:Secret",
name,
{
placeholder,
},
{},
);
this._name = name;
this._placeholder = placeholder;
const value = process.env["SST_SECRET_" + this._name] ?? this._placeholder;
if (typeof value !== "string") {
throw new SecretMissingError(this._name);
}
this._value = value;
} | /**
* @param placeholder A placeholder value of the secret. This can be useful for cases where you might not be storing sensitive values.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/secret.ts#L107-L123 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Secret.name | public get name() {
return output(this._name);
} | /**
* The name of the secret.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/secret.ts#L128-L130 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Secret.value | public get value() {
return secret(this._value);
} | /**
* The value of the secret. It'll be `undefined` if the secret has not been set through the CLI or if the `placeholder` hasn't been set.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/secret.ts#L135-L137 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Secret.placeholder | public get placeholder() {
return output(this._placeholder);
} | /**
* The placeholder value of the secret.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/secret.ts#L142-L144 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Secret.getSSTLink | public getSSTLink() {
return {
properties: {
value: this.value,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/secret.ts#L147-L153 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Analog.url | public get url() {
return all([this.cdn?.domainUrl, this.cdn?.url, this.devUrl]).apply(
([domainUrl, url, dev]) => domainUrl ?? url ?? dev!,
);
} | /**
* The URL of the Analog app.
*
* If the `domain` is set, this is the URL with the custom domain.
* Otherwise, it's the autogenerated CloudFront URL.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/analog.ts#L527-L531 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Analog.nodes | public get nodes() {
return {
/**
* The AWS Lambda server function that renders the site.
*/
server: this.server,
/**
* The Amazon S3 Bucket that stores the assets.
*/
assets: this.assets,
/**
* The Amazon CloudFront CDN that serves the site.
*/
cdn: this.cdn,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/analog.ts#L536-L551 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Analog.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/analog.ts#L554-L560 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocketRoute.nodes | public get nodes() {
return {
/**
* The Lambda function.
*/
function: this.fn.apply((fn) => fn.getFunction()),
/**
* The Lambda permission.
*/
permission: this.permission,
/**
* The API Gateway HTTP API route.
*/
route: this.apiRoute,
/**
* The API Gateway HTTP API integration.
*/
integration: this.integration,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket-route.ts#L145-L164 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocket.url | public get url() {
// Note: If mapping key is set, the URL needs a trailing slash. Without the
// trailing slash, the API fails with the error {"message":"Not Found"}
return this.apigDomain && this.apiMapping
? all([this.apigDomain.domainName, this.apiMapping.apiMappingKey]).apply(
([domain, key]) =>
key ? `wss://${domain}/${key}/` : `wss://${domain}`,
)
: interpolate`${this.api.apiEndpoint}/${this.stage.name}`;
} | /**
* The URL of the API.
*
* If the `domain` is set, this is the URL with the custom domain.
* Otherwise, it's the autogenerated API Gateway URL.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket.ts#L446-L455 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocket.managementEndpoint | public get managementEndpoint() {
// ie. https://v1lmfez2nj.execute-api.us-east-1.amazonaws.com/$default
return this.api.apiEndpoint.apply(
(endpoint) =>
interpolate`${endpoint.replace("wss", "https")}/${this.stage.name}`,
);
} | /**
* The management endpoint for the API used by the API Gateway Management API client.
* This is useful for sending messages to connected clients.
*
* @example
* ```js
* import { Resource } from "sst";
* import { ApiGatewayManagementApiClient } from "@aws-sdk/client-apigatewaymanagementapi";
*
* const client = new ApiGatewayManagementApiClient({
* endpoint: Resource.MyApi.managementEndpoint,
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket.ts#L471-L477 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocket.nodes | public get nodes() {
const self = this;
return {
/**
* The Amazon API Gateway V2 API.
*/
api: this.api,
/**
* The API Gateway HTTP API domain name.
*/
get domainName() {
if (!self.apigDomain)
throw new VisibleError(
`"nodes.domainName" is not available when domain is not configured for the "${self.constructorName}" API.`,
);
return self.apigDomain;
},
/**
* The CloudWatch LogGroup for the access logs.
*/
logGroup: this.logGroup,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket.ts#L482-L504 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocket.route | public route(
route: string,
handler: Input<string | FunctionArgs | FunctionArn>,
args: ApiGatewayWebSocketRouteArgs = {},
) {
const prefix = this.constructorName;
const suffix = logicalName(
["$connect", "$disconnect", "$default"].includes(route)
? route
: hashStringToPrettyString(`${outputId}${route}`, 6),
);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
`${prefix}Route${suffix}`,
args,
{ provider: this.constructorOpts.provider },
);
return new ApiGatewayWebSocketRoute(
transformed[0],
{
api: {
name: prefix,
id: this.api.id,
executionArn: this.api.executionArn,
},
route,
handler,
handlerTransform: this.constructorArgs.transform?.route?.handler,
...transformed[1],
},
transformed[2],
);
} | /**
* Add a route to the API Gateway WebSocket API.
*
* There are three predefined routes:
* - `$connect`: When the client connects to the API.
* - `$disconnect`: When the client or the server disconnects from the API.
* - `$default`: The default or catch-all route.
*
* In addition, you can create custom routes. When a request comes in, the API Gateway
* will look for the specific route defined by the user. If no route matches, the `$default`
* route will be invoked.
*
* @param route The path for the route.
* @param handler The function that'll be invoked.
* @param args Configure the route.
*
* @example
* Add a simple route.
*
* ```js title="sst.config.ts"
* api.route("sendMessage", "src/sendMessage.handler");
* ```
*
* Add a predefined route.
*
* ```js title="sst.config.ts"
* api.route("$default", "src/default.handler");
* ```
*
* Enable auth for a route.
*
* ```js title="sst.config.ts"
* api.route("sendMessage", "src/sendMessage.handler", {
* auth: {
* iam: true
* }
* });
* ```
*
* Customize the route handler.
*
* ```js title="sst.config.ts"
* api.route("sendMessage", {
* handler: "src/sendMessage.handler",
* memory: "2048 MB"
* });
* ```
*
* Or pass in the ARN of an existing Lambda function.
*
* ```js title="sst.config.ts"
* api.route("sendMessage", "arn:aws:lambda:us-east-1:123456789012:function:my-function");
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket.ts#L560-L594 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayWebSocket.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
managementEndpoint: this.managementEndpoint,
},
include: [
permission({
actions: ["execute-api:ManageConnections"],
resources: [interpolate`${this.api.executionArn}/*/*/@connections/*`],
}),
],
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigateway-websocket.ts#L597-L610 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1Authorizer.id | public get id() {
return this.authorizer.id;
} | /**
* The ID of the authorizer.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1-authorizer.ts#L143-L145 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1Authorizer.nodes | public get nodes() {
const self = this;
return {
/**
* The API Gateway Authorizer.
*/
authorizer: this.authorizer,
/**
* The Lambda function used by the authorizer.
*/
get function() {
if (!self.fn)
throw new VisibleError(
"Cannot access `nodes.function` because the data source does not use a Lambda function.",
);
return self.fn;
},
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1-authorizer.ts#L150-L168 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1IntegrationRoute.nodes | public get nodes() {
return {
/**
* The API Gateway REST API integration.
*/
integration: this.integration,
/**
* The API Gateway REST API method.
*/
method: this.method,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1-integration-route.ts#L76-L87 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1LambdaRoute.nodes | public get nodes() {
return {
/**
* The Lambda function.
*/
function: this.fn.apply((fn) => fn.getFunction()),
/**
* The Lambda permission.
*/
permission: this.permission,
/**
* The API Gateway REST API integration.
*/
integration: this.integration,
/**
* The API Gateway REST API method.
*/
method: this.method,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1-lambda-route.ts#L109-L128 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.url | public get url() {
return this.apigDomain && this.apiMapping
? all([this.apigDomain.domainName, this.apiMapping.basePath]).apply(
([domain, key]) =>
key ? `https://${domain}/${key}/` : `https://${domain}`,
)
: interpolate`https://${this.api.id}.execute-api.${this.region}.amazonaws.com/${$app.stage}/`;
} | /**
* The URL of the API.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L719-L726 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.nodes | public get nodes() {
return {
/**
* The Amazon API Gateway REST API
*/
api: this.api,
/**
* The Amazon API Gateway REST API stage
*/
stage: this.stage,
/**
* The CloudWatch LogGroup for the access logs.
*/
logGroup: this.logGroup,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L731-L746 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.route | public route(
route: string,
handler: Input<string | FunctionArgs | FunctionArn>,
args: ApiGatewayV1RouteArgs = {},
) {
const { method, path } = this.parseRoute(route);
this.createResource(path);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
this.buildRouteId(method, path),
args,
{ provider: this.constructorOpts.provider },
);
const apigRoute = new ApiGatewayV1LambdaRoute(
transformed[0],
{
api: {
name: this.constructorName,
id: this.api.id,
executionArn: this.api.executionArn,
},
method,
path,
resourceId: this.resources[path],
handler,
handlerTransform: this.constructorArgs.transform?.route?.handler,
...transformed[1],
},
transformed[2],
);
this.routes.push(apigRoute);
return apigRoute;
} | /**
* Add a route to the API Gateway REST API. The route is a combination of an HTTP method and a path, `{METHOD} /{path}`.
*
* A method could be one of `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`, or `ANY`. Here `ANY` matches any HTTP method.
*
* The path can be a combination of
* - Literal segments, `/notes`, `/notes/new`, etc.
* - Parameter segments, `/notes/{noteId}`, `/notes/{noteId}/attachments/{attachmentId}`, etc.
* - Greedy segments, `/{proxy+}`, `/notes/{proxy+}`, etc. The `{proxy+}` segment is a greedy segment that matches all child paths. It needs to be at the end of the path.
*
* :::tip
* The `{proxy+}` is a greedy segment, it matches all its child paths.
* :::
*
* When a request comes in, the API Gateway will look for the most specific match.
*
* :::note
* You cannot have duplicate routes.
* :::
*
* @param route The path for the route.
* @param handler The function that'll be invoked.
* @param args Configure the route.
*
* @example
* Add a simple route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler");
* ```
*
* Match any HTTP method.
*
* ```js title="sst.config.ts"
* api.route("ANY /", "src/route.handler");
* ```
*
* Add a default route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler")
* api.route($default, "src/default.handler");
* ```
*
* Add a parameterized route.
*
* ```js title="sst.config.ts"
* api.route("GET /notes/{id}", "src/get.handler");
* ```
*
* Add a greedy route.
*
* ```js title="sst.config.ts"
* api.route("GET /notes/{proxy+}", "src/greedy.handler");
* ```
*
* Enable auth for a route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler")
* api.route("POST /", "src/post.handler", {
* auth: {
* iam: true
* }
* });
* ```
*
* Customize the route handler.
*
* ```js title="sst.config.ts"
* api.route("GET /", {
* handler: "src/get.handler",
* memory: "2048 MB"
* });
* ```
*
* Or pass in the ARN of an existing Lambda function.
*
* ```js title="sst.config.ts"
* api.route("GET /", "arn:aws:lambda:us-east-1:123456789012:function:my-function");
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L830-L866 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.routeIntegration | public routeIntegration(
route: string,
integration: ApiGatewayV1IntegrationArgs,
args: ApiGatewayV1RouteArgs = {},
) {
const { method, path } = this.parseRoute(route);
this.createResource(path);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
this.buildRouteId(method, path),
args,
{ provider: this.constructorOpts.provider },
);
const apigRoute = new ApiGatewayV1IntegrationRoute(
transformed[0],
{
api: {
name: this.constructorName,
id: this.api.id,
executionArn: this.api.executionArn,
},
method,
path,
resourceId: this.resources[path],
integration,
...transformed[1],
},
transformed[2],
);
this.routes.push(apigRoute);
return apigRoute;
} | /**
* Add a custom integration to the API Gateway REST API.
*
* Learn more about [integrations for REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-integration-settings.html).
*
* @param route The path for the route.
* @param integration The integration configuration.
* @param args Configure the route.
*
* @example
* Add a route to trigger a Step Functions state machine execution.
*
* ```js title="sst.config.ts"
* api.routeIntegration("POST /run-my-state-machine", {
* type: "aws",
* uri: "arn:aws:apigateway:us-east-1:states:startExecution",
* credentials: "arn:aws:iam::123456789012:role/apigateway-execution-role",
* integrationHttpMethod: "POST",
* requestTemplates: {
* "application/json": JSON.stringify({
* input: "$input.json('$')",
* stateMachineArn: "arn:aws:states:us-east-1:123456789012:stateMachine:MyStateMachine",
* }),
* },
* passthroughBehavior: "when-no-match",
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L896-L931 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.addAuthorizer | public addAuthorizer(args: ApiGatewayV1AuthorizerArgs) {
const self = this;
const selfName = this.constructorName;
const nameSuffix = logicalName(args.name);
return new ApiGatewayV1Authorizer(
`${selfName}Authorizer${nameSuffix}`,
{
api: {
id: self.api.id,
name: selfName,
executionArn: self.api.executionArn,
},
...args,
},
{ provider: this.constructorOpts.provider },
);
} | /**
* Add an authorizer to the API Gateway REST API.
*
* @param args Configure the authorizer.
* @example
* Add a Lambda token authorizer.
*
* ```js title="sst.config.ts"
* api.addAuthorizer({
* name: "myAuthorizer",
* tokenFunction: "src/authorizer.index"
* });
* ```
*
* Add a Lambda REQUEST authorizer.
*
* ```js title="sst.config.ts"
* api.addAuthorizer({
* name: "myAuthorizer",
* requestFunction: "src/authorizer.index"
* });
* ```
*
* Add a Cognito User Pool authorizer.
*
* ```js title="sst.config.ts"
* const userPool = new aws.cognito.UserPool();
*
* api.addAuthorizer({
* name: "myAuthorizer",
* userPools: [userPool.arn]
* });
* ```
*
* Customize the authorizer.
*
* ```js title="sst.config.ts"
* api.addAuthorizer({
* name: "myAuthorizer",
* tokenFunction: "src/authorizer.index",
* ttl: 30
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L1042-L1059 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.deploy | public deploy() {
const name = this.constructorName;
const args = this.constructorArgs;
const parent = this;
const api = this.api;
const routes = this.routes;
const endpointType = this.endpointType;
const accessLog = normalizeAccessLog();
const domain = normalizeDomain();
const corsRoutes = createCorsRoutes();
const corsResponses = createCorsResponses();
const deployment = createDeployment();
const logGroup = createLogGroup();
const stage = createStage();
const certificateArn = createSsl();
const apigDomain = createDomainName();
createDnsRecords();
const apiMapping = createDomainMapping();
this.logGroup = logGroup;
this.stage = stage;
this.apigDomain = apigDomain;
this.apiMapping = apiMapping;
this.registerOutputs({
_hint: this.url,
});
function normalizeAccessLog() {
return output(args.accessLog).apply((accessLog) => ({
...accessLog,
retention: accessLog?.retention ?? "forever",
}));
}
function normalizeDomain() {
if (!args.domain) return;
// validate
output(args.domain).apply((domain) => {
if (typeof domain === "string") return;
if (!domain.name) throw new Error(`Missing "name" for domain.`);
if (domain.dns === false && !domain.cert)
throw new Error(`No "cert" provided for domain with disabled DNS.`);
});
// normalize
return output(args.domain).apply((domain) => {
const norm = typeof domain === "string" ? { name: domain } : domain;
return {
name: norm.name,
path: norm.path,
dns: norm.dns === false ? undefined : norm.dns ?? awsDns(),
cert: norm.cert,
};
});
}
function createCorsRoutes() {
const resourceIds = routes.map(
(route) => route.nodes.integration.resourceId,
);
return all([args.cors, resourceIds]).apply(([cors, resourceIds]) => {
if (cors === false) return [];
// filter unique resource ids
const uniqueResourceIds = [...new Set(resourceIds)];
// create cors integrations for the paths
return uniqueResourceIds.map((resourceId) => {
const method = new apigateway.Method(
`${name}CorsMethod${resourceId}`,
{
restApi: api.id,
resourceId,
httpMethod: "OPTIONS",
authorization: "NONE",
},
{ parent },
);
const methodResponse = new apigateway.MethodResponse(
`${name}CorsMethodResponse${resourceId}`,
{
restApi: api.id,
resourceId,
httpMethod: method.httpMethod,
statusCode: "204",
responseParameters: {
"method.response.header.Access-Control-Allow-Headers": true,
"method.response.header.Access-Control-Allow-Methods": true,
"method.response.header.Access-Control-Allow-Origin": true,
},
},
{ parent },
);
const integration = new apigateway.Integration(
`${name}CorsIntegration${resourceId}`,
{
restApi: api.id,
resourceId,
httpMethod: method.httpMethod,
type: "MOCK",
requestTemplates: {
"application/json": "{ statusCode: 200 }",
},
},
{ parent },
);
const integrationResponse = new apigateway.IntegrationResponse(
`${name}CorsIntegrationResponse${resourceId}`,
{
restApi: api.id,
resourceId,
httpMethod: method.httpMethod,
statusCode: methodResponse.statusCode,
responseParameters: {
"method.response.header.Access-Control-Allow-Headers": "'*'",
"method.response.header.Access-Control-Allow-Methods":
"'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'",
"method.response.header.Access-Control-Allow-Origin": "'*'",
},
},
{ parent, dependsOn: [integration] },
);
return { method, methodResponse, integration, integrationResponse };
});
});
}
function createCorsResponses() {
return output(args.cors).apply((cors) => {
if (cors === false) return [];
return ["4XX", "5XX"].map(
(type) =>
new apigateway.Response(
`${name}Cors${type}Response`,
{
restApiId: api.id,
responseType: `DEFAULT_${type}`,
responseParameters: {
"gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
"gatewayresponse.header.Access-Control-Allow-Headers": "'*'",
},
responseTemplates: {
"application/json":
'{"message":$context.error.messageString}',
},
},
{ parent },
),
);
});
}
function createDeployment() {
const resources = all([corsRoutes, corsResponses]).apply(
([corsRoutes, corsResponses]) =>
[
api,
corsRoutes.map((v) => Object.values(v)),
corsResponses,
routes.map((route) => [
route.nodes.integration,
route.nodes.method,
]),
].flat(3),
);
// filter serializable output values
const resourcesSanitized = all([resources]).apply(([resources]) =>
resources.map((resource) =>
Object.fromEntries(
Object.entries(resource).filter(
([k, v]) => !k.startsWith("_") && typeof v !== "function",
),
),
),
);
return new apigateway.Deployment(
...transform(
args.transform?.deployment,
`${name}Deployment`,
{
restApi: api.id,
triggers: all([resourcesSanitized]).apply(([resources]) =>
Object.fromEntries(
resources.map((resource) => [
resource.urn,
JSON.stringify(resource),
]),
),
),
},
{ parent },
),
);
}
function createLogGroup() {
return new cloudwatch.LogGroup(
...transform(
args.transform?.accessLog,
`${name}AccessLog`,
{
name: `/aws/vendedlogs/apis/${physicalName(64, name)}`,
retentionInDays: accessLog.apply(
(accessLog) => RETENTION[accessLog.retention],
),
},
{ parent },
),
);
}
function createStage() {
return new apigateway.Stage(
...transform(
args.transform?.stage,
`${name}Stage`,
{
restApi: api.id,
stageName: $app.stage,
deployment: deployment.id,
accessLogSettings: {
destinationArn: logGroup.arn,
format: JSON.stringify({
// request info
requestTime: `"$context.requestTime"`,
requestId: `"$context.requestId"`,
httpMethod: `"$context.httpMethod"`,
path: `"$context.path"`,
resourcePath: `"$context.resourcePath"`,
status: `$context.status`, // integer value, do not wrap in quotes
responseLatency: `$context.responseLatency`, // integer value, do not wrap in quotes
xrayTraceId: `"$context.xrayTraceId"`,
// integration info
functionResponseStatus: `"$context.integration.status"`,
integrationRequestId: `"$context.integration.requestId"`,
integrationLatency: `"$context.integration.latency"`,
integrationServiceStatus: `"$context.integration.integrationStatus"`,
// caller info
ip: `"$context.identity.sourceIp"`,
userAgent: `"$context.identity.userAgent"`,
principalId: `"$context.authorizer.principalId"`,
}),
},
},
{ parent },
),
);
}
function createSsl() {
if (!domain) return;
return domain.apply((domain) => {
if (domain.cert) return output(domain.cert);
return new DnsValidatedCertificate(
`${name}Ssl`,
{
domainName: domain.name,
dns: domain.dns!,
},
{ parent },
).arn;
});
}
function createDomainName() {
if (!domain || !certificateArn) return;
return endpointType.apply(
(endpointType) =>
new apigateway.DomainName(
...transform(
args.transform?.domainName,
`${name}DomainName`,
{
domainName: domain?.name,
endpointConfiguration: { types: endpointType },
...(endpointType === "REGIONAL"
? { regionalCertificateArn: certificateArn }
: { certificateArn }),
},
{ parent },
),
),
);
}
function createDnsRecords(): void {
if (!domain || !apigDomain) {
return;
}
domain.dns.apply((dns) => {
if (!dns) return;
dns.createAlias(
name,
{
name: domain.name,
aliasName: endpointType.apply((v) =>
v === "EDGE"
? apigDomain.cloudfrontDomainName
: apigDomain.regionalDomainName,
),
aliasZone: endpointType.apply((v) =>
v === "EDGE"
? apigDomain.cloudfrontZoneId
: apigDomain.regionalZoneId,
),
},
{ parent },
);
});
}
function createDomainMapping() {
if (!domain || !apigDomain) return;
return domain.path?.apply(
(path) =>
new apigateway.BasePathMapping(
`${name}DomainMapping`,
{
restApi: api.id,
domainName: apigDomain.id,
stageName: stage.stageName,
basePath: path,
},
{ parent },
),
);
}
} | /**
* Create a deployment for the API Gateway REST API.
*
* :::note
* You need to call this after you've added all your routes.
* :::
*
* Due to the way API Gateway V1 is created internally, you'll need to call this method after
* you've added all your routes.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L1071-L1417 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV1.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv1.ts#L1420-L1426 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2Authorizer.id | public get id() {
return this.authorizer.id;
} | /**
* The ID of the authorizer.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2-authorizer.ts#L152-L154 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2Authorizer.nodes | public get nodes() {
return {
/**
* The API Gateway V2 authorizer.
*/
authorizer: this.authorizer,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2-authorizer.ts#L159-L166 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2LambdaRoute.nodes | public get nodes() {
return {
/**
* The Lambda function.
*/
function: this.fn.apply((fn) => fn.getFunction()),
/**
* The Lambda permission.
*/
permission: this.permission,
/**
* The API Gateway HTTP API route.
*/
route: this.apiRoute,
/**
* The API Gateway HTTP API integration.
*/
integration: this.integration,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2-lambda-route.ts#L113-L132 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2PrivateRoute.nodes | public get nodes() {
return {
/**
* The API Gateway HTTP API route.
*/
route: this.apiRoute,
/**
* The API Gateway HTTP API integration.
*/
integration: this.integration,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2-private-route.ts#L85-L96 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2UrlRoute.nodes | public get nodes() {
return {
/**
* The API Gateway HTTP API route.
*/
route: this.apiRoute,
/**
* The API Gateway HTTP API integration.
*/
integration: this.integration,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2-url-route.ts#L74-L85 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.url | public get url() {
// Note: If mapping key is set, the URL needs a trailing slash. Without the
// trailing slash, the API fails with the error {"message":"Not Found"}
return this.apigDomain && this.apiMapping
? all([this.apigDomain.domainName, this.apiMapping.apiMappingKey]).apply(
([domain, key]) =>
key ? `https://${domain}/${key}/` : `https://${domain}`,
)
: this.api.apiEndpoint;
} | /**
* The URL of the API.
*
* If the `domain` is set, this is the URL with the custom domain.
* Otherwise, it's the autogenerated API Gateway URL.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L926-L935 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.nodes | public get nodes() {
const self = this;
return {
/**
* The Amazon API Gateway HTTP API.
*/
api: this.api,
/**
* The API Gateway HTTP API domain name.
*/
get domainName() {
if (!self.apigDomain)
throw new VisibleError(
`"nodes.domainName" is not available when domain is not configured for the "${self.constructorName}" API.`,
);
return self.apigDomain;
},
/**
* The CloudWatch LogGroup for the access logs.
*/
logGroup: this.logGroup,
/**
* The API Gateway HTTP API VPC link.
*/
vpcLink: this.vpcLink,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L940-L966 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.route | public route(
rawRoute: string,
handler: Input<string | FunctionArgs | FunctionArn>,
args: ApiGatewayV2RouteArgs = {},
) {
const route = this.parseRoute(rawRoute);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
this.buildRouteId(route),
args,
{ provider: this.constructorOpts.provider },
);
return new ApiGatewayV2LambdaRoute(
transformed[0],
{
api: {
name: this.constructorName,
id: this.api.id,
executionArn: this.api.executionArn,
},
route,
handler,
handlerLink: this.constructorArgs.link,
handlerTransform: this.constructorArgs.transform?.route?.handler,
...transformed[1],
},
transformed[2],
);
} | /**
* Add a route to the API Gateway HTTP API. The route is a combination of
* - An HTTP method and a path, `{METHOD} /{path}`.
* - Or a `$default` route.
*
* :::tip
* The `$default` route is a default or catch-all route. It'll match if no other route matches.
* :::
*
* A method could be one of `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`, or `ANY`. Here `ANY` matches any HTTP method.
*
* The path can be a combination of
* - Literal segments, `/notes`, `/notes/new`, etc.
* - Parameter segments, `/notes/{noteId}`, `/notes/{noteId}/attachments/{attachmentId}`, etc.
* - Greedy segments, `/{proxy+}`, `/notes/{proxy+}`, etc. The `{proxy+}` segment is a greedy segment that matches all child paths. It needs to be at the end of the path.
*
* :::tip
* The `{proxy+}` is a greedy segment, it matches all its child paths.
* :::
*
* The `$default` is a reserved keyword for the default route. It'll be matched if no other route matches.
*
* :::note
* You cannot have duplicate routes.
* :::
*
* When a request comes in, the API Gateway will look for the most specific match. If no route matches, the `$default` route will be invoked.
*
* @param rawRoute The path for the route.
* @param handler The function that'll be invoked.
* @param args Configure the route.
*
* @example
* Add a simple route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler");
* ```
*
* Match any HTTP method.
*
* ```js title="sst.config.ts"
* api.route("ANY /", "src/route.handler");
* ```
*
* Add a default route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler")
* api.route($default, "src/default.handler");
* ```
*
* Add a parameterized route.
*
* ```js title="sst.config.ts"
* api.route("GET /notes/{id}", "src/get.handler");
* ```
*
* Add a greedy route.
*
* ```js title="sst.config.ts"
* api.route("GET /notes/{proxy+}", "src/greedy.handler");
* ```
*
* Enable auth for a route.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler")
* api.route("POST /", "src/post.handler", {
* auth: {
* iam: true
* }
* });
* ```
*
* Customize the route handler.
*
* ```js title="sst.config.ts"
* api.route("GET /", {
* handler: "src/get.handler",
* memory: "2048 MB"
* });
* ```
*
* Or pass in the ARN of an existing Lambda function.
*
* ```js title="sst.config.ts"
* api.route("GET /", "arn:aws:lambda:us-east-1:123456789012:function:my-function");
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L1058-L1086 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.routeUrl | public routeUrl(
rawRoute: string,
url: string,
args: ApiGatewayV2RouteArgs = {},
) {
const route = this.parseRoute(rawRoute);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
this.buildRouteId(route),
args,
{ provider: this.constructorOpts.provider },
);
return new ApiGatewayV2UrlRoute(
transformed[0],
{
api: {
name: this.constructorName,
id: this.api.id,
executionArn: this.api.executionArn,
},
route,
url,
...transformed[1],
},
transformed[2],
);
} | /**
* Add a URL route to the API Gateway HTTP API.
*
* @param rawRoute The path for the route.
* @param url The URL to forward to.
* @param args Configure the route.
*
* @example
* Add a simple route.
*
* ```js title="sst.config.ts"
* api.routeUrl("GET /", "https://google.com");
* ```
*
* Enable auth for a route.
*
* ```js title="sst.config.ts"
* api.routeUrl("POST /", "https://google.com", {
* auth: {
* iam: true
* }
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L1112-L1138 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.routePrivate | public routePrivate(
rawRoute: string,
arn: string,
args: ApiGatewayV2RouteArgs = {},
) {
if (!this.vpcLink)
throw new VisibleError(
`To add private routes, you need to have a VPC link. Configure "vpc" for the "${this.constructorName}" API to create a VPC link.`,
);
const route = this.parseRoute(rawRoute);
const transformed = transform(
this.constructorArgs.transform?.route?.args,
this.buildRouteId(route),
args,
{ provider: this.constructorOpts.provider },
);
return new ApiGatewayV2PrivateRoute(
transformed[0],
{
api: {
name: this.constructorName,
id: this.api.id,
executionArn: this.api.executionArn,
},
route,
vpcLink: this.vpcLink.id,
arn,
...transformed[1],
},
transformed[2],
);
} | /**
* Adds a private route to the API Gateway HTTP API.
*
* To add private routes, you need to have a VPC link. Make sure to pass in a `vpc`.
* Learn more about [adding private routes](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-private.html).
*
* :::tip
* You need to pass `vpc` to add a private route.
* :::
*
* @param rawRoute The path for the route.
* @param arn The ARN of the AWS Load Balander or Cloud Map service.
* @param args Configure the route.
*
* @example
* Add a route to Application Load Balander.
*
* ```js title="sst.config.ts"
* const loadBalancerArn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188";
* api.routePrivate("GET /", loadBalancerArn);
* ```
*
* Add a route to AWS Cloud Map service.
*
* ```js title="sst.config.ts"
* const serviceArn = "arn:aws:servicediscovery:us-east-2:123456789012:service/srv-id?stage=prod&deployment=green_deployment";
* api.routePrivate("GET /", serviceArn);
* ```
*
* Enable IAM authentication for a route.
*
* ```js title="sst.config.ts"
* api.routePrivate("GET /", serviceArn, {
* auth: {
* iam: true
* }
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L1179-L1211 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.addAuthorizer | public addAuthorizer(args: ApiGatewayV2AuthorizerArgs) {
const self = this;
const selfName = this.constructorName;
const nameSuffix = logicalName(args.name);
return new ApiGatewayV2Authorizer(
`${selfName}Authorizer${nameSuffix}`,
{
api: {
id: self.api.id,
name: selfName,
executionArn: this.api.executionArn,
},
...args,
},
{ provider: this.constructorOpts.provider },
);
} | /**
* Add an authorizer to the API Gateway HTTP API.
*
* @param args Configure the authorizer.
* @example
* Add a Lambda authorizer.
*
* ```js title="sst.config.ts"
* api.addAuthorizer({
* name: "myAuthorizer",
* lambda: {
* function: "src/authorizer.index"
* }
* });
* ```
*
* Add a JWT authorizer.
*
* ```js title="sst.config.ts"
* const authorizer = api.addAuthorizer({
* name: "myAuthorizer",
* jwt: {
* issuer: "https://issuer.com/",
* audiences: ["https://api.example.com"],
* identitySource: "$request.header.AccessToken"
* }
* });
* ```
*
* Add a Cognito UserPool as a JWT authorizer.
*
* ```js title="sst.config.ts"
* const pool = new sst.aws.CognitoUserPool("MyUserPool");
* const poolClient = userPool.addClient("Web");
*
* const authorizer = api.addAuthorizer({
* name: "myCognitoAuthorizer",
* jwt: {
* issuer: $interpolate`https://cognito-idp.${aws.getRegionOutput().name}.amazonaws.com/${pool.id}`,
* audiences: [poolClient.id]
* }
* });
* ```
*
* Now you can use the authorizer in your routes.
*
* ```js title="sst.config.ts"
* api.route("GET /", "src/get.handler", {
* auth: {
* jwt: {
* authorizer: authorizer.id
* }
* }
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L1311-L1328 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | ApiGatewayV2.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/apigatewayv2.ts#L1331-L1337 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSyncDataSource.name | public get name() {
return this.dataSource.name;
} | /**
* The name of the data source.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync-data-source.ts#L224-L226 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSyncDataSource.nodes | public get nodes() {
const self = this;
return {
/**
* The Amazon AppSync DataSource.
*/
dataSource: this.dataSource,
/**
* The Lambda function used by the data source.
*/
get function() {
if (!self.lambda)
throw new VisibleError(
"Cannot access `nodes.function` because the data source does not use a Lambda function.",
);
return self.lambda.apply((fn) => fn.getFunction());
},
/**
* The DataSource service's IAM role.
*/
get serviceRole() {
if (!self.serviceRole)
throw new VisibleError(
"Cannot access `nodes.serviceRole` because the data source does not have a service role.",
);
return self.serviceRole;
},
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync-data-source.ts#L231-L259 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSyncFunction.nodes | public get nodes() {
return {
/**
* The Amazon AppSync Function.
*/
function: this.fn,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync-function.ts#L67-L74 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSyncResolver.nodes | public get nodes() {
return {
/**
* The Amazon AppSync Resolver.
*/
resolver: this.resolver,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync-resolver.ts#L98-L105 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.id | public get id() {
return this.api.id;
} | /**
* The GraphQL API ID.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L630-L632 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.url | public get url() {
return this.domainName
? interpolate`https://${this.domainName.domainName}/graphql`
: this.api.uris["GRAPHQL"];
} | /**
* The URL of the GraphQL API.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L637-L641 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.nodes | public get nodes() {
return {
/**
* The Amazon AppSync GraphQL API.
*/
api: this.api,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L646-L653 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.addDataSource | public addDataSource(args: AppSyncDataSourceArgs) {
const self = this;
const selfName = this.constructorName;
const nameSuffix = logicalName(args.name);
return new AppSyncDataSource(
`${selfName}DataSource${nameSuffix}`,
{
apiId: self.api.id,
apiComponentName: selfName,
...args,
},
{ provider: this.constructorOpts.provider },
);
} | /**
* Add a data source to this AppSync API.
*
* @param args Configure the data source.
*
* @example
*
* Add a Lambda function as a data source.
*
* ```js title="sst.config.ts"
* api.addDataSource({
* name: "lambdaDS",
* lambda: "src/lambda.handler"
* });
* ```
*
* Customize the Lambda function.
*
* ```js title="sst.config.ts"
* api.addDataSource({
* name: "lambdaDS",
* lambda: {
* handler: "src/lambda.handler",
* timeout: "60 seconds"
* }
* });
* ```
*
* Add a data source with an existing Lambda function.
*
* ```js title="sst.config.ts"
* api.addDataSource({
* name: "lambdaDS",
* lambda: "arn:aws:lambda:us-east-1:123456789012:function:my-function"
* })
* ```
*
* Add a DynamoDB table as a data source.
*
* ```js title="sst.config.ts"
* api.addDataSource({
* name: "dynamoDS",
* dynamodb: "arn:aws:dynamodb:us-east-1:123456789012:table/my-table"
* })
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L701-L715 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.addFunction | public addFunction(args: AppSyncFunctionArgs) {
const self = this;
const selfName = this.constructorName;
const nameSuffix = logicalName(args.name);
return new AppSyncFunction(
`${selfName}Function${nameSuffix}`,
{
apiId: self.api.id,
...args,
},
{ provider: this.constructorOpts.provider },
);
} | /**
* Add a function to this AppSync API.
*
* @param args Configure the function.
*
* @example
*
* Add a function using a Lambda data source.
*
* ```js title="sst.config.ts"
* api.addFunction({
* name: "myFunction",
* dataSource: "lambdaDS",
* });
* ```
*
* Add a function using a DynamoDB data source.
*
* ```js title="sst.config.ts"
* api.addResolver("Query user", {
* name: "myFunction",
* dataSource: "dynamoDS",
* requestTemplate: `{
* "version": "2017-02-28",
* "operation": "Scan",
* }`,
* responseTemplate: `{
* "users": $utils.toJson($context.result.items)
* }`,
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L749-L762 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.addResolver | public addResolver(operation: string, args: AppSyncResolverArgs) {
const self = this;
const selfName = this.constructorName;
// Parse field and type
const parts = operation.trim().split(/\s+/);
if (parts.length !== 2)
throw new VisibleError(`Invalid resolver ${operation}`);
const [type, field] = parts;
const nameSuffix = `${logicalName(type)}` + `${logicalName(field)}`;
return new AppSyncResolver(
`${selfName}Resolver${nameSuffix}`,
{
apiId: self.api.id,
type,
field,
...args,
},
{ provider: this.constructorOpts.provider },
);
} | /**
* Add a resolver to this AppSync API.
*
* @param operation The type and name of the operation.
* @param args Configure the resolver.
*
* @example
*
* Add a resolver using a Lambda data source.
*
* ```js title="sst.config.ts"
* api.addResolver("Query user", {
* dataSource: "lambdaDS",
* });
* ```
*
* Add a resolver using a DynamoDB data source.
*
* ```js title="sst.config.ts"
* api.addResolver("Query user", {
* dataSource: "dynamoDS",
* requestTemplate: `{
* "version": "2017-02-28",
* "operation": "Scan",
* }`,
* responseTemplate: `{
* "users": $utils.toJson($context.result.items)
* }`,
* });
* ```
*
* Add a pipeline resolver.
*
* ```js title="sst.config.ts"
* api.addResolver("Query user", {
* functions: [
* "MyFunction1",
* "MyFunction2"
* ]
* code: `
* export function request(ctx) {
* return {};
* }
* export function response(ctx) {
* return ctx.result;
* }
* `,
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L814-L835 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | AppSync.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/app-sync.ts#L838-L844 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Astro.url | public get url() {
return all([this.cdn?.domainUrl, this.cdn?.url, this.devUrl]).apply(
([domainUrl, url, dev]) => domainUrl ?? url ?? dev!,
);
} | /**
* The URL of the Astro site.
*
* If the `domain` is set, this is the URL with the custom domain.
* Otherwise, it's the autogenerated CloudFront URL.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/astro.ts#L616-L620 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Astro.nodes | public get nodes() {
return {
/**
* The AWS Lambda server function that renders the site.
*/
server: this.server,
/**
* The Amazon S3 Bucket that stores the assets.
*/
assets: this.assets,
/**
* The Amazon CloudFront CDN that serves the site.
*/
cdn: this.cdn,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/astro.ts#L625-L640 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Astro.getSSTLink | public getSSTLink() {
return {
properties: {
url: this.url,
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/astro.ts#L643-L649 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Auth.getSSTLink | public getSSTLink() {
return {
properties: {
publicKey: secret(this.key.publicKeyPem),
},
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/auth.ts#L57-L63 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | BucketLambdaSubscriber.nodes | public get nodes() {
return {
/**
* The Lambda function that'll be notified.
*/
function: this.fn.apply((fn) => fn.getFunction()),
/**
* The Lambda permission.
*/
permission: this.permission,
/**
* The S3 bucket notification.
*/
notification: this.notification,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket-lambda-subscriber.ts#L138-L153 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | BucketQueueSubscriber.nodes | public get nodes() {
return {
/**
* The SQS Queue policy.
*/
policy: this.policy,
/**
* The S3 Bucket notification.
*/
notification: this.notification,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket-queue-subscriber.ts#L129-L140 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | BucketTopicSubscriber.nodes | public get nodes() {
return {
/**
* The SNS Topic policy.
*/
policy: this.policy,
/**
* The S3 Bucket notification.
*/
notification: this.notification,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket-topic-subscriber.ts#L128-L139 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.name | public get name() {
return this.bucket.bucket;
} | /**
* The generated name of the S3 Bucket.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L531-L533 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.domain | public get domain() {
return this.bucket.bucketDomainName;
} | /**
* The domain name of the bucket. Has the format `${bucketName}.s3.amazonaws.com`.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L538-L540 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.arn | public get arn() {
return this.bucket.arn;
} | /**
* The ARN of the S3 Bucket.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L545-L547 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.nodes | public get nodes() {
return {
/**
* The Amazon S3 bucket.
*/
bucket: this.bucket,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L552-L559 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.get | public static get(name: string, bucketName: string) {
return new Bucket(name, {
ref: true,
bucket: s3.BucketV2.get(`${name}Bucket`, bucketName),
} as BucketArgs);
} | /**
* Reference an existing bucket with the given bucket name. This is useful when you
* create a bucket in one stage and want to share it in another stage. It avoids having to
* create a new bucket in the other stage.
*
* :::tip
* You can use the `static get` method to share buckets across stages.
* :::
*
* @param name The name of the component.
* @param bucketName The name of the existing S3 Bucket.
*
* @example
* Imagine you create a bucket in the `dev` stage. And in your personal stage `frank`,
* instead of creating a new bucket, you want to share the bucket from `dev`.
*
* ```ts title="sst.config.ts"
* const bucket = $app.stage === "frank"
* ? sst.aws.Bucket.get("MyBucket", "app-dev-mybucket-12345678")
* : new sst.aws.Bucket("MyBucket");
* ```
*
* Here `app-dev-mybucket-12345678` is the auto-generated bucket name for the bucket created
* in the `dev` stage. You can find this by outputting the bucket name in the `dev` stage.
*
* ```ts title="sst.config.ts"
* return {
* bucket: bucket.name
* };
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L592-L597 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribe | public subscribe(
subscriber: Input<string | FunctionArgs | FunctionArn>,
args?: BucketSubscriberArgs,
) {
this.ensureNotSubscribed();
return Bucket._subscribeFunction(
this.constructorName,
this.bucket.bucket,
this.bucket.arn,
subscriber,
args,
{ provider: this.constructorOpts.provider },
);
} | /**
* Subscribe to events from this bucket.
*
* @param subscriber The function that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* ```js title="sst.config.ts"
* bucket.subscribe("src/subscriber.handler");
* ```
*
* Subscribe to specific S3 events. The `link` ensures the subscriber can access the bucket.
*
* ```js title="sst.config.ts" "link: [bucket]"
* bucket.subscribe({
* handler: "src/subscriber.handler",
* link: [bucket]
* }, {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* bucket.subscribe("src/subscriber.handler", {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Customize the subscriber function.
*
* ```js title="sst.config.ts"
* bucket.subscribe({
* handler: "src/subscriber.handler",
* timeout: "60 seconds",
* });
* ```
*
* Or pass in the ARN of an existing Lambda function.
*
* ```js title="sst.config.ts"
* bucket.subscribe("arn:aws:lambda:us-east-1:123456789012:function:my-function");
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L646-L659 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribe | public static subscribe(
bucketArn: Input<string>,
subscriber: Input<string | FunctionArgs | FunctionArn>,
args?: BucketSubscriberArgs,
) {
return output(bucketArn).apply((bucketArn) => {
const bucketName = parseBucketArn(bucketArn).bucketName;
return this._subscribeFunction(
bucketName,
bucketName,
bucketArn,
subscriber,
args,
);
});
} | /**
* Subscribe to events of an S3 bucket that was not created in your app.
*
* @param bucketArn The ARN of the S3 bucket to subscribe to.
* @param subscriber The function that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have an existing S3 bucket with the following ARN.
*
* ```js title="sst.config.ts"
* const bucketArn = "arn:aws:s3:::my-bucket";
* ```
*
* You can subscribe to it by passing in the ARN.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribe(bucketArn, "src/subscriber.handler");
* ```
*
* Subscribe to specific S3 events.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribe(bucketArn, "src/subscriber.handler", {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* sst.aws.Bucket.subscribe(bucketArn, "src/subscriber.handler", {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Customize the subscriber function.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribe(bucketArn, {
* handler: "src/subscriber.handler",
* timeout: "60 seconds",
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L708-L723 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribeQueue | public subscribeQueue(
queueArn: Input<string>,
args: BucketSubscriberArgs = {},
) {
this.ensureNotSubscribed();
return Bucket._subscribeQueue(
this.constructorName,
this.bucket.bucket,
this.arn,
queueArn,
args,
{ provider: this.constructorOpts.provider },
);
} | /**
* Subscribe to events from this bucket with an SQS Queue.
*
* @param queueArn The ARN of the queue that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have a queue.
*
* ```js title="sst.config.ts"
* const queue = sst.aws.Queue("MyQueue");
* ```
*
* You can subscribe to this bucket with it.
*
* ```js title="sst.config.ts"
* bucket.subscribe(queue.arn);
* ```
*
* Subscribe to specific S3 events.
*
* ```js title="sst.config.ts"
* bucket.subscribe(queue.arn, {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* bucket.subscribe(queue.arn, {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L791-L804 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribeQueue | public static subscribeQueue(
bucketArn: Input<string>,
queueArn: Input<string>,
args?: BucketSubscriberArgs,
) {
return output(bucketArn).apply((bucketArn) => {
const bucketName = parseBucketArn(bucketArn).bucketName;
return this._subscribeQueue(
bucketName,
bucketName,
bucketArn,
queueArn,
args,
);
});
} | /**
* Subscribe to events of an S3 bucket that was not created in your app with an SQS Queue.
*
* @param bucketArn The ARN of the S3 bucket to subscribe to.
* @param queueArn The ARN of the queue that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have an existing S3 bucket and SQS queue with the following ARNs.
*
* ```js title="sst.config.ts"
* const bucketArn = "arn:aws:s3:::my-bucket";
* const queueArn = "arn:aws:sqs:us-east-1:123456789012:MyQueue";
* ```
*
* You can subscribe to the bucket with the queue.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribeQueue(bucketArn, queueArn);
* ```
*
* Subscribe to specific S3 events.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribeQueue(bucketArn, queueArn, {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* sst.aws.Bucket.subscribeQueue(bucketArn, queueArn, {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L845-L860 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribeTopic | public subscribeTopic(
topicArn: Input<string>,
args: BucketSubscriberArgs = {},
) {
this.ensureNotSubscribed();
return Bucket._subscribeTopic(
this.constructorName,
this.bucket.bucket,
this.arn,
topicArn,
args,
{ provider: this.constructorOpts.provider },
);
} | /**
* Subscribe to events from this bucket with an SNS Topic.
*
* @param topicArn The ARN of the topic that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have a topic.
*
* ```js title="sst.config.ts"
* const topic = sst.aws.SnsTopic("MyTopic");
* ```
*
* You can subscribe to this bucket with it.
*
* ```js title="sst.config.ts"
* bucket.subscribe(topic.arn);
* ```
*
* Subscribe to specific S3 events.
*
* ```js title="sst.config.ts"
* bucket.subscribe(topic.arn, {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* bucket.subscribe(topic.arn, {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L925-L938 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.subscribeTopic | public static subscribeTopic(
bucketArn: Input<string>,
topicArn: Input<string>,
args?: BucketSubscriberArgs,
) {
return output(bucketArn).apply((bucketArn) => {
const bucketName = parseBucketArn(bucketArn).bucketName;
return this._subscribeTopic(
bucketName,
bucketName,
bucketArn,
topicArn,
args,
);
});
} | /**
* Subscribe to events of an S3 bucket that was not created in your app with an SNS Topic.
*
* @param bucketArn The ARN of the S3 bucket to subscribe to.
* @param topicArn The ARN of the topic that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have an existing S3 bucket and SNS topic with the following ARNs.
*
* ```js title="sst.config.ts"
* const bucketArn = "arn:aws:s3:::my-bucket";
* const topicArn = "arn:aws:sns:us-east-1:123456789012:MyTopic";
* ```
*
* You can subscribe to the bucket with the topic.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribe(bucketArn, topicArn);
* ```
*
* Subscribe to specific S3 events.
*
* ```js title="sst.config.ts"
* sst.aws.Bucket.subscribe(bucketArn, topicArn, {
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*
* Subscribe to specific S3 events from a specific folder.
*
* ```js title="sst.config.ts" {2}
* sst.aws.Bucket.subscribe(bucketArn, topicArn, {
* filterPrefix: "images/",
* events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L979-L994 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bucket.getSSTLink | public getSSTLink() {
return {
properties: {
name: this.name,
},
include: [
permission({
actions: ["s3:*"],
resources: [this.arn, interpolate`${this.arn}/*`],
}),
],
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bucket.ts#L1061-L1073 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | BusLambdaSubscriber.nodes | public get nodes() {
return {
/**
* The Lambda function that'll be notified.
*/
function: this.fn.apply((fn) => fn.getFunction()),
/**
* The Lambda permission.
*/
permission: this.permission,
/**
* The EventBus rule.
*/
rule: this.rule,
/**
* The EventBus target.
*/
target: this.target,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus-lambda-subscriber.ts#L133-L152 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bus.name | public get name() {
return this.bus.name;
} | /**
* The name of the EventBus.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus.ts#L202-L204 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bus.nodes | public get nodes() {
return {
/**
* The Amazon EventBus resource.
*/
bus: this.bus,
};
} | /**
* The underlying [resources](/docs/components/#nodes) this component creates.
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus.ts#L209-L216 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bus.subscribe | public subscribe(
subscriber: Input<string | FunctionArgs | FunctionArn>,
args: BusSubscriberArgs = {},
) {
return Bus._subscribeFunction(
this.constructorName,
this.nodes.bus.name,
this.nodes.bus.arn,
subscriber,
args,
{ provider: this.constructorOpts.provider },
);
} | /**
* Subscribe to this EventBus.
*
* @param subscriber The function that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* ```js
* bus.subscribe("src/subscriber.handler");
* ```
*
* Add a pattern to the subscription.
*
* ```js
* bus.subscribe("src/subscriber.handler", {
* pattern: {
* source: ["my.source", "my.source2"],
* price_usd: [{numeric: [">=", 100]}]
* }
* });
* ```
*
* Customize the subscriber function.
*
* ```js
* bus.subscribe({
* handler: "src/subscriber.handler",
* timeout: "60 seconds"
* });
* ```
*
* Or pass in the ARN of an existing Lambda function.
*
* ```js title="sst.config.ts"
* bus.subscribe("arn:aws:lambda:us-east-1:123456789012:function:my-function");
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus.ts#L256-L268 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bus.subscribe | public static subscribe(
busArn: Input<string>,
subscriber: Input<string | FunctionArgs | FunctionArn>,
args?: BusSubscriberArgs,
) {
return output(busArn).apply((busArn) => {
const busName = parseEventBusArn(busArn).busName;
return this._subscribeFunction(
logicalName(busName),
busName,
busArn,
subscriber,
args,
);
});
} | /**
* Subscribe to an EventBus that was not created in your app.
*
* @param busArn The ARN of the EventBus to subscribe to.
* @param subscriber The function that'll be notified.
* @param args Configure the subscription.
*
* @example
*
* For example, let's say you have an existing EventBus with the following ARN.
*
* ```js
* const busArn = "arn:aws:events:us-east-1:123456789012:event-bus/my-bus";
* ```
*
* You can subscribe to it by passing in the ARN.
*
* ```js
* sst.aws.Bus.subscribe(busArn, "src/subscriber.handler");
* ```
*
* Add a pattern to the subscription.
*
* ```js
* sst.aws.Bus.subscribe(busArn, "src/subscriber.handler", {
* pattern: {
* price_usd: [{numeric: [">=", 100]}]
* }
* });
* ```
*
* Customize the subscriber function.
*
* ```js
* sst.aws.Bus.subscribe(busArn, {
* handler: "src/subscriber.handler",
* timeout: "60 seconds"
* });
* ```
*/ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus.ts#L310-L325 | d5c4855b2618198f5e9af315c5e67d4163df165a |
ion | github_2023 | sst | typescript | Bus.getSSTLink | public getSSTLink() {
return {
properties: {
name: this.name,
arn: this.nodes.bus.arn,
},
include: [
permission({
actions: ["events:*"],
resources: [this.nodes.bus.arn],
}),
],
};
} | /** @internal */ | https://github.com/sst/ion/blob/d5c4855b2618198f5e9af315c5e67d4163df165a/platform/src/components/aws/bus.ts#L360-L373 | d5c4855b2618198f5e9af315c5e67d4163df165a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.