repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
cloudypad
github_2023
PierreBeucher
typescript
humanReadableArgs
const humanReadableArgs = (obj?: any, parentKey?: string): string => { if(obj === undefined){ return "" } return Object.keys(obj).map(key => { // If parent key is not empty, add a dot between parent key and current key // Otherwise, use current key (only for first level iteration) const fullKey = parentKey ? `${parentKey} ${key}` : key; // If value is an object, recursively transform it if (typeof obj[key] === 'object' && obj[key] !== null && obj[key] !== undefined) { return humanReadableArgs(obj[key], fullKey); } // Tranform original key into human readable key, with MAJ on first letter of each word let humanReadableKey = fullKey.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()) if(humanReadableKey.startsWith("Ssh")){ humanReadableKey = humanReadableKey.replace("Ssh", "SSH") } if(humanReadableKey.startsWith("Ip")){ humanReadableKey = humanReadableKey.replace("Ip", "IP") } // Transform value into human readable value (don't transform raw type into string) const humanReadableValue = typeof obj[key] === 'boolean' ? obj[key] ? 'Yes' : 'No' : obj[key] === undefined || obj[key] === null ? 'None' : String(obj[key]) return `${humanReadableKey}: ${humanReadableValue}`; }).join('\n '); };
// Shamelessly generated by IA and edited/commented by hand
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/provisioner.ts#L103-L138
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
ConfigManager.constructor
constructor(dataRootDir?: string) { this.dataRootDir = dataRootDir ?? DataRootDirManager.getEnvironmentDataRootDir() this.configPath = path.join(this.dataRootDir, 'config.yml') }
/** * Do not call constructor directly. Use getInstance() instead. * @param dataRootDir Do not use default dataRootDir. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/config/manager.ts#L61-L64
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
ConfigManager.init
init(): void { if (!fs.existsSync(this.configPath)) { this.logger.info(`CLI config not found at ${this.configPath}. Creating default config...`) const initConfig = lodash.merge( {}, BASE_DEFAULT_CONFIG, { analytics: { posthog: { distinctId: uuidv4(), collectionMethod: "technical" } } } ) this.writeConfigSafe(initConfig) this.logger.debug(`Generated default config: ${JSON.stringify(initConfig)}`) this.logger.info(`Default config created at ${this.configPath}`) } this.logger.debug(`Init: found existing config at ${this.configPath}. Not overwriting it.`) }
/** * Initialize configuration if needed: * - Create default config.yml in root data dir if none already exists, prompting user for details * - If one already exists, parse it */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/config/manager.ts#L78-L101
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateInitializer.initializeState
public async initializeState(): Promise<InstanceStateV1> { const instanceName = this.args.input.instanceName const input = this.args.input this.logger.debug(`Initializing a new instance with config ${JSON.stringify(input)}`) // Create the initial state const initialState: InstanceStateV1 = { version: "1", name: instanceName, provision: { provider: this.args.provider, input: input.provision, output: undefined }, configuration: { configurator: CLOUDYPAD_CONFIGURATOR_ANSIBLE, input: input.configuration, output: undefined, } } const writer = new StateWriter({ state: initialState, }) await writer.persistStateNow() return initialState }
/** * Initialize instance: * - Prompt for common and provisioner-specific configs * - Initialize state * - Run provision * - Run configuration * - Optionally pair instance * @param opts */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/initializer.ts#L30-L59
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.instanceExists
async instanceExists(instanceName: string): Promise<boolean> { const instanceDir = this.getInstanceDir(instanceName) const instanceStateV1Path = this.getInstanceStatePath(instanceName) this.logger.debug(`Checking instance ${instanceName} in directory ${instanceStateV1Path} at ${instanceDir}`) return fs.existsSync(instanceDir) && fs.existsSync(instanceStateV1Path) }
/** * Check an instance exists. An instance is considering existing if the folder * ${dataRootDir}/instances/<instance_name> exists and contains a state. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L49-L56
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.loadRawInstanceState
private async loadRawInstanceState(instanceName: string): Promise<unknown> { this.logger.debug(`Loading instance state ${instanceName}`) if (!(await this.instanceExists(instanceName))) { throw new Error(`Instance named '${instanceName}' does not exist.`) } const instanceStatePath = this.getInstanceStatePath(instanceName) if(fs.existsSync(instanceStatePath)) { this.logger.debug(`Loading instance V1 state for ${instanceName} at ${instanceStatePath}`) return yaml.load(fs.readFileSync(instanceStatePath, 'utf8')) } else { throw new Error(`Instance '${instanceName}' state not found at '${instanceStatePath}'`) } }
/** * Load raw instance state from disk. Loaded state is NOT type-checked. * First try to load state V1, then State V0 before failing */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L62-L78
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.loadAndMigrateInstanceState
async loadAndMigrateInstanceState(instanceName: string): Promise<InstanceStateV1> { await new StateMigrator({ dataRootDir: this.dataRootDir }).ensureInstanceStateV1(instanceName) // state is unchecked, any is acceptable at this point // eslint-disable-next-line @typescript-eslint/no-explicit-any const rawState = await this.loadRawInstanceState(instanceName) as any if(rawState.version != "1") { throw new Error(`Unknown state version '${rawState.version}'`) } const parser = new AnonymousStateParser() return parser.parse(rawState) }
/** * Load and migrate an instance state to the latest version safely (by validating schema and throwing on error) * This method should be called before trying to parse the state for a provider */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L84-L97
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateMigrator.needMigration
async needMigration(instanceName: string): Promise<boolean>{ const v0InstancePath = this.getInstanceStateV0Path(instanceName) this.logger.debug(`Checking if instance ${instanceName} needs migration using ${v0InstancePath}`) if(fs.existsSync(this.getInstanceDir(instanceName)) && fs.existsSync(v0InstancePath)) { return true } return false }
/** * * @param instanceName */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/migrator.ts#L23-L34
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateMigrator.doMigrateStateV0toV1
private async doMigrateStateV0toV1(rawState: any): Promise<AnyInstanceStateV1>{ const stateV0 = rawState as InstanceStateV0 const name = stateV0.name // Transform provider const providerV0 = stateV0.provider let stateV1: AnyInstanceStateV1 let providerName: CLOUDYPAD_PROVIDER const defaultConfigurationInput: CommonConfigurationInputV1 = { sunshine: null, wolf: { enable: true } } try { if(!stateV0.ssh || !stateV0.ssh.user || !stateV0.ssh.privateKeyPath) { throw new Error("Missing SSH config in state. Was instance fully configured ?") } if(providerV0?.aws) { providerName = CLOUDYPAD_PROVIDER_AWS if(!providerV0.aws.provisionArgs || !providerV0.aws.provisionArgs.create){ throw new Error("Missing AWS provision args in state. Was instance fully configured ?") } if(providerV0.aws.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_STATIC && providerV0.aws.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_DYNAMIC) { throw new Error(`Public IP type is neither ${PUBLIC_IP_TYPE_STATIC} nor ${PUBLIC_IP_TYPE_DYNAMIC}`) } const awsState: AwsInstanceStateV1 = { name: name, version: "1", provision: { provider: providerName, input: { ...providerV0.aws.provisionArgs.create, publicIpType: providerV0.aws.provisionArgs.create.publicIpType, ssh: { user: stateV0.ssh.user, privateKeyPath: stateV0.ssh.privateKeyPath }, } }, configuration: { configurator: CLOUDYPAD_CONFIGURATOR_ANSIBLE, input: defaultConfigurationInput } } if(stateV0.host){ if(!providerV0.aws.instanceId){ throw new Error(`Invalid state: host is defined but not AWS instance ID.`) } awsState.provision.output = { host: stateV0.host, instanceId: providerV0.aws.instanceId, } } stateV1 = awsState } else if (providerV0?.azure) { providerName = CLOUDYPAD_PROVIDER_AZURE if(!providerV0.azure.provisionArgs || !providerV0.azure.provisionArgs.create){ throw new Error("Missing Azure provision args in state. Was instance fully configured ?") } if(providerV0.azure.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_STATIC && providerV0.azure.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_DYNAMIC) { throw new Error(`Public IP type is neither ${PUBLIC_IP_TYPE_STATIC} nor ${PUBLIC_IP_TYPE_DYNAMIC}`) } const azureState: AzureInstanceStateV1 = { name: name, version: "1", provision: { provider: providerName, input: { ...providerV0.azure.provisionArgs.create, publicIpType: providerV0.azure.provisionArgs.create.publicIpType, diskType: AZURE_SUPPORTED_DISK_TYPES.STANDARD_LRS, ssh: { user: stateV0.ssh.user, privateKeyPath: stateV0.ssh.privateKeyPath }, }, }, configuration: { configurator: CLOUDYPAD_CONFIGURATOR_ANSIBLE, input: defaultConfigurationInput }, } if(stateV0.host){ if(!providerV0.azure.vmName || !providerV0.azure.resourceGroupName){ throw new Error(`Invalid state: host is defined but Azure VM name and/or Resource Group is missing.`) } azureState.provision.output = { host: stateV0.host, resourceGroupName: providerV0.azure.resourceGroupName, vmName: providerV0.azure.vmName } } stateV1 = azureState } else if (providerV0?.gcp) { providerName = CLOUDYPAD_PROVIDER_GCP if(!providerV0.gcp.provisionArgs || !providerV0.gcp.provisionArgs.create){ throw new Error("Missing Google provision args in state. Was instance fully provisioned ?") } if(providerV0.gcp.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_STATIC && providerV0.gcp.provisionArgs.create.publicIpType !== PUBLIC_IP_TYPE_DYNAMIC) { throw new Error(`Public IP type is neither ${PUBLIC_IP_TYPE_STATIC} nor ${PUBLIC_IP_TYPE_DYNAMIC}`) } const gcpState: GcpInstanceStateV1 = { name: name, version: "1", provision: { provider: providerName, input: { ...providerV0.gcp.provisionArgs.create, publicIpType: providerV0.gcp.provisionArgs.create.publicIpType, ssh: { user: stateV0.ssh.user, privateKeyPath: stateV0.ssh.privateKeyPath }, }, }, configuration: { configurator: CLOUDYPAD_CONFIGURATOR_ANSIBLE, input: defaultConfigurationInput }, } if(stateV0.host){ if(!providerV0.gcp.instanceName){ throw new Error(`Invalid state: host is defined but GCP instance name is missing.`) } gcpState.provision.output = { host: stateV0.host, instanceName: providerV0.gcp.instanceName } } stateV1 = gcpState } else if (providerV0?.paperspace) { providerName = CLOUDYPAD_PROVIDER_PAPERSPACE if(!providerV0.paperspace.provisionArgs || !providerV0.paperspace.provisionArgs.create){ throw new Error("Missing Paperspace provision args in state. Was instance fully configured ?") } if(!providerV0.paperspace.apiKey && !providerV0.paperspace.provisionArgs.apiKey){ throw new Error("Missing Paperspace API Key. Was instance fully configured ?") } const pspaceState: PaperspaceInstanceStateV1 = { name: name, version: "1", provision: { provider: providerName, input: { ...providerV0.paperspace.provisionArgs.create, apiKey: providerV0.paperspace.apiKey ?? providerV0.paperspace.provisionArgs.apiKey, ssh: { user: stateV0.ssh.user, privateKeyPath: stateV0.ssh.privateKeyPath }, }, }, configuration: { configurator: CLOUDYPAD_CONFIGURATOR_ANSIBLE, input: defaultConfigurationInput } } if(stateV0.host){ if(!providerV0.paperspace.machineId){ throw new Error(`Invalid state: host is defined but Paperspace machine ID and/or API Key is missing.`) } pspaceState.provision.output = { host: stateV0.host, machineId: providerV0.paperspace.machineId } } stateV1 = pspaceState } else { throw new Error(`Unknwon provider in state ${JSON.stringify(providerV0)}`) } } catch (e) { throw new Error(`Unable to migrate State from V0 to V1.` + `Please create an issue with full error log and state: ${JSON.stringify(rawState)}`, { cause: e }) } return stateV1 }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/migrator.ts#L70-L287
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.instanceName
instanceName(): string { return this.state.name }
/** * @returns instance name for managed State */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L66-L68
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.cloneState
cloneState(): ST { return lodash.cloneDeep(this.state) }
/** * Return a clone of managed State. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L73-L75
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.persistStateNow
async persistStateNow(){ await this.updateState(this.state) }
/** * Persist managed State on disk. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L80-L82
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.destroyInstanceStateDirectory
async destroyInstanceStateDirectory(){ await this.removeInstanceDir() }
/** * Effectively destroy instance state and it's directory */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L123-L125
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
awsPulumiProgram
async function awsPulumiProgram(): Promise<Record<string, any> | void> { const config = new pulumi.Config(); const instanceType = config.require("instanceType"); const rootVolumeSizeGB = config.requireNumber("rootVolumeSizeGB"); const publicIpType = config.require("publicIpType"); const publicKeyContent = config.require("publicSshKeyContent"); const useSpot = config.requireBoolean("useSpot"); const ingressPorts = config.requireObject<SimplePortDefinition[]>("ingressPorts") const billingAlertEnabled = config.requireBoolean("billingAlertEnabled"); const billingAlertLimit = config.get("billingAlertLimit"); const billingAlertNotificationEmail = config.get("billingAlertNotificationEmail"); const instanceName = pulumi.getStack() const ubuntuAmi = aws.ec2.getAmiOutput({ mostRecent: true, filters: [ { name: "name", // Use a specific version as much as possible to avoid reproducibility issues // Can't use AMI ID as it's region dependent // and specifying AMI for all regions may not yield expected results and would be hard to maintain values: ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-20250115"], }, { name: "virtualization-type", values: ["hvm"], }, ], owners: ["099720109477"], }) let billingAlert: { limit: pulumi.Input<string> notificationEmail: pulumi.Input<string> } | undefined = undefined if(billingAlertEnabled) { if(!billingAlertLimit) { throw new Error("billingAlertLimit is required when billingAlertEnabled is true") } if(!billingAlertNotificationEmail) { throw new Error("billingAlertNotificationEmail is required when billingAlertEnabled is true") } billingAlert = { limit: billingAlertLimit, notificationEmail: billingAlertNotificationEmail } } const instance = new CloudyPadEC2Instance(instanceName, { ami: ubuntuAmi.imageId, type: instanceType, publicKeyContent: publicKeyContent, rootVolume: { type: "gp3", encrypted: true, sizeGb: rootVolumeSizeGB }, publicIpType: publicIpType, ignorePublicKeyChanges: true, spot: { enabled: useSpot }, billingAlert: billingAlert, ingressPorts: ingressPorts.map(p => ({ fromPort: p.port, toPort: p.port, protocol: p.protocol, cidrBlocks: ["0.0.0.0/0"], ipv6CidrBlocks: ["::/0"] })) }) return { instanceId: instance.instanceId, publicIp: instance.publicIp } }
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/aws/pulumi.ts#L239-L321
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
azurePulumiProgram
async function azurePulumiProgram(): Promise<Record<string, any> | void> { const config = new pulumi.Config() const vmSize = config.require("vmSize") const publicKeyContent = config.require("publicSshKeyContent") const rootDiskSizeGB = config.requireNumber("rootDiskSizeGB") const rootDiskType = config.require("rootDiskType") const publicIpType = config.require("publicIpType") const useSpot = config.requireBoolean("useSpot") const costAlert = config.getObject<CostAlertOptions>("costAlert") const securityGroupPorts = config.requireObject<SimplePortDefinition[]>("securityGroupPorts") const instanceName = pulumi.getStack() const instance = new CloudyPadAzureInstance(instanceName, { vmSize: vmSize, publicKeyContent: publicKeyContent, osDisk: { type: rootDiskType, sizeGb: rootDiskSizeGB, deviceName: `${instanceName}-osdisk` }, publicIpType: publicIpType, networkSecurityGroupRules: securityGroupPorts.map((p, index) => ({ name: `${instanceName}-rule-${index}`, protocol: p.protocol, sourcePortRange: "*", destinationPortRange: p.port.toString(), sourceAddressPrefix: "*", destinationAddressPrefix: "*", access: "Allow", priority: 100 + index, direction: "Inbound", })), // Spot config if enabled priority: useSpot ? "Spot" : undefined, evictionPolicy: useSpot ? "Deallocate" : undefined, costAlert: costAlert }) return { vmName: instance.vmName, publicIp: instance.publicIp, resourceGroupName: instance.resourceGroupName } }
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/azure/pulumi.ts#L214-L259
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
gcpPulumiProgram
async function gcpPulumiProgram(): Promise<Record<string, any> | void> { const gcpConfig = new pulumi.Config("gcp") const projectId = gcpConfig.require("project") const config = new pulumi.Config() const machineType = config.require("machineType") const acceleratorType = config.require("acceleratorType") const bootDiskSizeGB = config.requireNumber("bootDiskSizeGB") const publicIpType = config.require("publicIpType") const publicKeyContent = config.require("publicSshKeyContent") const useSpot = config.requireBoolean("useSpot") const costAlert = config.getObject<CostAlertOptions>("costAlert") const firewallAllowPorts = config.requireObject<SimplePortDefinition[]>("firewallAllowPorts") const instanceName = pulumi.getStack() const instance = new CloudyPadGCEInstance(instanceName, { projectId: projectId, machineType: machineType, acceleratorType: acceleratorType, publicKeyContent: publicKeyContent, bootDisk: { sizeGb: bootDiskSizeGB }, publicIpType: publicIpType, ingressPorts: [ { from: 22, protocol: "tcp" }, { from: 47984, protocol: "tcp" }, { from: 47989, protocol: "tcp" }, { from: 48010, protocol: "tcp" }, { from: 47999, protocol: "udp" }, { from: 48100, to: 48110, protocol: "udp" }, { from: 48200, to: 48210, protocol: "udp" }, ], useSpot: useSpot, costAlert: costAlert, firewallAllowPorts: firewallAllowPorts.map(p => ({ ports: [p.port.toString()], protocol: p.protocol, })), }) return { instanceName: instance.instanceName, publicIp: instance.publicIp } }
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/gcp/pulumi.ts#L228-L276
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PaperspaceClient.getPublicIp
async getPublicIp(ip: string): Promise<PaperspaceIp | undefined>{ // GET:public-ips/{ip} not available on Paperspace API // Searching with list instead const ips = await this.listPublicIps() return ips.find(item => item.ip == ip) }
/** * Try to get a Public IP. * @param ip * @returns IP or undefined if IP not found */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/client.ts#L147-L153
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PaperspaceClient.deleteMachine
async deleteMachine(machineId: string, releasePublicIp?: boolean): Promise<void> { try { if(releasePublicIp){ const m = await this.getMachine(machineId) if(m.publicIp && m.publicIpType == paperspace.MachinesList200ResponseItemsInnerPublicIpTypeEnum.Static) { this.logger.debug(`Deleting machine ${machineId}: Releasing static public IP ${m.publicIp}`) await this.releasePublicIp(m.publicIp) } else { this.logger.debug(`Deleting machine ${machineId}: no static public IP on machine, no need to release it.`) } } this.logger.debug(`Deleting machine: ${JSON.stringify(machineId)}`) const response = await this.machineClient.machinesDelete(machineId, this.baseOptions) this.logger.debug(`Deleting machine ${machineId} response: ${JSON.stringify(response.status)}`) } catch (e: unknown) { throw buildAxiosError(e) } }
/** * Delete a Paperspace machine. If machine has a static public IP and releasePublicIp is true, static IP is released as well. * Otherwise public IP (if any) attached to machine is left untouched. * @param machineId * @param releasePublicIp * @returns */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/client.ts#L194-L215
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AuthenticationApi.authSession
public authSession(options?: RawAxiosRequestConfig) { return AuthenticationApiFp(this.configuration).authSession(options).then((request) => request(this.axios, this.basePath)); }
/** * Get the current session. If a user is not logged in, this will be null. Otherwise, it will contain the current team and user. * @summary Get the current session * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AuthenticationApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L1517-L1519
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesCreate
public machinesCreate(machinesCreateRequest: MachinesCreateRequest, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesCreate(machinesCreateRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Creates a new machine. * @summary Create a machine * @param {MachinesCreateRequest} machinesCreateRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2118-L2120
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesDelete
public machinesDelete(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesDelete(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Deletes a single machine by ID. * @summary Delete a machine * @param {string} id The ID of the machine to delete. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2130-L2132
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesGet
public machinesGet(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesGet(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Fetches a single machine by ID. * @summary Get a machine * @param {string} id The ID of the machine to fetch. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2142-L2144
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesList
public machinesList(after?: string, limit?: number, orderBy?: MachinesListOrderByEnum, order?: MachinesListOrderEnum, name?: string, region?: PublicIpsListRegionParameter, agentType?: string, machineType?: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesList(after, limit, orderBy, order, name, region, agentType, machineType, options).then((request) => request(this.axios, this.basePath)); }
/** * Fetches a list of machines. * @summary List machines * @param {string} [after] Fetch the next page of results after this cursor. * @param {number} [limit] The number of items to fetch after this page. * @param {MachinesListOrderByEnum} [orderBy] Order results by one of these fields. * @param {MachinesListOrderEnum} [order] The order to sort the results by. * @param {string} [name] * @param {PublicIpsListRegionParameter} [region] * @param {string} [agentType] * @param {string} [machineType] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2161-L2163
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesRestart
public machinesRestart(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesRestart(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Restarts a machine. * @summary Restart a machine * @param {string} id The ID of the machine to restart. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2173-L2175
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesStart
public machinesStart(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesStart(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Starts a machine. * @summary Start a machine * @param {string} id The ID of the machine to start. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2185-L2187
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesStop
public machinesStop(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesStop(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Stops a machine. * @summary Stop a machine * @param {string} id The ID of the machine to stop. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2197-L2199
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesUpdate
public machinesUpdate(id: string, machinesUpdateRequest: MachinesUpdateRequest, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesUpdate(id, machinesUpdateRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Updates a machine. * @summary Update a machine * @param {string} id The ID of the machine to update. * @param {MachinesUpdateRequest} machinesUpdateRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2210-L2212
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsAssign
public publicIpsAssign(ip: string, publicIpsAssignRequest: PublicIpsAssignRequest, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsAssign(ip, publicIpsAssignRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Assigns a public IP to a machine. * @summary Assign a public IP * @param {string} ip The IP address of the public IP. * @param {PublicIpsAssignRequest} publicIpsAssignRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2564-L2566
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsClaim
public publicIpsClaim(publicIpsClaimRequest: PublicIpsClaimRequest, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsClaim(publicIpsClaimRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Claims a public IP. * @summary Claim a public IP * @param {PublicIpsClaimRequest} publicIpsClaimRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2576-L2578
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsList
public publicIpsList(after?: string, limit?: number, orderBy?: PublicIpsListOrderByEnum, order?: PublicIpsListOrderEnum, region?: PublicIpsListRegionParameter, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsList(after, limit, orderBy, order, region, options).then((request) => request(this.axios, this.basePath)); }
/** * Fetches a list of public IPs. * @summary List public IPs * @param {string} [after] Fetch the next page of results after this cursor. * @param {number} [limit] The number of items to fetch after this page. * @param {PublicIpsListOrderByEnum} [orderBy] Order results by one of these fields. * @param {PublicIpsListOrderEnum} [order] The order to sort the results by. * @param {PublicIpsListRegionParameter} [region] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2592-L2594
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsRelease
public publicIpsRelease(ip: string, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsRelease(ip, options).then((request) => request(this.axios, this.basePath)); }
/** * Releases a public IP. * @summary Release a public IP * @param {string} ip The IP address of the public IP. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2604-L2606
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
objectEntries
function objectEntries(object: Record<string, any>): Array<[string, any]> { return Object.keys(object).map(key => [key, object[key]]); }
/** * Ponyfill for Object.entries */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/common.ts#L159-L161
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
objectFromEntries
function objectFromEntries(entries: any): Record<string, any> { return [...entries].reduce((object, [key, val]) => { object[key] = val; return object; }, {}); }
/** * Ponyfill for Object.fromEntries */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/common.ts#L166-L171
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
Configuration.isJsonMime
public isJsonMime(mime: string): boolean { const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); }
/** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * @param mime - MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON, false otherwise. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/configuration.ts#L106-L109
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getCurrentRegion
static async getCurrentRegion(): Promise<string | undefined> { // AWS SDK V3 does not provide an easy way to get current region // Use this method taken from https://github.com/aws/aws-sdk-js-v3/discussions/4488 try { return await loadConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS)() } catch (e){ AwsClient.staticLogger.debug("Couldn't fin AWS region: ", e) return undefined } }
/** * Return currently set region (as identified by AWS SDK). * @returns currently configured region - undefined if not region currently set */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L39-L48
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getQuota
async getQuota(quotaCode: string): Promise<number | undefined> { try { this.logger.debug(`Checking quota code ${quotaCode} in region: ${this.region}`) const command = new GetServiceQuotaCommand({ ServiceCode: 'ec2', QuotaCode: quotaCode, }) const response = await this.quotaClient.send(command) this.logger.trace(`Service Quota Response: ${JSON.stringify(response)}`) return response.Quota?.Value } catch (error) { throw new Error(`Failed to check quota code ${quotaCode} in region ${this.region}`, { cause: error }) } }
/** * Get quota value for a given quota code * @param quotaCode quota code to check * @returns quota value if available, undefined if not */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L227-L244
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getInstanceTypeDetails
async getInstanceTypeDetails(instanceTypes: string[]): Promise<InstanceTypeInfo[]> { try { const internalInstanceTypes = stringsToInstanceTypes(instanceTypes) const command = new DescribeInstanceTypesCommand({ InstanceTypes: internalInstanceTypes, }) const response = await this.ec2Client.send(command) if (response.InstanceTypes && response.InstanceTypes.length > 0) { return response.InstanceTypes } else { throw new Error(`No instance type details found for ${JSON.stringify(instanceTypes)} in region ${this.region}`) } } catch (error) { throw new Error(`Failed to fetch instance details for instance type ${JSON.stringify(instanceTypes)} in region ${this.region}`, { cause: error }) } }
/** * Fetch instance type details from AWS (vCPU, memory...) * @param instanceTypes instance types to fetch details for * @returns instance type details */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L251-L269
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.filterAvailableInstanceTypes
async filterAvailableInstanceTypes(instanceTypes: string[]): Promise<string[]> { try { const internalInstanceTypes = stringsToInstanceTypes(instanceTypes) const command = new DescribeInstanceTypeOfferingsCommand({ LocationType: "region", Filters: [ { Name: "instance-type", Values: internalInstanceTypes, }, ], }) const response = await this.ec2Client.send(command) const offerings = response.InstanceTypeOfferings || [] return offerings .filter(offering => offering.Location === this.region && offering.InstanceType) .map(offering => String(offering.InstanceType)) } catch (error) { throw new Error(`Failed to check availability of instance type ${instanceTypes} in region ${this.region}`, { cause: error }) } }
/** * Filter instance types that are available in client's region * @param instanceTypes instance types to filter * @returns instance types available in client's region */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L276-L300
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AnalyticsManager.get
static get(): AnalyticsClient { if(AnalyticsManager.client){ return AnalyticsManager.client } if(process.env.CLOUDYPAD_ANALYTICS_DISABLE === "true" || process.env.CLOUDYPAD_ANALYTICS_DISABLE === "1") { AnalyticsManager.logger.debug(`Initializing NoOp AnalyticsClient as per CLOUDYPAD_ANALYTICS_DISABLE=${process.env.CLOUDYPAD_ANALYTICS_DISABLE}`) AnalyticsManager.client = new NoOpAnalyticsClient() } const config = ConfigManager.getInstance().load() AnalyticsManager.logger.debug("Initializing PostHog AnalyticsClient") if (!config.analytics.posthog?.distinctId) { throw new Error("Analytics enabled but PostHog distinctId not set. This is probably an internal bug, please file an issue.") } switch(config.analytics.posthog.collectionMethod) { case "all": // Collect additional personal data AnalyticsManager.client = new PostHogAnalyticsClient({ distinctId: config.analytics.posthog.distinctId, additionalProperties: { "os_name": os.platform(), "os_version": os.version(), "os_arch": os.arch(), "os_release": os.release(), }, }) break case "technical": // Simply client with no additional properties // Explicitely disable personao data tracking AnalyticsManager.client = new PostHogAnalyticsClient({ distinctId: config.analytics.posthog.distinctId, additionalProperties: { "$process_person_profile": false }, }) break case "none": AnalyticsManager.client = new NoOpAnalyticsClient() break } return AnalyticsManager.get() }
/** * Build an AnalyticsManager using current global configuration. * Returned instance is a singleton initialized the firs time this function is called. * * On first call, create an analytics client following: * - If CLOUDYPAD_ANALYTICS_DISABLE is true, a dummy no-op client is created * - If global enables analytics, a client is created according to collection method * - None: do not collect anything * - Technical: only collect technical non-personal data * - All: collect everything, including personal data * - Otherwise, a dummy no-op client is created */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/analytics/manager.ts#L23-L71
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
getTestWriter
async function getTestWriter(): Promise<{ dataDir: string, writer: StateWriter<AwsInstanceStateV1> }> { const dataDir = mkdtempSync(path.join(tmpdir(), 'statewriter-test-')) const loader = new StateLoader({ dataRootDir: path.resolve(__dirname, "v1-root-data-dir")}) const state = await loader.loadAndMigrateInstanceState(instanceName) const awState = new AwsStateParser().parse(state) const writer = new StateWriter<AwsInstanceStateV1>({ state: awState, dataRootDir: dataDir }) return { dataDir: dataDir, writer: writer } }
// create a test writer using a temp directory as data dir
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/test/unit/core/state/writer.spec.ts#L17-L30
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
loadResultPersistedState
function loadResultPersistedState(dataDir: string){ const filePath = path.resolve(path.join(dataDir, "instances", instanceName, "state.yml")) return yaml.load(fs.readFileSync(filePath, 'utf-8')) }
// Load state from given data dir to compare with expected result
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/test/unit/core/state/writer.spec.ts#L33-L36
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
ai-playground
github_2023
rokbenko
typescript
handleDialogClose
const handleDialogClose = () => { setLoadingAssistants(false); setLoadingThread(false); onClose(); };
// Function to close the dialog
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L49-L53
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
assistantsFunction
const assistantsFunction = async (e: any) => { e.preventDefault(); setLoadingAssistants(true); try { const response = await fetch(`/api/listAssistants`, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (response.ok) { const getResponse = await response.json(); const getData = getResponse.message.body.data; const extractedInfoForAssistants = getData.map((assistant: any) => { return { id: assistant.id, name: assistant.name, instructions: assistant.instructions, }; }); setExtractedInfoForAssistants(extractedInfoForAssistants); } else { console.error(response); } } catch (error: any) { console.error(error); } finally { setLoadingAssistants(false); } };
// Function to fetch and list all assistants
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L56-L89
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
threadFunction
const threadFunction = async (e: any) => { e.preventDefault(); setLoadingThread(true); try { const response = await fetch(`api/createThread`, { method: "POST", headers: { "Content-Type": "application/json", }, }); if (response.ok) { const getResponse = await response.json(); const getData = getResponse.message; const threadId = getData.id; const threadCreatedAt = getData.created_at; setExtractedInfoForThread([ { id: threadId, created_at: threadCreatedAt, }, ]); } else { console.error(response); } } catch (error: any) { console.error(error); } finally { setLoadingThread(false); } };
// Function to create a new thread
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L92-L125
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
formatUnixTimestamp
const formatUnixTimestamp = ( timestamp: number, locale: string, timeZone: string ) => { const milliseconds = timestamp * 1000; return new Intl.DateTimeFormat(locale, { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", timeZone: timeZone, }).format(new Date(milliseconds)); };
// Function to format Unix timestamp to a readable date
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L128-L143
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
copyToClipboard
const copyToClipboard = async (text: string, idType: string) => { try { await copy(text); setSnackbarOpen(true); setSnackbarSeverity("success"); setSnackbarMessage(`${idType} ID copied to clipboard`); } catch (error) { console.error("Error copying to clipboard:", error); setSnackbarOpen(true); setSnackbarSeverity("error"); setSnackbarMessage(`Error copying ${idType} ID to clipboard`); } };
// Function to copy text to clipboard
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L146-L158
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
handleSnackbarClose
const handleSnackbarClose = ( event: React.SyntheticEvent | Event, reason?: string ) => { if (reason === "clickaway") { return; } setSnackbarOpen(false); };
// Function to handle Snackbar close event
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L161-L169
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
mapSeverityToAlertColor
const mapSeverityToAlertColor = (severity: string): AlertColor => { switch (severity) { case "success": return "success"; case "error": return "error"; case "warning": return "warning"; case "info": return "info"; default: return "info"; } };
// Function to map severity to Alert color
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L172-L185
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
delay
const delay = (ms: any) => new Promise((resolve) => setTimeout(resolve, ms));
// Function to introduce a delay using promises
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/pages/api/openai.ts#L15-L15
3c229d9f10fefba1a24b70b13b2bb956d64914ec
beakjs
github_2023
mme
typescript
hasParentWithClass
const hasParentWithClass = (element: Element, className: string): boolean => { while (element && element !== document.body) { if (element.classList.contains(className)) { return true; } element = element.parentElement!; } return false; };
// Function to check if the target has the parent with a given class
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/packages/react/src/Window.tsx#L128-L136
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
readVersionFile
function readVersionFile(filePath: string): string { return fs.readFileSync(filePath, "utf8").trim(); }
// This function reads the VERSION file and returns the version string
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L22-L24
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
readPackageJson
function readPackageJson(filePath: string): any { return JSON.parse(fs.readFileSync(filePath, "utf8")); }
// This function reads a package.json file and returns its content as a JSON object
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L27-L29
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
writePackageJson
function writePackageJson(filePath: string, content: any): void { fs.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n"); }
// This function writes the updated JSON content back to the package.json file
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L32-L34
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
updatePackageData
function updatePackageData( rootPackageJson: any, targetPackageJson: any, newVersion: string ): boolean { let hasChanged = false; // Update version if (newVersion && targetPackageJson.version !== newVersion) { targetPackageJson.version = newVersion; hasChanged = true; } // Update dependencies if they exist in rootPackageJson const typesOfDependencies = [ "dependencies", "devDependencies", "peerDependencies", ]; typesOfDependencies.forEach((depType) => { if (rootPackageJson[depType] && targetPackageJson[depType]) { Object.keys(targetPackageJson[depType]).forEach((dep) => { if (dep.startsWith("@beakjs/")) { targetPackageJson[depType][dep] = newVersion; hasChanged = true; } else if (rootPackageJson[depType][dep]) { targetPackageJson[depType][dep] = rootPackageJson[depType][dep]; hasChanged = true; } }); } }); return hasChanged; }
// This function updates the version and dependencies in targetPackageJson using the versions from rootPackageJson
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L37-L71
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
updateVersionsAndDependencies
function updateVersionsAndDependencies(): void { const newVersion = readVersionFile(versionFilePath); const rootPackageJson = readPackageJson(rootPackageJsonPath); otherPackageJsonPaths.forEach((packageJsonPath) => { try { const targetPackageJson = readPackageJson(packageJsonPath); const hasChanged = updatePackageData( rootPackageJson, targetPackageJson, newVersion ); if (hasChanged) { writePackageJson(packageJsonPath, targetPackageJson); console.log(`Updated version and dependencies in ${packageJsonPath}`); } else { console.log(`No changes made to ${packageJsonPath}`); } } catch (error) { console.error(`Error updating ${packageJsonPath}: ${error}`); } }); }
// Main function to update version and dependencies versions in all package.json files
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L74-L97
c837e84da19082ae6ed977381548efb74930d678
btime-desktop
github_2023
sajjadmrx
typescript
withPrototype
function withPrototype(obj: Record<string, any>) { const protos = Object.getPrototypeOf(obj) for (const [key, value] of Object.entries(protos)) { if (Object.prototype.hasOwnProperty.call(obj, key)) continue if (typeof value === 'function') { // Some native APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function. obj[key] = (...args: any) => value.call(obj, ...args) } else { obj[key] = value } } return obj }
// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L11-L25
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
domReady
function domReady( condition: DocumentReadyState[] = ['complete', 'interactive'], ) { return new Promise((resolve) => { if (condition.includes(document.readyState)) { resolve(true) } else { document.addEventListener('readystatechange', () => { if (condition.includes(document.readyState)) { resolve(true) } }) } }) }
// --------- Preload scripts loading ---------
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L28-L42
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
useLoading
function useLoading() { const className = 'loaders-css__square-spin' const styleContent = ` @keyframes square-spin { 25% { transform: perspective(100px) rotateX(180deg) rotateY(0); } 50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); } 75% { transform: perspective(100px) rotateX(0) rotateY(180deg); } 100% { transform: perspective(100px) rotateX(0) rotateY(0); } } .${className} > div { animation-fill-mode: both; width: 50px; height: 50px; background: #fff; animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite; } .app-loading-wrap { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; background: #282c34; z-index: 9; } ` const oStyle = document.createElement('style') const oDiv = document.createElement('div') oStyle.id = 'app-loading-style' oStyle.innerHTML = styleContent oDiv.className = 'app-loading-wrap' oDiv.innerHTML = `<div class="${className}"><div></div></div>` return { appendLoading() { safeDOM.append(document.head, oStyle) safeDOM.append(document.body, oDiv) }, removeLoading() { safeDOM.remove(document.head, oStyle) safeDOM.remove(document.body, oDiv) }, } }
/** * https://tobiasahlin.com/spinkit * https://connoratherton.com/loaders * https://projects.lukehaas.me/css-loaders * https://matejkustec.github.io/SpinThatShit */
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L63-L110
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
toHex
const toHex = (value: number) => value.toString(16).padStart(2, '0')
// Convert RGB back to hex
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/src/weather/components/weather-card.component.tsx#L192-L192
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
vscode-ui-sketcher
github_2023
pAIrprogio
typescript
crc
const crc: CRCCalculator<Uint8Array> = (current, previous) => { let crc = previous === 0 ? 0 : ~~previous! ^ -1; for (let index = 0; index < current.length; index++) { crc = TABLE[(crc ^ current[index]) & 0xff] ^ (crc >>> 8); } return crc ^ -1; };
// crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts
https://github.com/pAIrprogio/vscode-ui-sketcher/blob/bcbced57d6465bd0b9d379dae2641103c95abb9a/ui-sketcher-webview/src/lib/png.ts#L58-L66
bcbced57d6465bd0b9d379dae2641103c95abb9a
pr-stats
github_2023
naver
typescript
msToTime
const msToTime = ( duration: number, ): { days: number; hours: number; minutes: number; seconds: number; } => { if (!duration) { return { days: -1, hours: -1, minutes: -1, seconds: -1, }; } const seconds = Math.floor((duration / 1000) % 60); const minutes = Math.floor((duration / (1000 * 60)) % 60); const hours = Math.floor((duration / (1000 * 60 * 60)) % 24); const days = Math.floor(duration / (1000 * 60 * 60 * 24)); return { days, hours, minutes, seconds, }; };
/** * pr-stats * Copyright (c) 2023-present NAVER Corp. * Apache-2.0 */
https://github.com/naver/pr-stats/blob/cb9b122926af0d118c690ddd313cbe4d9334729b/src/util/time.ts#L7-L35
cb9b122926af0d118c690ddd313cbe4d9334729b
nextjs-live-transcription
github_2023
deepgram-starters
typescript
connectToDeepgram
const connectToDeepgram = async (options: LiveSchema, endpoint?: string) => { const key = await getApiKey(); const deepgram = createClient(key); const conn = deepgram.listen.live(options, endpoint); conn.addListener(LiveTranscriptionEvents.Open, () => { setConnectionState(LiveConnectionState.OPEN); }); conn.addListener(LiveTranscriptionEvents.Close, () => { setConnectionState(LiveConnectionState.CLOSED); }); setConnection(conn); };
/** * Connects to the Deepgram speech recognition service and sets up a live transcription session. * * @param options - The configuration options for the live transcription session. * @param endpoint - The optional endpoint URL for the Deepgram service. * @returns A Promise that resolves when the connection is established. */
https://github.com/deepgram-starters/nextjs-live-transcription/blob/474b3dfb8eb3bad6ac997c02ba63c82650ad995c/app/context/DeepgramContextProvider.tsx#L56-L71
474b3dfb8eb3bad6ac997c02ba63c82650ad995c
server
github_2023
interval
typescript
getWorkers
function getWorkers(): number { const workers = Math.floor(os.cpus().length / 2 - 1) if (workers < 1) return 1 return workers }
/** * Reserve one core to run the web app when performing parallel tests. * * The default is NUM_CORES / 2, which is good on fast machines but can starve * the server on slower or throttled ones. We reduce that by one by default. * * This can be overridden using the `--workers` command line argument if * calling directly, or within `PLAYWRIGHT_ARGS` env var if using `test:all`. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/playwright.config.ts#L54-L60
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
createDevOrg
async function createDevOrg() { console.log('Creating dev org...') await upsertUser({ id: ADMIN_USER_ID, email: ADMIN_USER_EMAIL, password: encryptPassword(ADMIN_USER_PASSWORD), firstName: 'Admin', lastName: 'User', }) const acme = await upsertOrg({ id: 'RQ1FQoNTFCYe-W8RTGF1u', slug: 'acme-corp', name: 'Acme Corp', owner: { connect: { id: ADMIN_USER_ID, }, }, private: { create: {} }, environments: { create: [ { slug: PRODUCTION_ORG_ENV_SLUG, name: PRODUCTION_ORG_ENV_NAME }, { slug: DEVELOPMENT_ORG_ENV_SLUG, name: DEVELOPMENT_ORG_ENV_NAME, color: DEVELOPMENT_ORG_DEFAULT_COLOR, }, ], }, }) // make this org the default org for the new user const now = new Date() now.setSeconds(now.getSeconds() + 2) await createUserOrgAccess({ user: { connect: { id: ADMIN_USER_ID } }, organization: { connect: { id: acme.id } }, permissions: ['ADMIN'], lastSwitchedToAt: now, }) await upsertApiKey({ id: 'gfVYGr9AhZBni3TT_N5L0', key: API_KEYS.acme.dev, user: { connect: { id: ADMIN_USER_ID, }, }, usageEnvironment: 'DEVELOPMENT', organization: { connect: { id: acme.id, }, }, organizationEnvironment: { connect: { id: acme.environments.find(env => env.slug === DEVELOPMENT_ORG_ENV_SLUG) ?.id, }, }, }) await upsertApiKey({ id: 'fzlGEIA93Yf27FgB2WAAQ', key: encryptPassword(API_KEYS.acme.live), user: { connect: { id: ADMIN_USER_ID, }, }, usageEnvironment: 'PRODUCTION', organization: { connect: { id: acme.id, }, }, organizationEnvironment: { connect: { id: acme.environments.find(env => env.slug === PRODUCTION_ORG_ENV_SLUG) ?.id, }, }, }) const otherUsers: [string, string][] = Array.from({ length: 10 }).map(() => { return [faker.name.firstName(), faker.name.lastName()] }) const users = await Promise.all([ ...otherUsers.map(([firstName, lastName]) => upsertUser({ password: encryptPassword('password'), email: `${firstName.toLowerCase()}@interval.com`, firstName, lastName, }) ), // ACTION_RUNNER-level user in the Support group upsertUser({ password: encryptPassword('password'), email: 'support@interval.com', firstName: 'Support', lastName: 'User', }), // DEVELOPER-level user in the Engineers group upsertUser({ password: encryptPassword('password'), email: 'engineers@interval.com', firstName: 'Engineers', lastName: 'User', }), ]) const engGroup = await upsertUserAccessGroup({ name: 'Engineers', slug: 'engineers', organization: { connect: { id: acme.id } }, id: 'uR81EKV0sEVeV0brFSTaD', }) const supportGroup = await upsertUserAccessGroup({ name: 'Support', slug: 'support', organization: { connect: { id: acme.id } }, id: 'jNb18gzlCKMYFcr98jZM0', }) for (let i = 0; i < users.length; i++) { const user = users[i] if (user.firstName === 'Support') { const access = await createUserOrgAccess({ user: { connect: { id: user.id } }, organization: { connect: { id: acme.id } }, permissions: ['ACTION_RUNNER'], }) await createUserAccessGroupMembership({ userOrganizationAccess: { connect: { id: access.id } }, group: { connect: { id: supportGroup.id } }, }) } else if (user.firstName === 'Engineers') { const access = await createUserOrgAccess({ user: { connect: { id: user.id } }, organization: { connect: { id: acme.id } }, permissions: ['DEVELOPER'], }) await createUserAccessGroupMembership({ userOrganizationAccess: { connect: { id: access.id } }, group: { connect: { id: engGroup.id } }, }) } else if (i <= 5) { const access = await createUserOrgAccess({ user: { connect: { id: user.id } }, organization: { connect: { id: acme.id } }, permissions: ['DEVELOPER'], }) await createUserAccessGroupMembership({ userOrganizationAccess: { connect: { id: access.id } }, group: { connect: { id: engGroup.id } }, }) } else { const access = await createUserOrgAccess({ user: { connect: { id: user.id } }, organization: { connect: { id: acme.id } }, permissions: ['ACTION_RUNNER'], }) await createUserAccessGroupMembership({ userOrganizationAccess: { connect: { id: access.id } }, group: { connect: { id: supportGroup.id } }, }) } } }
/** * Creates an organization for local development. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/prisma/seed.ts#L167-L347
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
createIntervalOrg
async function createIntervalOrg() { console.log('Creating internal Interval org...') const interval = await upsertOrg({ name: 'Interval', owner: { connect: { id: ADMIN_USER_ID, }, }, private: { create: {} }, id: 'URobaKdFwHieImSKFO37D', slug: 'interval', environments: { create: [ { slug: PRODUCTION_ORG_ENV_SLUG, name: PRODUCTION_ORG_ENV_NAME }, { slug: DEVELOPMENT_ORG_ENV_SLUG, name: DEVELOPMENT_ORG_ENV_NAME, color: DEVELOPMENT_ORG_DEFAULT_COLOR, }, ], }, }) await upsertApiKey({ id: 'J91ACL455qSsHtp6x-QJB', key: API_KEYS.interval.dev, user: { connect: { id: ADMIN_USER_ID, }, }, usageEnvironment: 'DEVELOPMENT', organization: { connect: { id: interval.id, }, }, organizationEnvironment: { connect: { id: interval.environments.find( env => env.slug === DEVELOPMENT_ORG_ENV_SLUG )?.id, }, }, }) await upsertApiKey({ id: 'qhykubq7PUAGHnVv-xDh6', key: encryptPassword(API_KEYS.interval.live), user: { connect: { id: ADMIN_USER_ID, }, }, usageEnvironment: 'PRODUCTION', organization: { connect: { id: interval.id, }, }, organizationEnvironment: { connect: { id: interval.environments.find( env => env.slug === PRODUCTION_ORG_ENV_SLUG )?.id, }, }, }) await createUserOrgAccess({ user: { connect: { id: ADMIN_USER_ID } }, organization: { connect: { id: interval.id } }, permissions: ['ADMIN'], }) }
/** * Creates an internal "Interval" organization containing actions for * managing the Interval instance. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/prisma/seed.ts#L353-L429
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
useLoginRedirect
function useLoginRedirect() { const location = useLocation() const { loginRedirect: stateRedirect } = (location.state as Record<string, string | undefined | null>) || {} const setRecoilRedirect = useSetRecoilState(redirectAfterLogin) // updates recoil + localStorage if a redirect is found in the location state on any page useEffect(() => { if (stateRedirect !== undefined) { setRecoilRedirect(stateRedirect) } }, [stateRedirect, setRecoilRedirect]) }
// Reads `loginRedirect` from the location state and adds it to recoil + localStorage
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/LoginRedirect.tsx#L15-L27
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
IVDialogWrapper
const IVDialogWrapper = (props: IVDialogProps) => { const dialog = useDialogState({ visible: true, }) return ( <div className="fixed inset-0 flex items-center justify-center"> <IVButton theme="primary" label="Open dialog" onClick={dialog.show} /> <IVDialog {...props} dialog={dialog} /> </div> ) }
/** * Dialogs are controlled by the `useDialogState` hook, so every story here * must use `DialogWrapper`. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/IVDialog/IVDialog.stories.tsx#L10-L21
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
applySortingAndFiltering
function applySortingAndFiltering(state: TableState) { if (!state.isFullTableInMemory) return state let filtered: BaseTableRecord<any>[] = state.data // filtering is always performed on the host when remote state is supported. if (!state.isRemote) { filtered = filterRows({ queryTerm: state.searchQuery, data: state.data, }) } const sorted = sortRows({ data: filtered, column: state.sortColumn, direction: state.sortDirection, }) return { ...state, // spread triggers useMemo() for getting currentPage data: [...sorted], totalRecords: sorted.length, } }
/** * Sorts and filters rows if the full table is in memory. * We do this outside of the reducer so we don't have to store * a copy of the unmodified data set in the state. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/IVTable/useTable.ts#L431-L456
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
prepareEmail
async function prepareEmail<T extends TemplateData>({ to, template, templateProps, subjectBuilder, }: PrepareEmailProps<T>): Promise<PreparedEmail> { const emailRenderProps = { ...templateProps, APP_URL: env.APP_URL } const from = env.EMAIL_FROM const subject = subjectBuilder(templateProps) const html = await emailTemplate.render(template, emailRenderProps) return { from, to, html, subject } }
/** * Prepares an email to pass to a sender, such as Postmark. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/emails/sender.ts#L84-L97
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
sendResponse
function sendResponse( statusCode: number, returns: z.input<(typeof ENQUEUE_ACTION)['returns']> ) { res.status(statusCode).send(returns) }
// To ensure correct return type
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/actions.ts#L18-L23
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
sendResponse
function sendResponse( statusCode: number, returns: z.input<(typeof DEQUEUE_ACTION)['returns']> ) { res.status(statusCode).send(returns) }
// To ensure correct return type
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/actions.ts#L115-L120
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
randInt
function randInt(min, max) { return Math.floor(Math.random() * (max - min) + min) }
// src: https://futurestud.io/tutorials/generate-a-random-number-in-range-with-javascript-node-js
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/auth/ghost/generateRandomSlug.ts#L279-L281
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
randEl
function randEl(arr: string[]) { return arr[Math.floor(Math.random() * arr.length)] }
// https://stackoverflow.com/a/5915122
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/auth/ghost/generateRandomSlug.ts#L284-L286
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
shouldSkip
function shouldSkip(url: string): boolean { if (url.includes('/static/')) { return true } if (url.includes('hot-update.js')) { return true } return false }
// Skip some paths that are related to the static react app
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/middleware/requestLogger.ts#L14-L22
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
permissionsCodeToConfig
async function permissionsCodeToConfig({ access, organizationId, }: { access?: AccessControlDefinition | null organizationId: string }): Promise<{ availability: ActionAvailability | undefined teamPermissions: GroupPermissionDefinition[] | undefined warnings: string[] }> { const warnings: string[] = [] if (!access) { return { availability: undefined, teamPermissions: undefined, warnings } } let availability: ActionAvailability let teamPermissions: GroupPermissionDefinition[] = [] if (access === 'entire-organization') { availability = 'ORGANIZATION' } else { availability = 'GROUPS' if ('teams' in access && access.teams) { const groups = await prisma.userAccessGroup.findMany({ where: { organizationId, slug: { in: access.teams, }, }, }) const validSlugs = groups.map(group => group.slug) const invalidSlugs = access.teams.filter( slug => !validSlugs.includes(slug) ) for (const slug in invalidSlugs) { warnings.push('Invalid team slug: ' + slug) } // RUNNER only supported via code config teamPermissions = groups.map(group => ({ groupId: group.id, level: 'RUNNER', })) } } return { availability, teamPermissions, warnings, } }
/** * Converts code-based permissions into values for writing to the database. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/utils/actions.ts#L744-L802
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
canAccessEntityInTree
function canAccessEntityInTree( groupsMap: Map<string, ActionGroupLookupResult>, groupSlug: string ) { const group = groupsMap.get(groupSlug) if (group && group.canRun) return true if (group && group.actions.length > 0) return true const nestedGroups = Array.from(groupsMap.keys()).filter(slug => slug.startsWith(`${groupSlug}/`) ) for (const nestedSlug of nestedGroups) { const canAccessChildren = canAccessEntityInTree(groupsMap, nestedSlug) if (canAccessChildren) return true } return false }
/** * Determines whether the user can access a group, actions in that group, * or any groups & their actions nested within the `groupSlug`. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/utils/actions.ts#L843-L864
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
userCanAccessAction
function userCanAccessAction( action: Prisma.ActionGetPayload<{ include: { metadata: { include: { accesses: true } } } }>, accessLevel: ActionAccessLevel ): boolean | undefined { // Should only receive own from backend if (action.developerId) return true if (action.metadata?.archivedAt) return false switch (action.metadata?.availability) { case undefined: case null: return undefined case 'ORGANIZATION': return true case 'GROUPS': return ( action.metadata.accesses.some(access => actionAccessHasLevel(access, accessLevel) ) ?? false ) } }
/** * Determines whether the user can run the given action. * Does not check whether the user can run actions at all, do that elsewhere. * * Relies on the backend only returning their own development actions, and * only returning the user's own ActionAccesses. * * Returns `undefined` if availability is set to ORGANIZATION, as access * may be inherited by a parent group. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/actions.ts#L135-L159
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
getStyle
function getStyle(element: HTMLElement, prop: string) { return window.getComputedStyle(element, null).getPropertyValue(prop) }
// based on https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/getTextWidth.ts#L2-L4
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
getNavPath
function getNavPath(path: string) { return path.replace(/^\/dashboard\/[0-9A-Za-z+_-]*/, '') }
/** * Returns the rest of the path after the `/dashboard/:orgSlug` prefix. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/navigation.ts#L25-L27
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
triggerSubmit
function triggerSubmit(ev: KeyboardEvent) { const isModifierKeyPressed = didReportAsAppleDevice ? ev.metaKey : ev.ctrlKey if (isModifierKeyPressed && ev.key === 'Enter' && enabled) { formRef.current?.requestSubmit() } }
/* This seems convoluted (using formRef to call requestSubmit) but it's "on purpose:" - The value of onSubmit is _really_ unstable. The functions it calls like onRespond are not memoized - It's "safe" because it ensures CMD+Enter does _exactly_ what clicking "submit" would do */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/useSubmitFormWithShortcut.ts#L16-L24
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
authMiddleware
function authMiddleware(req: Request, res: Response, next?: NextFunction) { const header = req.header('Authorization') const token = header?.split(' ')[1] if (token === encryptPassword(env.WSS_API_SECRET)) { next?.() return } res.status(401) res.end() }
// Very basic authentication layer that uses a shared secret
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/index.ts#L20-L30
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
initializationFailure
function initializationFailure( message: string, sdkAlert?: SdkAlert ) { if (!sdkName || !sdkVersion) return null if (sdkName === NODE_SDK_NAME && sdkVersion >= '0.18.0') { return { type: 'error' as const, message, sdkAlert, } } return null }
/** * Returns an error response if the SDK supports it, or null otherwise indicating a general failure supported by all SDKs. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/wss.ts#L541-L556
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
checkForUnreachableHosts
async function checkForUnreachableHosts() { try { // Do this with a raw query in order to use database time // instead of server time. await prisma.$queryRaw` update "HostInstance" set status = 'UNREACHABLE' where status = 'ONLINE' and "updatedAt" < (now() - '00:01:00'::interval) ` await prisma.$queryRaw` delete from "HostInstance" where status in ('UNREACHABLE', 'OFFLINE') and "updatedAt" < (now() - '06:00:00'::interval) ` } catch (error) { logger.error('Failed checking for unreachable hosts', { error, }) } }
/** * Set all hosts as UNREACHABLE if they haven't been touched * in the last minute. The periodic heartbeat will bump * this while the host is connected. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/wss.ts#L2832-L2853
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
code-snippet-editor-plugin
github_2023
figma
typescript
performImport
function performImport(data: CodegenResultTemplatesByComponentKey) { const componentsByKey = getComponentsInFileByKey(); let componentCount = 0; for (let componentKey in data) { const component = componentsByKey[componentKey]; if (component) { componentCount++; setCodegenResultsInPluginData(component, data[componentKey]); } } const s = componentCount === 1 ? "" : "s"; figma.notify(`Updated ${componentCount} Component${s}`); }
/** * Import code snippet templates into components in bulk via JSON. * https://github.com/figma/code-snippet-editor-plugin#importexport * @param data CodegenResultTemplatesByComponentKey * @returns void */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L21-L33
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
performExport
function performExport() { const data: CodegenResultTemplatesByComponentKey = {}; const components = findComponentNodesInFile(); components.forEach((component) => { const codegenResults = getCodegenResultsFromPluginData(component); if (codegenResults && codegenResults.length) { data[component.key] = codegenResults; } }); const message: EventToBulk = { type: "BULK_EXPORT", code: JSON.stringify(data, null, 2), }; figma.ui.postMessage(message); }
/** * Export code snippet templates, posting stringified CodegenResultTemplatesByComponentKey to UI * https://github.com/figma/code-snippet-editor-plugin#importexport * @returns void */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L40-L54
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
findComponentNodesInFile
function findComponentNodesInFile() { if (figma.currentPage.parent) { return ( figma.currentPage.parent.findAllWithCriteria({ types: ["COMPONENT", "COMPONENT_SET"], }) || [] ); } return []; }
/** * Find all component and component set nodes in a file * @returns array of all components and component sets in a file. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L60-L69
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
getComponentsInFileByKey
function getComponentsInFileByKey() { const components = findComponentNodesInFile(); const data: ComponentsByComponentKey = {}; components.forEach((component) => (data[component.key] = component)); return data; }
/** * Find all components and component sets in a file and return object of them by key. * @returns ComponentsByComponentKey */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L75-L80
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initializeCodegenMode
function initializeCodegenMode() { /** * The preferences change event is fired when settings change from the codegen settings menu. * We only respond to this event when the user selects "Open Editor" * This is configured in manifest.json "codegenPreferences" as the "editor" action. */ figma.codegen.on("preferenceschange", async (event) => { if (event.propertyName === "editor") { openCodeSnippetEditorUI(); } else if (event.propertyName === "templates") { openTemplateUI(); } }); /** * Whenever we receive a message from the UI in codegen mode, it is either: * - INITIALIZE: requesting initial data about the current selection when it opens * - SAVE: providing template data for the plugin to save on the current selection */ figma.ui.on( "message", async (event: EventFromEditor | EventFromTemplates) => { if (event.type === "EDITOR_INITIALIZE") { handleCurrentSelection(); } else if (event.type === "EDITOR_SAVE") { setCodegenResultsInPluginData( figma.currentPage.selection[0], event.data ); } else if (event.type === "TEMPLATES_DATA") { setGlobalTemplatesInClientStorage(event.data); } else { console.log("UNKNOWN EVENT", event); } } ); /** * When the selection changes we want to rerun the code that handles a new node. */ figma.on("selectionchange", () => handleCurrentSelection); /** * This is the main codegen event and expects us to resolve with a CodegenResult array */ figma.codegen.on("generate", async () => { try { /** * Settings defined in manifest.json "codegenPreferences" for "details mode" and * what to render when there is no template to render. * https://github.com/figma/code-snippet-editor-plugin#details-mode */ const { detailsMode, defaultSnippet } = figma.codegen.preferences.customSettings; const isDetailsMode = detailsMode === "on"; const hasDefaultMessage = defaultSnippet === "message"; const currentNode = handleCurrentSelection(); const templates = (await getGlobalTemplatesFromClientStorage()) || {}; const recursiveParamsMap = await recursiveParamsFromNode( currentNode, templates ); const nodeSnippetTemplateDataArray = await nodeSnippetTemplateDataArrayFromNode( currentNode, recursiveParamsMap, templates ); const snippets = codegenResultsFromNodeSnippetTemplateDataArray( nodeSnippetTemplateDataArray, isDetailsMode ); /** * In "Details mode" we render the params and raw params as code snippets * https://github.com/figma/code-snippet-editor-plugin#details-mode */ if (isDetailsMode) { snippets.push({ title: "Params", code: JSON.stringify(recursiveParamsMap, null, 2), language: "JSON", }); } /** * If there are no snippets and the default snippet setting is to show a mesage, * add the message as a snippet. */ if (!snippets.length && hasDefaultMessage) { snippets.push({ title: "Snippets", code: "No snippets on this node. Add snippets via the Snippet Editor.", language: "PLAINTEXT", }); } return snippets; } catch (e: any) { return [ { language: "PLAINTEXT", code: typeof e === "string" ? e : `${e}`, title: "Error", }, ]; } }); }
/** * In codegen mode (running in Dev Mode), the plugin returns codegen, * and can also open a UI "editor" for managing snippet templates. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L23-L133
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initializeDesignMode
function initializeDesignMode() { figma.ui.on("message", async (event: EventFromBulk) => { if (event.type === "BULK_INITIALIZE") { handleCurrentSelection(); } else if (event.type === "BULK_EXPORT") { bulk.performExport(); } else if (event.type === "BULK_IMPORT") { bulk.performImport(event.data); } }); figma.showUI(__uiFiles__.bulk, { width: 600, height: 600, themeColors: true, }); }
/** * Running in design mode, we can perform bulk operations like import/export from JSON * and helpers for loading node data and component data. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L139-L155
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
openCodeSnippetEditorUI
function openCodeSnippetEditorUI() { const { x, y, width, height } = figma.viewport.bounds; const absWidth = width * figma.viewport.zoom; const absHeight = height * figma.viewport.zoom; const finalWidth = Math.round( Math.max(Math.min(absWidth, 400), Math.min(absWidth * 0.6, 700)) ); const finalHeight = Math.round(Math.min(absHeight, 600)); const realX = x + Math.round(absWidth - finalWidth); figma.showUI(__uiFiles__.editor, { position: { x: realX, y }, width: finalWidth, height: finalHeight, themeColors: true, }); }
/** * This attempts to open the editor UI in a large, but unobtrusive way. * Real important math right here (jk, totally arbitrary). */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L161-L176
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
openTemplateUI
async function openTemplateUI() { figma.showUI(__uiFiles__.templates, { width: 600, height: 600, themeColors: true, }); const templates = (await getGlobalTemplatesFromClientStorage()) || "{}"; const message: EventToTemplates = { type: "TEMPLATES_INITIALIZE", templates }; figma.ui.postMessage(message); }
/** * Opening the UI for templates and sending a message with the initial template data */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L180-L189
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
codegenResultsFromNodeSnippetTemplateDataArray
function codegenResultsFromNodeSnippetTemplateDataArray( nodeSnippetTemplateDataArray: NodeSnippetTemplateData[], isDetailsMode: boolean ) { const codegenResult: CodegenResult[] = []; nodeSnippetTemplateDataArray.forEach((nodeSnippetTemplateData) => { const { codegenResultArray, codegenResultRawTemplatesArray } = nodeSnippetTemplateData; /** * If details mode, interleave raw templates between rendered snippets * Otherwise, return the codegen result array by itself */ if (isDetailsMode) { codegenResultArray.forEach((result, i) => { codegenResult.push(codegenResultRawTemplatesArray[i]); codegenResult.push(result); }); } else { codegenResult.push(...codegenResultArray); } }); return codegenResult; }
/** * Final assembly of the codegen result that will include raw templates when in "details mode" * Can have additional things appended to it conditionally, but this yields the main snippet array. * https://github.com/figma/code-snippet-editor-plugin#details-mode * @param nodeSnippetTemplateDataArray the compiled codegen result array with the raw templates version * @param isDetailsMode "details mode" boolean setting value * @returns the final codegen result to render */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L199-L221
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
handleCurrentSelection
function handleCurrentSelection() { const node = figma.currentPage.selection[0]; try { const nodePluginData = node ? getCodegenResultsFromPluginData(node) : null; const nodeId = node ? node.id : null; const nodeType = node ? node.type : null; const message: EventToEditor = { type: "EDITOR_SELECTION", nodeId, nodeType, nodePluginData, }; figma.ui.postMessage(message); return node; } catch (e) { // no ui open. ignore this. return node; } }
/** * Whenever the selection changes, we want to send information to an open UI if one exists. * Using try/catch as a lazy version of open UI detection. * @returns currently selected node */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L228-L246
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
paramsFromNode
async function paramsFromNode( node: BaseNode, propertiesOnly = false ): Promise<CodeSnippetParamsMap> { const { componentPropValuesMap, instanceParamsMap } = await componentPropertyDataFromNode(node); const params: CodeSnippetParams = {}; const paramsRaw: CodeSnippetParams = {}; for (let key in componentPropValuesMap) { const item = componentPropValuesMap[key]; const itemKeys = Object.keys(item) as ComponentPropertyType[]; if (itemKeys.length > 1) { itemKeys.forEach((type) => { const value = `${item[type]}`; const lowerChar = type.charAt(0).toLowerCase(); params[`property.${key}.${lowerChar}`] = safeString(value); paramsRaw[`property.${key}.${lowerChar}`] = value; }); } else { const value = `${item[itemKeys[0]]}`; params[`property.${key}`] = safeString(value); paramsRaw[`property.${key}`] = value; } if (itemKeys.includes("INSTANCE_SWAP") && instanceParamsMap[key]) { const keyPrefix = itemKeys.length > 1 ? `property.${key}.i` : `property.${key}`; for (let k in instanceParamsMap[key].params) { params[`${keyPrefix}.${k}`] = safeString( instanceParamsMap[key].params[k] ); paramsRaw[`${keyPrefix}.${k}`] = instanceParamsMap[key].paramsRaw[k]; } } } if (propertiesOnly) { return { params, paramsRaw, template: {} }; } const initial = await initialParamsFromNode(node); return { params: Object.assign(params, initial.params), paramsRaw: Object.assign(paramsRaw, initial.paramsRaw), template: {}, }; }
/** * Return the code snippet params for a node. * https://github.com/figma/code-snippet-editor-plugin#params * @param node the node we want params for * @param propertiesOnly a boolean flag to only return component property params * (only true when getting instance swap child properties) * @returns Promise that resolves a CodeSnippetParamsMap */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L15-L60
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
componentPropertyDataFromNode
async function componentPropertyDataFromNode(node: BaseNode) { const componentPropObject = componentPropObjectFromNode(node); const componentPropValuesMap: ComponentPropValuesMap = {}; const isDefinitions = isComponentPropertyDefinitionsObject(componentPropObject); const instanceParamsMap: { [k: string]: CodeSnippetParamsMap } = {}; for (let propertyName in componentPropObject) { const value = isDefinitions ? componentPropObject[propertyName].defaultValue : componentPropObject[propertyName].value; const type = componentPropObject[propertyName].type; const cleanName = sanitizePropertyName(propertyName); if (value !== undefined) { componentPropValuesMap[cleanName] = componentPropValuesMap[cleanName] || {}; if (typeof value === "string") { if (type === "VARIANT") componentPropValuesMap[cleanName].VARIANT = value; if (type === "TEXT") componentPropValuesMap[cleanName].TEXT = value; if (type === "INSTANCE_SWAP") { const foundNode = await figma.getNodeById(value); const nodeName = nameFromFoundInstanceSwapNode(foundNode); componentPropValuesMap[cleanName].INSTANCE_SWAP = nodeName; if (foundNode) { instanceParamsMap[cleanName] = await paramsFromNode( foundNode, true ); } } } else { componentPropValuesMap[cleanName].BOOLEAN = value; } } } return { componentPropValuesMap, instanceParamsMap }; }
/** * Given a node, find all the relevant component property data, including from instance swap property instances. * @param node the node to get component property data from * @returns componentPropValuesMap containing component property values * and instanceParamsMap object containing property params for instances */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L152-L188
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
nameFromFoundInstanceSwapNode
function nameFromFoundInstanceSwapNode(node: BaseNode | null) { return node && node.parent && node.parent.type === "COMPONENT_SET" ? node.parent.name : node ? node.name : ""; }
/** * Find the appropriate component name for an instance swap instance node * @param node implicitly an instance node to find a name for * @returns a name as a string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L195-L201
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initialParamsFromNode
async function initialParamsFromNode( node: BaseNode ): Promise<CodeSnippetParamsMap> { const componentNode = getComponentNodeFromNode(node); const css = await node.getCSSAsync(); const autolayout = "inferredAutoLayout" in node ? node.inferredAutoLayout : undefined; const paramsRaw: CodeSnippetParams = { "node.name": node.name, "node.type": node.type, }; const params: CodeSnippetParams = { "node.name": safeString(node.name), "node.type": safeString(node.type), }; if ("key" in node) { paramsRaw["node.key"] = node.key; params["node.key"] = node.key; } if ("children" in node) { const childCount = node.children.length.toString(); paramsRaw["node.children"] = childCount; params["node.children"] = childCount; } if (node.type === "TEXT") { paramsRaw["node.characters"] = node.characters; params["node.characters"] = safeString(node.characters); // Only supporting single style text nodes. figma.mixed means multiple in text block. if (node.textStyleId) { if (node.textStyleId === figma.mixed) { paramsRaw["node.textStyle"] = "figma.mixed"; params["node.textStyle"] = "figma.mixed"; } else { const style = figma.getStyleById(node.textStyleId); if (style) { paramsRaw["node.textStyle"] = style.name; params["node.textStyle"] = safeString(style.name); } } } } if (componentNode && "key" in componentNode) { paramsRaw["component.key"] = componentNode.key; paramsRaw["component.type"] = componentNode.type; paramsRaw["component.name"] = componentNode.name; params["component.key"] = componentNode.key; params["component.type"] = safeString(componentNode.type); params["component.name"] = safeString(componentNode.name); } for (let key in css) { const k = transformStringWithFilter(key, key, "camel"); params[`css.${k}`] = css[key]; paramsRaw[`css.${k}`] = css[key]; } if ("boundVariables" in node && node.boundVariables) { const boundVariables: SceneNodeMixin["boundVariables"] = node.boundVariables; for (let key in boundVariables) { let vars: VariableAlias | VariableAlias[] | undefined = boundVariables[key as keyof SceneNodeMixin["boundVariables"]]; if (vars) { if (!Array.isArray(vars)) { vars = [vars]; } vars.forEach((v, i) => { const va = figma.variables.getVariableById(v.id); if (va) { if (i === 0) { paramsRaw[`variables.${key}`] = va.name; params[`variables.${key}`] = safeString(va.name); } for (let syntax in va.codeSyntax) { const syntaxKey = syntax.charAt(0).toLowerCase(); const syntaxName = syntax as "WEB" | "ANDROID" | "iOS"; const value = va.codeSyntax[syntaxName]; if (value) { if (i === 0) { paramsRaw[`variables.${key}.${syntaxKey}`] = value; params[`variables.${key}.${syntaxKey}`] = safeString(value); } paramsRaw[`variables.${key}.${i}.${syntaxKey}`] = value; params[`variables.${key}.${i}.${syntaxKey}`] = safeString(value); } } paramsRaw[`variables.${key}.${i}`] = va.name; params[`variables.${key}.${i}`] = safeString(va.name); } }); } } } if (autolayout) { const props: (keyof InferredAutoLayoutResult)[] = [ "layoutMode", "layoutWrap", "paddingLeft", "paddingRight", "paddingTop", "paddingBottom", "itemSpacing", "counterAxisSpacing", "primaryAxisAlignItems", "counterAxisAlignItems", ]; props.forEach((p) => { const val = autolayout[p] + ""; if (val !== "undefined" && val !== "null") { paramsRaw[`autolayout.${p}`] = val; params[`autolayout.${p}`] = safeString(val); } }); } return { params, paramsRaw, template: {} }; }
/** * Generate initial CodeSnippetParamsMap for a node, including autolayout, node, component, css, and variables. * Component property params are combined with this map later. * @param node node to generate initial params for * @returns Promise resolving an initial CodeSnippetParamsMap for the provided node */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L209-L323
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
isComponentPropertyDefinitionsObject
function isComponentPropertyDefinitionsObject( object: ComponentProperties | ComponentPropertyDefinitions ): object is ComponentPropertyDefinitions { return ( object[Object.keys(object)[0]] && "defaultValue" in object[Object.keys(object)[0]] ); }
/** * A util for typesafety that determines if an object * that can be ComponentProperties or ComponentPropertyDefinitions is the latter * @param object the object in question, ComponentProperties or ComponentPropertyDefinitions * @returns whether or not the object is ComponentProperties or ComponentPropertyDefinitions */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L331-L338
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
componentPropObjectFromNode
function componentPropObjectFromNode( node: BaseNode ): ComponentProperties | ComponentPropertyDefinitions { if (node.type === "INSTANCE") return node.componentProperties; if (node.type === "COMPONENT_SET") return node.componentPropertyDefinitions; if (node.type === "COMPONENT") { if (node.parent && node.parent.type === "COMPONENT_SET") { const initialProps = Object.assign( {}, node.parent.componentPropertyDefinitions ); const nameProps = node.name.split(", "); nameProps.forEach((prop) => { const [propName, propValue] = prop.split("="); initialProps[propName].defaultValue = propValue; }); return initialProps; } else { return node.componentPropertyDefinitions; } } return {}; }
/** * Finding the right component property value object from the current node. * @param node the node in question, ignored if not component-like. * @returns ComponentProperties or ComponentPropertyDefinitions */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L345-L367
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
capitalize
function capitalize(name: string) { return `${name.charAt(0).toUpperCase()}${name.slice(1)}`; }
/** * Uppercase the first character in a string * @param name the string to capitalize * @returns capitalized string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L374-L376
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09