Coder Social home page Coder Social logo

glassbricks / typed-factorio Goto Github PK

View Code? Open in Web Editor NEW
32.0 3.0 3.0 13.87 MB

Complete and featureful Typescript defintions for the Factorio modding API

License: MIT License

TypeScript 100.00%
factorio types typescript-to-lua typescript tstl modding

typed-factorio's Introduction

Typed Factorio

Complete and featureful typescript definitions for the Factorio modding lua API, for use with TypescriptToLua.

This project aims to provide type definitions are as complete as possible. The generator uses both the Factorio api docs JSON and manually defined additions.

Installation

To use in your TypescriptToLua project:

  1. Install this package: npm install typed-factorio

    • Note: When types are updated for a new factorio version, you will need to update this package.
  2. Add types for the stages used to tsconfig.json > compilerOptions > types. The available stages are "typed-factorio/settings", "typed-factorio/prototype", and "typed-factorio/runtime".

Example:

// in tsconfig.json
{
  "compilerOptions": {
+    "types": [ "typed-factorio/runtime" ]
  }
}

The stages used will select the global variables defined. You can include multiple stages, but there are some caveats. See Using multiple stages in the same project for more info.

Usage notes

Here are some notes on using the types:

Types for other stages

No matter which stage(s) are selected, type definitions for all stages are available in the modules "factorio:settings", "factorio:prototype", and "factorio:runtime":

import { BoolSettingDefinition } from "factorio:settings"
import { ItemPrototype } from "factorio:prototype"
import { LuaEntity } from "factorio:runtime"

You can also include just "typed-factorio" in your types field. This will include only global variables available to all stages.

data.extend() types

In the settings and prototype stages, the data global variable is available.

For performance reasons, data.extend() is by default loosely typed. To get full type checking, you can use specific types in one of the following ways:

// Use `satisfies` to check types:
data.extend([
  {
    type: "ammo-category",
    name: "foo",
  } satisfies AmmoCategory,
  {
    type: "item",
    name: "bar",
    // ...other fields
  } satisfies ItemPrototype,
])

// List types as a type argument to `extend`:
data.extend<AmmoCategory | ItemPrototype>([
  {
    type: "ammo-category",
    name: "foo",
  },
  {
    type: "item",
    name: "bar",
    // ...other fields
  },
])

// Use types on separate variables:
const fooCategory: AmmoCategory = {
  /* ... */
}
const barItem: ItemPrototype = {
  /* ... */
}
data.extend([fooCategory, barItem])

Factorio lualib modules

There are types for the following Factorio lualib modules:

  • util
  • mod-gui

These can be imported as modules:

import * as util from "util"

const foo = util.copy(bar)

If you wish to see types for more lualib modules, feel free to open an issue or pull request.

The global table

The global table (in the runtime stage) can have any shape, so it is not defined here. Instead, you can define it yourself:

  • Add declare const global: <Your type> in a .d.ts file included in your project, to apply it project-wide.
  • Add declare const global: {...} to each file where needed. This way, you can define only properties that each file specifically uses.

Using multiple stages in the same project

Every Factorio loading stage declares different global variables. To add types for multiple Factorio stages, you have a few options:

  1. Add multiple stages to the "types" field, e.g. "types": ["typed-factorio/prototype", "typed-factorio/runtime"]. This will define global variables for all stages selected. With this option, take care that you only use global variables available in the stages the code is run.
  2. Add only the runtime stage, then manually declare other global variables in files that use them. There are types in "factorio:common" to allow this:
    // -- For the prototype stage --
    import { PrototypeData, ActiveMods } from "factorio:common"
    declare const data: PrototypeData
    declare const mods: ActiveMods
    // The `settings` global variable is already declared in the runtime stage.
    // However, in the prototype stage _only_ `settings.startup` are available.
    // -- For the settings stage --
    import { SettingsData, ActiveMods } from "factorio:common"
    declare const data: SettingsData
    declare const mods: ActiveMods
  3. Use a separate tsconfig.json for each stage. In each tsconfig.json, add only files in that stage to the "include" field, e.g. include: ["src/control.ts"] for the runtime stage. However, this means you need to run tstl separately for each stage, and files shared by multiple stages will be compiled multiple times.

Type features

Here is some info on type features that you may find useful:

nil

The nil type is equivalent to undefined. A class attribute is marked as possibly nil if the read type is possibly nil. For properties where nil is possible on write, but not read, you can use undefined! or myNullableValue!, e.g. controlBehavior.parameters = undefined!.

Parameter Variants

Parameter tables with variants (having "additional attributes can be specified depending on type ...") are defined as a union of all variants. The type for a specific variant is prefixed with the variant name (e.g. AmmoDamageTechnologyModifier), or prefixed with "Other" for variants without extra properties (e.g. OtherTechnologyModifier).

Events

Event IDs (defines.events) hold type info for their corresponding event type and filters, which is used by various methods in script.

You can pass an event data type parameter to script.generate_event_name<T>(), and it will return a CustomEventId that includes type info.

Optional custominput name checking

You can optionally enable type-checking for custom input names (for script.on_event and CustomInputPrototype). To do so, specify names by extending the CustomInputNames interface like so:

declare module "factorio:common" {
  export interface CustomInputNames {
    "my-custom-input": any
  }
}

script.on_event("my-custom-input", () => {}) // type-checked

If not specified, CustomInputName defaults to just string.

Array-like classes

Classes that have an index operator, a length operator, and have an array-like structure subclass from (Readonly)Array. These are LuaInventory, LuaFluidBox, LuaTransportLine. This allows you to use these classes like arrays, e.g. having array methods and .length translating to the lua length operator. However, this means like typescript arrays, they are 0-indexed, not 1-indexed.

Read and write variants

For concepts that can take a table or array form, the main type (e.g. MapPosition) defines the table form, and an Array suffix (e.g. MapPositionArray) defines the array form. Concepts in a "read" position are in table form, and concepts in a "write" position may be either in table or array form (e.g. MapPosition | MapPositionArray). Concepts that include table-or-array concepts may have an additional Write variant (e.g. ScriptArea, ScriptAreaWrite).

Classes with subclasses

Some classes have attributes that only work for particular subclasses. For these classes (e.g. LuaEntity) there are specific types that you can optionally use:

  • A "Base" type (e.g. BaseEntity) which contains only members usable by all subclasses
  • Multiple subclass types, e.g. CraftingMachineEntity, which extends the base type with members specific to that subclass.

The original class name (e.g. LuaEntity) contains attributes for all subclasses.

For stricter types, use the Base type generally, and the specific subclass type when needed. You can also create your own type-narrowing functions:

function isCraftingMachineEntity(entity: BaseEntity): entity is CraftingMachineEntity {
  return entity.type === "crafting-machine"
}

LuaGuiElement

LuaGuiElement is broken up into a discriminated union, for each gui element type. Individual gui element types can be referred to by <Type>GuiElement, e.g. ButtonGuiElement.

Similarly, GuiSpec (the table passed to LuaGuiElement.add), is also a discriminated union. The type for a specific GuiSpec is <Type>GuiSpec, e.g. ListBoxGuiSpec. LuaGuiElement.add will return the appropriate gui element type corresponding to the GuiSpec type passed in.

This is done both to provide more accurate types, and for possible integration with JSX.

Support

If you find this project useful, consider tipping me on Kofi!

Buy Me a Coffee at ko-fi.com

typed-factorio's People

Contributors

asemy avatar emeiziying avatar glassbricks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

typed-factorio's Issues

CraftingMachinePrototype::fluid_boxes needs manual type def

I have not tried this project but I was taking a look through the files to see how people use our docs. I wanted to note that CraftingMachinePrototype::fluid_boxes needs a manual type definition, the machine readable docs don't include the off_when_no_fluid_recipe property. This is the case because we currently don't have a way to represent an array that also has a named key. This prototype property is the only place where this special format is used, everything else should be complete in the machine readable docs.

Request: Provide strong typing of numeric Builtin Types

At the moment all numeric types are Type Aliases of number. This means that there is no type-checking, so accidentally using the wrong type doesn't raise an compilation error.

function test(
    player: LuaPlayer
) {
  const position: MapEntityPosition = player.position
  const x1: double = position.x // correct
  const x2: uint = position.x // incorrect, x is not a uint

  const playerIndex1: uint = player.index // correct
  const playerIndex2: double = player.index // incorrect, index is not a double
}

Is it possible to make all numeric types type-safe, so const x2: uint = position.x creates a compilation error?

I've done a bit of research and I think a couple of the approaches described here Nominal Typing in Typescript might be the most intuitive and least intrusive, but I don't know if they are technically compatible with TypeScriptToLua.

type BuiltInNumeric<T extends "uint" | "double"> = number & { __precision: T }

type uint2 = BuiltInNumeric<"uint">
type double2 = BuiltInNumeric<"double">

function double2(value: number) { // util function
  return value as double2;
}

function test(
    playerIndex: uint2,
    playerXPos: double2
) {
  const x1: double2 = playerXPos // compiles
  const x2: uint2 = playerXPos // error, Type 'double2' is not assignable to type 'uint2'.

  const playerIndex1: uint2 = playerIndex // compiles
  const playerIndex2: double2 = playerIndex // error, Type 'uint2' is not assignable to type 'double2'.

  const fooX: double2 = 123 as double2
  const barX: double2 = double2(123)
  
  const bazX: uint2 = double2(123) // error
}

Add runtime equivalent of PrototypeMap

I have an LuaEntity and want to make something like

function isEntityType<T extends keyof EntityTypeMap>(type: T, entity: LuaEntity): entity is EntityTypeMap[T} {
  return entity.type === type;
}

to make sorta type autoinferring, but this requires something like PrototypeMap for factorio:runtime

What does this do over `factorio-type-kit`?

Hi,

Just found out we could use typescript to do mods now and I'm trying to figure which of those two options I should start my mod with and since you're the most recent one I figure I would ask here.

Why should I use this over factorio-type-kit.. like what was the motivation behind doing your own solution rather than using the other existing one?

Thanks!

Add `types` declaration to package.json

I wanted to try and use another tool to utilise the typed-factorio .d.ts files, but this requires that package.json has a types (or typings) field defined.

For example, TypeScriptToLua's package.json has:

    "types": "dist/index.d.ts",

The types field requires a single file of all the types. I see there's typed-factorio/runtime/index.d.ts, but as this references files from libraries, this might not be suitable? This task might require a specific index.d.ts file that only references typed-factorio files?

Thanks!

Issue with import in scenario.

Hi,

I have a problem that I can't seem to find a solution for when trying to add a scenario to a mod with import in it.

Factorio scenarios are placed in a scenarios folder and have their own control.lua.

There I have the following files.

./scenarios/ScenarioName/control.ts

/** @noResolution */
import main from './main';

import handler from 'event_handler';

handler.add_lib(main);

Which compile to

local ____exports = {}
local ____main = require("scenarios.ScenarioName.main") // THIS IS WRONG
local main = ____main.default
local ____event_handler = require("event_handler")
local handler = ____event_handler.default
handler.add_lib(main)
return ____exports

./scenarios/ScenarioName/main.ts

import * as util from 'util';

type EventHandlerSubscription = {
    events?: { [x: number]: (event: any) => void; },
};

const main: EventHandlerSubscription = {};

main.events = {
    [defines.events.on_player_created]: function(event: OnPlayerCreatedEvent) {
        game.print('Player was created' + util.color('red')); // this is just to test importing util
    },
    [defines.events.on_player_respawned]: function(event: OnPlayerRespawnedEvent) {
        game.print('Player was respawned');
    }
};

export default main;

Which compile to

local ____exports = {}
local util = require("util")
local main = {}
main.events = {
    [defines.events.on_player_created] = function(event)
        game.print(
            "Player was created caliss" .. tostring(
                util.color("red")
            )
        )
    end,
    [defines.events.on_player_respawned] = function(event)
        game.print("Player was respawned caliss")
    end
}
____exports.default = main
return ____exports

Notice how scenarios.ScenarioName.main is the required path when I import main instead of just being main.

@noResolution should force it to stay what it was in the ยญ.ts file but that won't work there for some reason.

I also tryed setting a rootdir for it in my tsconfig but not luck there either

{
  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "esnext"
    ],
    "moduleResolution": "node",
    "strict": true,
    "sourceMap": true,
    "types": [ "typed-factorio/runtime"  ],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "rootDirs": [
      "scenarios/ScenarioName"       <<--------
    ]
  },
  "tstl": {
    "luaTarget": "JIT",
    "noHeader": false,
    "noImplicitSelf": true,
    "sourceMapTraceback": false
  },
  "include": [
    "./**/*",
  ]
}

any idea?

Typechecked CustomEventName

// lib side:
declare module 'factorio:common' {
  export interface CustomEventMap {}
  // just `string` if not used
  export type CustomEventName = [keyof CustomEventMap] extends [never] ? string : keyof CustomEventMap
}
declare module 'factorio:runtime' {
  export interface LuaBootstrap {
    on_event(event: import('factorio:common').CustomEventName, f: ((data: CustomInputEvent) => void) | nil): void
  }
}
declare module 'factorio:prototype' {
  export interface CustomInputPrototype {
    name: import('factorio:common').CustomEventName
  }
}
// user side:
declare module 'factorio:common' {
  export interface CustomEventMap {
    'dish-kruise-run': true
  }
}
data.extend<CustomInputPrototype>([{
  name: 'dish-kruise-run', // <-- typechecked & autocompleted
  type: 'custom-input',
  key_sequence: 'mouse-button-3',
}])
script.on_event(
  'dish-kruise-run', // <-- typechecked & autocompleted
  () => {},
)

Subtypes for `LuaEntity` that follow the "Can only be used if this is <Prototype>" documentation

Hi, I've got another request that might or might not fit in with the excellent work so far.

Some properties and functions in LuaEntity are documented as only being available for certain prototypes. For example, amount, initial_amount, and deplete() are only available when the prototype is ResourceEntity.

I'm asking because I want to find all entities of a specific type (resources, trees, buildings, biters...) in a chunk, and map each to a JSON object. I'd find that easier to do if I could do a type-check and then only the relevant fields are available, rather than going back and forth to verify it manually. Of course it's not a significant problem - but I wanted to make a request in case you think it's workable.

I think for backwards compatibility reasons LuaEntity should keep the 'Can only be used if' properties - but can they be changed to be optional? E.g. amount: uint -> amount: uint | undefined and deplete(): void -> deplete?():void

Usage demo

Here's a quick demo showing how the code would work after the changes

function handleLuaEntity(entity: TypedLuaEntity) {

  if (entity.entity_type == "resource") {
    handleResourceEntity(
        entity.amount, // no error
    )

    entity.deplete() // no error
  }
  if (entity.entity_type == "radar") {
    handleRadarEntity(
        entity.radar_scan_progress, // doesn't cause error: Type 'undefined' is not assignable to
                                    // type 'number'.
    )

    entity.deplete() // error: Cannot invoke an object which is possibly 'undefined'.
  }
}

function handleResourceEntity(amount: uint) {
  // ...
}

function handleRadarEntity(radar_scan_progress: float) {
  // ...
}

Library changes demo

And here's a quick demo of the library changes, in case this is more illuminating.

TypedLuaEntity would be a type-union of all the prototype names that are in the the documentation. I count 45 distinct "Can only be used if this is" references in the LuaEntity docs.

// union of all LuaEntity subtypes (can be scraped from the docs?)
type TypedLuaEntity =
    | ResourceLuaEntity
    | RadarLuaEntity

interface LuaEntity {

  // ...

  // change these properties and function to be marked as optional - override them in the subtypes
  deplete?(): void
  
  amount: uint  | undefined
  radar_scan_progress: float | undefined
}

interface ResourceLuaEntity extends LuaEntity {
  entity_type: "resource" // required for discriminating TypedLuaEntity

  deplete(): void 

  amount: uint 
}

interface RadarLuaEntity extends LuaEntity {
  entity_type: "radar" // required for discriminating TypedLuaEntity

  radar_scan_progress: float
}

Require of different mod with Lua snippet (Lua API global Variable Viewer (gvv))

Hi there,

First of all, huge thank you for all the work you have been doing for typed-factorio!

I'm currently developing a mod which I would like to debug by using: https://mods.factorio.com/mod/gvv

The mod requires the use of the following lua snippet:

    if script.active_mods["gvv"] then
        require("__gvv__.gvv")()
    end

I have been struggeling but so far I have managed to get it working by doing the following:

//debug.lua
local debug = {}

function debug:setup_gvv()
    if script.active_mods["gvv"] then
        require("__gvv__.gvv")()
    end
end

return debug
// control.ts
setup_gvv();

This works and I am able to use GVV succesfully. However I keep receiving the following error in the console of my IDE

error TSTL: Could not resolve lua source files for require path '__gvv__.gvv' in file debug.lua.

Am I importing it wrong or is there a different way to translate the Lua snippet to Typescript?

Very much thank you in advance!

`Color` - unable to access rgba fields

I have a LuaPlayer variable, and I'd like to access the rgba fields of player.color. However I'm unable to do this - the fields are not resolvable.

  export function playerToTable(player: LuaPlayer): PlayerData {
    
    player.color.r // Unresolved variable r
    player.color.g // Unresolved variable g 
    player.color.b // Unresolved variable b
    player.color.a // Unresolved variable a 

    //...
  }

I'm sure there's an easy way to do this, I'm just not familiar enough with TypeScript to figure it out :) But it would be nice to be able to access the rgba fields without having to determine whether player.color is a ColorTable or a ColorArray

If an improvement is possible, I think ColorModifier, Position, ChunkPosition, TilePosition, BoundingBox, and GuiLocation, would also benefit from the same improvement.

reading `LuaControl.force` should only return `LuaForce`, not `LuaForce | string`

At the moment, reading LuaControl.force returns either a string or LuaForce, but it should only return a LuaForce.

  const player = game.players[playerIndex]
  
  const force : LuaForce = player.force
  // ERROR 
  // TS2322: Type 'ForceIdentification' is not assignable to type 'LuaForce'. 
  // Type 'string' is not assignable to type 'LuaForce'.

However, assigning a string should be possible.

I think this is probably true anywhere that ForceIdentification can be read, but that's a guess. At a minimum it's also documented as the case for

  • LuaControl.force
  • LuaEntity.render_to_forces
  • BaseEntity.render_to_forces

I also guess this is similar to #7

This is a really minor issue, it's not disrupting me, it's just something I noticed.

https://lua-api.factorio.com/latest/LuaControl.html#LuaControl.force

The force of this entity. Reading will always give a LuaForce, but it is possible to assign either string or LuaForce to this attribute to change the force.

Add definition for `global` variable

// lib
declare global {
  interface LuaGlobal {
    // empty. Use interface merging to extend.
  }
  const global: LuaGlobal
}

// usage
declare global {
  interface LuaGlobal {
    savedData: string
  }
}
global.savedData = 'foo'

node_modules/typed-factorio/generated/classes.d.ts(261,3): error TS2304: Cannot find name 'https'.

Hi, I'm getting a new error after updating to v1.1.0.

If I downgrade to v1.0.0 it works correctly, no errors.

TSTL seems to run okay, but something fails on the last step.

Including lualib bundle
Emitting output
Emitting ...
Emitting ...
Emitting ...
Emitting ...
Emit finished!
node_modules/typed-factorio/generated/classes.d.ts(238,3): error TS2304: Cannot find name 'https'.
node_modules/typed-factorio/generated/classes.d.ts(261,3): error TS2304: Cannot find name 'https'.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: `tstl "--outDir" "my-project\build\tmp\typescriptToLua"`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     ...\npm-cache\_logs\2022-05-14T11_30_03_008Z-debug.log
...
package.json
{
  "name": "my-factorio-mod",
  "version": "0.5.0",
  "private": true,
  "scripts": {
    "build": "tstl",
    "dev": "tstl --watch"
  },
  "engines": {
    "node": "~14.19.1"
  },
  "devDependencies": {},
  "dependencies": {
    "lua-types": "^2.11.0",
    "typescript-to-lua": "1.4.4",
    "typed-factorio": "1.1.0",
    "typescript": "4.6.4"
  },
  "license": "UNLICENSED",
  "peerDependencies": {},
  "optionalDependencies": {},
  "bundledDependencies": []
}
tsconfig.json
{
  "$schema": "https://raw.githubusercontent.com/TypeScriptToLua/vscode-typescript-to-lua/master/tsconfig-schema.json",
  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "esnext"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "types": [
      "typescript-to-lua/language-extensions",
      "lua-types/5.2",
      "typed-factorio/runtime"
    ],
    "plugins": [
      {
        "name": "typescript-tstl-plugin"
      }
    ],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "explainFiles": true,
    "forceConsistentCasingInFileNames": true,
    "listEmittedFiles": true,
    "listFiles": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "sourceMap": false,
    "strict": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "traceResolution": true,
    "noImplicitReturns": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true
  },
  "tstl": {
    "luaTarget": "5.2",
    "tstlVerbose": true,
    "noHeader": true,
    "noImplicitSelf": true,
    "luaLibImport": "require"
  }
}
npm-cache log
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '..\\my-project\\.gradle\\nodejs\\node-v14.19.1-win-x64\\node.exe',
1 verbose cli   '..\\my-project\\.gradle\\nodejs\\node-v14.19.1-win-x64\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build',
1 verbose cli   '--',
1 verbose cli   '--outDir',
1 verbose cli   '..\\my-project\\build\\tmp\\typescriptToLua'
1 verbose cli ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle [email protected]~prebuild: [email protected]
6 info lifecycle [email protected]~build: [email protected]
7 verbose lifecycle [email protected]~build: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~build: PATH: ..\my-project\.gradle\nodejs\node-v14.19.1-win-x64\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;..\my-project\src\main\typescript\node_modules\.bin;..\my-project\.gradle\nodejs\node-v14.19.1-win-x64;..\my-project\.gradle\nodejs\node-v14.19.1-win-x64;C:\ProgramData\scoop\apps\temurin-lts-jdk\current\bin;C:\ProgramData\scoop\shims;...
9 verbose lifecycle [email protected]~build: CWD: ..\my-project\src\main\typescript
10 silly lifecycle [email protected]~build: Args: [
10 silly lifecycle   '/d /s /c',
10 silly lifecycle   'tstl "--outDir" "..\\my-project\\build\\tmp\\typescriptToLua"'
10 silly lifecycle ]
11 silly lifecycle [email protected]~build: Returned: code: 2  signal: null
12 info lifecycle [email protected]~build: Failed to exec build script
13 verbose stack Error: [email protected] build: `tstl "--outDir" "..\my-project\build\tmp\typescriptToLua"`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (..\my-project\.gradle\nodejs\node-v14.19.1-win-x64\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:400:28)
13 verbose stack     at ChildProcess.<anonymous> (..\my-project\.gradle\nodejs\node-v14.19.1-win-x64\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:400:28)
13 verbose stack     at maybeClose (internal/child_process.js:1058:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:293:5)
14 verbose pkgid [email protected]
15 verbose cwd ..\my-project\src\main\typescript
16 verbose Windows_NT 10.0.19044
17 verbose argv "..\\my-project\\.gradle\\nodejs\\node-v14.19.1-win-x64\\node.exe" "..\\my-project\\.gradle\\nodejs\\node-v14.19.1-win-x64\\node_modules\\npm\\bin\\npm-cli.js" "run" "build" "--" "--outDir" "..\\my-project\\build\\tmp\\typescriptToLua"
18 verbose node v14.19.1
19 verbose npm  v6.14.16
20 error code ELIFECYCLE
21 error errno 2
22 error [email protected] build: `tstl "--outDir" "..\my-project\build\tmp\typescriptToLua"`
22 error Exit status 2
23 error Failed at the [email protected] build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Feature request: Get the name of an event as a string

At the moment I'm processing events from Factorio

script.on_event(
    defines.events.on_player_mined_entity,
    (e: OnPlayerMinedEntityEvent) => {
      handlePlayerUpdate(e.tick, e.player_index, "on_player_mined_entity")
      handleEntityUpdate(e.tick, e.entity, "on_player_mined_entity")
    }
)

I'd like to be able to do something like e.event_name which will return a string, "on_player_mined_entity".

I've tried e.name, but that returns another object, not the name.

Maybe this is already possible and I don't know how to do it in TypeScript :)

A question about Icons

So I am not sure if this is only me, but I couldn't find an "icon" or "icons" property for the prototypes I've been trying out. I gave the type definitions files a good search and I haven't found a definition for any "icons" property except for something related to blueprints. I also tried the BaseEntity type but it didn't have them either.

Also I apologize for my bad way of writing this, as this is the first Issue that I made.
Thank you in advance

Alternative to `satisfies`

In my opinion, you don't do like

data.extend([
   {
     type: "ammo-category",
     name: "foo",
   } satisfies AmmoCategory,
   { 
     type: "item",
     name: "bar",
     // other fields...
   } satisfies ItemPrototype,
])

You do like

data.extend<AmmoCategory | ItemPrototype>([
   {
     type: "ammo-category",
     name: "foo",
   },
   { 
     type: "item",
     name: "bar",
     // other fields...
   },
])

This is more simple if you have one type and many items

Consider adding this as an option in readme

LuaEntity name is "inserter" | "filter-inserter"

Hey. I'm new to Typescript and Lua so I might be mistaken but I thought I'd write a quick issue just in case.

LuaEntity has a name field, but I think it should be any string, not just limited to inserter or filter-inserter.

node_modules\typed-factorio\generated\classes.d.ts line 2394

  /**
   * Name of the entity prototype. E.g. "inserter" or "filter-inserter".
   *
   * {@link https://lua-api.factorio.com/next/LuaEntity.html#LuaEntity.name View documentation}
   */
  readonly name: "inserter" | "filter-inserter"

I have typed-factorio version 0.7.3

image

Proto-types?

sguest has typings for prototypes as well. Would you consider integrating them here?

Cannot use table.deepcopy imported from util

I'm trying to use table.deepcopy, this is what I tried so far:

import { table } from "util"
table.deepcopy(someTable)

The above code gets transpiled into this:

local ____util = require("util")
local ____table = ____util.table

____table.deepcopy(someTable)

The variable ____table is nil in the Lua code.
How can I extend the table type with the table namespace from util?

Make a `create-typed-factorio` package

I would like to be able to easily create a new mod by just typing yarn create typed-factorio

So I would have a set-up directory with

  • package.json scripts (watch, build)
  • all the basic lua scripts (data, data-fixes, runtime)
  • a simple readme
  • a simple changelog
    without bothering with configuration

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.